repo_name
stringlengths
6
112
path
stringlengths
4
204
copies
stringlengths
1
3
size
stringlengths
4
6
content
stringlengths
714
810k
license
stringclasses
15 values
BradyHammond/Topic_Modeler
visualization.py
1
5384
"""==================================================""" """ VISUALIZATION """ """==================================================""" """ AUTHOR: Brady Hammond """ """ CREATED: 09/26/17 """ """ EDITED BY: ----- """ """ EDITED: --/--/-- """ """==================================================""" """ FILE SETUP """ """==================================================""" import logging import matplotlib.pyplot as pyplot from wordcloud import WordCloud import word_cloud_color """==================================================""" """ CLASS DEFINITIONS """ """==================================================""" class visualizerObject(object): def __init__(self, top_point_one_percent, top_point_two_five_percent, top_point_five_percent, mallet, word_clouds_directory, distributions, documents, scatter_plot_directory): self.top_point_one_percent = top_point_one_percent self.top_point_two_five_percent = top_point_two_five_percent self.top_point_five_percent = top_point_five_percent self.mallet = mallet self.word_clouds_directory = word_clouds_directory self.distributions = distributions self.documents = documents self.scatter_plot_directory = scatter_plot_directory # ================================================== def setScatterPlotDirectory(self, scatter_plot_directory): self.scatter_plot_directory = scatter_plot_directory # ================================================== def setWordCloudDirectory(self, word_clouds_directory): self.word_clouds_directory = word_clouds_directory # ================================================== def generateWordClouds(self, number, model): word_cloud = WordCloud( background_color="white", max_words=100, width=1024, height=1024, ) color_to_words = { "#2bf72d": self.top_point_one_percent, "#9e40ed": self.top_point_two_five_percent, "#103ffb": self.top_point_five_percent } default_color = "black" grouped_color_function = word_cloud_color.GroupedColorFunc(color_to_words, default_color) if self.mallet == True: tuples = model.show_topic(number, num_words=100) frequency_dictionary = dict([(entry[1], entry[0]) for entry in tuples]) for key in frequency_dictionary.keys(): if frequency_dictionary[key] == 0.0: frequency_dictionary[key] = 0.00001 else: tuples = model.show_topic(number, topn=100) frequency_dictionary = dict(tuples) for key in frequency_dictionary.keys(): if frequency_dictionary[key] == 0.0: frequency_dictionary[key] = 0.00001 try: word_cloud.generate_from_frequencies(frequency_dictionary) word_cloud.recolor(color_func=grouped_color_function) word_cloud.to_file(self.word_clouds_directory + "/word_cloud_" + str(number + 1) + ".png") except Exception as exception: logging.info(exception) # ================================================== def generateScatterPlots(self, number): document_saturations = [] for distribution in self.distributions: document_saturations.append(distribution[number][1]) x = range(0, len(self.documents)) figure = pyplot.figure(figsize=(10, 5), dpi=100) figure.suptitle("Topic " + str(number + 1) + " Distribution", fontsize=14) figure.add_subplot(1, 1, 1) ''' *** Add Document Titles to Scatter Plots *** if self.chunk_size_input.text().lower() == "document": pyplot.xticks(x, self.documents, rotation="vertical") else: ticks = [] for i in range(len(self.documents) - 1): if i == (len(self.documents) - 1): ticks.append(re.sub("_\d*$", "", self.documents[i])) elif re.sub("_\d*$", "", self.documents[i]) == re.sub("_\d*$", "", self.documents[i+1]): ticks.append(self.documents[i]) else: ticks.append(re.sub("_\d*$", "", self.documents[i])) pyplot.xticks(x, ticks, rotation="vertical") axes = pyplot.axes() for label in axes.xaxis.get_ticklabels(): if re.search("_\d*$", label.get_text()): label.set_visible(False) axes.xaxis.set_ticks_position("none") ''' for label in pyplot.axes().xaxis.get_ticklabels(): label.set_visible(False) pyplot.axes().xaxis.set_ticks_position("none") pyplot.scatter(x, document_saturations, alpha=0.8, color="#3097d1") pyplot.savefig(self.scatter_plot_directory + "/scatter_plot_" + str(number + 1) + ".png") pyplot.clf() pyplot.close() """==================================================""" """ EOF """ """=================================================="""
gpl-3.0
openfisca/openfisca-qt
openfisca_qt/scripts/validation/check_consistency_tests.py
1
4125
# -*- coding:utf-8 -*- # Created on 17 févr. 2013 # This file is part of OpenFisca. # OpenFisca is a socio-fiscal microsimulation software # Copyright © #2013 Clément Schaff, Mahdi Ben Jelloul # Licensed under the terms of the GVPLv3 or later license # (see openfisca/__init__.py for details) from openfisca_core import model from openfisca_core.columns import EnumCol from openfisca_core.simulations import SurveySimulation from pandas import concat def check_entities(simulation): is_ok = True message = None survey = simulation.survey for entity in model.ENTITIES_INDEX: id = survey.table['id' + entity] head = survey.table['qui' + entity] df = concat([id, head],axis=1) grouped_by_id = df.groupby(id) def is_there_head(group): dummy = (group == 0).sum() return dummy headcount = grouped_by_id["qui"+entity].aggregate({entity + " heads" : is_there_head}) result = headcount[headcount[entity + " heads"] != 1] if len(result) != 0: is_ok = False return is_ok, message def check_inputs_enumcols(simulation): """ Check that the enumcols are consistent with data in the survey dataframe Parameters ---------- simulation : SurveySimulation The simulation to check Returns ------- is_ok : bool True or False according to tests message : string """ # TODO: eventually should be a method of SurveySimulation specific for france is_ok = True message = None survey = simulation.input_table for var, varcol in survey.column_by_name.iteritems(): if isinstance(varcol, EnumCol): try: x = sorted(varcol.enum._nums.values()) if set(survey.table[var].unique()) > set(varcol.enum._nums.values()): print "Wrong nums for %s" %var print varcol.enum._nums print sorted(survey.table[var].unique()) is_ok = False except: is_ok = False print var print "Wrong nums" print varcol.enum print sorted(survey.table[var].unique()) print "\n" try: x = varcol.enum._vars except: is_ok = False print var print "wrong vars" print varcol.enum print sorted(survey.table[var].unique()) print "\n" return is_ok, message def check_weights(simulation): """ Check weights positiveness Parameters ---------- simulation : SurveySimulation The simulation to check Returns ------- is_ok : boolean True or False according to tests message : string, None if is_ok is True error message """ is_ok = True message = None survey = simulation.survey WEIGHT = model.WEIGHT weight = survey.get_value(WEIGHT) nb = sum(weight<=0) if nb != 0: is_ok = False message = "%i weights are less than or equal to zero" % nb return is_ok, message def toto(simulation): survey = simulation.survey # verifying the age of childrens quifam = survey.get_value('quifam') age = survey.get_value('age') if sum((quifam >= 2) & (age >= 21)) != 0: print "they are kids that are of age >= 21" # Problemes # enfants de plus de 21 ans et parents à charge dans les familles avec quifam=0 # idmen = survey.get_value('idmen') # from numpy import max as max_ # print max_(idmen) if __name__ == '__main__': year = 2006 simulation = SurveySimulation() simulation.set_config(year = year) simulation.set_param() simulation.set_survey() ok, message = check_inputs_enumcols(simulation) if not ok: print message ok, message = check_entities(simulation) if not ok: print message ok, message = check_weights(simulation) if not ok: print message
agpl-3.0
xguse/bokeh
bokeh/charts/_data_adapter.py
43
8802
"""This is the Bokeh charts interface. It gives you a high level API to build complex plot is a simple way. This is the ChartObject class, a minimal prototype class to build more chart types on top of it. It provides the mechanisms to support the shared chained methods. """ #----------------------------------------------------------------------------- # Copyright (c) 2012 - 2014, Continuum Analytics, Inc. All rights reserved. # # Powered by the Bokeh Development Team. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from __future__ import absolute_import from six import string_types from collections import OrderedDict from ..properties import bokeh_integer_types, Datetime try: import numpy as np except ImportError: np = None try: import pandas as pd except ImportError: pd = None try: import blaze except ImportError: blaze=None #----------------------------------------------------------------------------- # Classes and functions #----------------------------------------------------------------------------- DEFAULT_INDEX_ALIASES = list('abcdefghijklmnopqrstuvz1234567890') DEFAULT_INDEX_ALIASES += list(zip(DEFAULT_INDEX_ALIASES, DEFAULT_INDEX_ALIASES)) class DataAdapter(object): """ Adapter object used to normalize Charts inputs to a common interface. Supported inputs are dict, list, tuple, np.ndarray and pd.DataFrame. """ def __init__(self, data, index=None, columns=None, force_alias=True): self.__values = data self._values = self.validate_values(data) self.convert_index_to_int = False self._columns_map = {} self.convert_items_to_dict = False if columns is None and force_alias: # no column 'labels' defined for data... in this case we use # default names keys = getattr(self._values, 'keys', None) if callable(keys): columns = list(keys()) elif keys is None: columns = list(map(str, range(len(data)))) else: columns = list(keys) if columns: self._columns = columns # define a mapping between the real keys to access data and the aliases # we have defined using 'columns' self._columns_map = dict(zip(columns, self.keys())) if index is not None: self._index = index self.convert_items_to_dict = True elif force_alias: _index = getattr(self._values, 'index', None) # check because if it is a callable self._values is not a # dataframe (probably a list) if _index is None: indexes = self.index if isinstance(indexes[0], int): self._index = DEFAULT_INDEX_ALIASES[:][:len(self.values()[0])] self.convert_items_to_dict = True elif not callable(_index): self._index = list(_index) self.convert_items_to_dict = True else: self._index = DEFAULT_INDEX_ALIASES[:][:len(self.values()[0])] self.convert_items_to_dict = True @staticmethod def is_number(value): numbers = (float, ) + bokeh_integer_types return isinstance(value, numbers) @staticmethod def is_datetime(value): try: dt = Datetime(value) dt # shut up pyflakes return True except ValueError: return False @staticmethod def validate_values(values): if np and isinstance(values, np.ndarray): if len(values.shape) == 1: return np.array([values]) else: return values elif pd and isinstance(values, pd.DataFrame): return values elif isinstance(values, (dict, OrderedDict)): if all(DataAdapter.is_number(x) for x in values.values()): return values return values elif isinstance(values, (list, tuple)): if all(DataAdapter.is_number(x) for x in values): return [values] return values elif hasattr(values, '__array__'): values = pd.DataFrame(np.asarray(values)) return values # TODO: Improve this error message.. raise TypeError("Input type not supported! %s" % values) def index_converter(self, x): key = self._columns_map.get(x, x) if self.convert_index_to_int: key = int(key) return key def keys(self): # assuming it's a dict or dataframe keys = getattr(self._values, "keys", None) if callable(keys): return list(keys()) elif keys is None: self.convert_index_to_int = True indexes = range(len(self._values)) return list(map(str, indexes)) else: return list(keys) def __len__(self): return len(self.values()) def __iter__(self): for k in self.keys(): yield k def __getitem__(self, key): val = self._values[self.index_converter(key)] # if we have "index aliases" we need to remap the values... if self.convert_items_to_dict: val = dict(zip(self._index, val)) return val def values(self): return self.normalize_values(self._values) @staticmethod def normalize_values(values): _values = getattr(values, "values", None) if callable(_values): return list(_values()) elif _values is None: return values else: # assuming it's a dataframe, in that case it returns transposed # values compared to it's dict equivalent.. return list(_values.T) def items(self): return [(key, self[key]) for key in self] def iterkeys(self): return iter(self) def itervalues(self): for k in self: yield self[k] def iteritems(self): for k in self: yield (k, self[k]) @property def columns(self): try: return self._columns except AttributeError: return list(self.keys()) @property def index(self): try: return self._index except AttributeError: index = getattr(self._values, "index", None) if not callable(index) and index is not None: # guess it's a pandas dataframe.. return index # no, it's not. So it's probably a list so let's get the # values and check values = self.values() if isinstance(values, dict): return list(values.keys()) else: first_el = self.values()[0] if isinstance(first_el, dict): indexes = list(first_el.keys()) else: indexes = range(0, len(self.values()[0])) self._index = indexes return indexes #----------------------------------------------------------------------------- # Convenience methods #----------------------------------------------------------------------------- @staticmethod def get_index_and_data(values, index=None): """Parse values (that must be one of the DataAdapter supported input types) and create an separate/create index and data depending on values type and index. Args: values (iterable): container that holds data to be plotted using on the Chart classes Returns: A tuple of (index, values), where: ``index`` is an iterable that represents the data index and ``values`` is an iterable containing the values to be plotted. """ _values = DataAdapter(values, force_alias=False) if hasattr(values, 'keys'): if index is not None: if isinstance(index, string_types): xs = _values[index] else: xs = index else: try: xs = _values.index except AttributeError: xs = values.index else: if index is None: xs = _values.index elif isinstance(index, string_types): xs = _values[index] else: xs = index return xs, _values
bsd-3-clause
shikhardb/scikit-learn
doc/tutorial/text_analytics/skeletons/exercise_01_language_train_model.py
254
2005
"""Build a language detector model The goal of this exercise is to train a linear classifier on text features that represent sequences of up to 3 consecutive characters so as to be recognize natural languages by using the frequencies of short character sequences as 'fingerprints'. """ # Author: Olivier Grisel <[email protected]> # License: Simplified BSD import sys from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import Perceptron from sklearn.pipeline import Pipeline from sklearn.datasets import load_files from sklearn.cross_validation import train_test_split from sklearn import metrics # The training data folder must be passed as first argument languages_data_folder = sys.argv[1] dataset = load_files(languages_data_folder) # 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.5) # TASK: Build a an vectorizer that splits strings into sequence of 1 to 3 # characters instead of word tokens # TASK: Build a vectorizer / classifier pipeline using the previous analyzer # the pipeline instance should stored in a variable named clf # TASK: Fit the pipeline on the training set # TASK: Predict the outcome on the testing set in a variable named y_predicted # Print the classification report print(metrics.classification_report(y_test, y_predicted, target_names=dataset.target_names)) # Plot the confusion matrix cm = metrics.confusion_matrix(y_test, y_predicted) print(cm) #import pylab as pl #pl.matshow(cm, cmap=pl.cm.jet) #pl.show() # Predict the result on some short new sentences: sentences = [ u'This is a language detection test.', u'Ceci est un test de d\xe9tection de la langue.', u'Dies ist ein Test, um die Sprache zu erkennen.', ] predicted = clf.predict(sentences) for s, p in zip(sentences, predicted): print(u'The language of "%s" is "%s"' % (s, dataset.target_names[p]))
bsd-3-clause
BhallaLab/moose
moose-core/python/moose/recording.py
4
4690
# -*- coding: utf-8 -*- from __future__ import print_function try: from future_builtins import zip except ImportError: pass from . import moose as _moose _tick = 8 _base = '/_utils' _path = _base + '/y{0}' _counter = 0 _plots = [] _moose.Neutral( _base ) _defaultFields = { _moose.Compartment : 'Vm', _moose.ZombieCompartment : 'Vm', _moose.HHChannel: 'Gk', _moose.ZombieHHChannel: 'Gk', _moose.HHChannel2D: 'Gk', _moose.SynChan: 'Gk', _moose.CaConc: 'Ca', _moose.ZombieCaConc: 'Ca', _moose.Pool: 'conc', _moose.ZombiePool: 'conc', _moose.ZPool: 'conc', _moose.BufPool: 'conc', _moose.ZombieBufPool: 'conc', _moose.ZBufPool: 'conc', _moose.FuncPool: 'conc', _moose.ZombieFuncPool: 'conc', _moose.ZFuncPool: 'conc', } def _defaultField( obj ): return _defaultFields[ type( obj ) ] def setDt( dt ): '''----------- Description ----------- Sets time-step for recording values. --------- Arguments --------- dt: Time-step for recording values. ------- Returns ------- Nothing.''' _moose.setClock( _tick, dt ) class SetupError( Exception ): pass def _time( npoints = None ): import numpy if npoints is None: try: npoints = len( _plots[ 0 ].vec ) except IndexError: raise SetupError( 'List of time-points cannot be constructed because ' 'no plots have been set up yet.' ) begin = 0.0 end = _moose.Clock( '/clock' ).currentTime return numpy.linspace( begin, end, npoints ) class _Plot( _moose.Table ): def __init__( self, path, obj, field, label ): _moose.Table.__init__( self, path ) self._table = _moose.Table( path ) self.obj = obj self.field = field self.label = label @property def values( self ): return self._table.vec @property def size( self ): return len( self.values ) @property def time( self ): return _time( self.size ) def __iter__( self ): return iter( self.values ) def record( obj, field = None, label = None ): ''' ''' global _counter # Checking if object is an iterable like list or a tuple, but not a string. if hasattr( obj, '__iter__' ): return [ record( o, field, label ) for o in obj ] if isinstance( obj, str ): obj = _moose.element( obj ) if field is None: field = _defaultField( obj ) path = _path.format( _counter ) _counter += 1 p = _Plot( path, obj, field, label ) _plots.append( p ) _moose.connect( p, "requestData", obj, 'get_' + field ) _moose.useClock( _tick, path, "process" ) return p def _label( plot, labelFormat = '{path}.{field}' ): # Over-ride label format if label has been given explicitly. if plot.label: labelFormat = plot.label return labelFormat.format( path = plot.obj.path, name = plot.obj.name, field = plot.field ) def _selectedPlots( selected ): if selected is None: # Returning a copy of this list, instead of reference. The returned # list will be manipulated later. return _plots[ : ] elif isinstance( selected, _Plot ): return [ selected ] else: return selected def saveCSV( fileName, selected = None, delimiter = '\t', header = True, headerCommentCharacter = '#', labelFormat = '{path}.{field}', timeCol = True, timeHeader = 'Time', fileMode = 'w' ): ''' ''' import csv plots = _selectedPlots( selected ) if header: header = [] if timeCol: header.append( timeHeader ) for plot in plots: header.append( _label( plot, labelFormat ) ) header[ 0 ] = headerCommentCharacter + header[ 0 ] if timeCol: plots.insert( 0, _time() ) with open( fileName, fileMode ) as fout: writer = csv.writer( fout, delimiter = delimiter ) if header: writer.writerow( header ) writer.writerows( list(zip( *plots )) ) def saveXPLOT( fileName, selected = None, labelFormat = '{path}.{field}', fileMode = 'w' ): ''' ''' plots = _selectedPlots( selected ) with open( fileName, fileMode ) as fout: write = lambda line: fout.write( line + '\n' ) for ( i, plot ) in enumerate( plots ): label = '/plotname ' + _label( plot, labelFormat ) if i > 0: write( '' ) write( '/newplot' ) write( label ) for value in plot: write( str( value ) ) def show( selected = None, combine = True, labelFormat = '{path}.{field}', xLabel = 'Time (s)', yLabel = '{field}' ): ''' ''' try: from matplotlib import pyplot as plt except ImportError: print("Warning: recording.show(): Cannot find 'matplotlib'. Not showing plots.") return plots = _selectedPlots( selected ) if combine: plt.figure() for plot in plots: if not combine: plt.figure() print(_label(plot)) plt.plot( plot.time, plot.values, label = _label( plot ) ) plt.legend() plt.show() def HDF5(): pass
gpl-3.0
ckinzthompson/biasd
biasd/gui/posterior.py
1
3373
# -*- coding: utf-8 -*-® ''' GUI written in QT5 to perform ... ''' from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QComboBox, QLabel, QLineEdit, QMessageBox, QMainWindow, QShortcut, QSpinBox, QGroupBox, QSizePolicy, QFileDialog from PyQt5.QtGui import QStandardItemModel, QStandardItem from PyQt5.QtCore import Qt # Make sure that we are using QT5 import matplotlib matplotlib.use('Qt5Agg') from matplotlib.backends.backend_qt5agg import FigureCanvas import sys import biasd as b import numpy as np from smd_loader import ui_loader class posterior(QWidget): def __init__(self,parent): super(QWidget,self).__init__(parent=parent) self.initialize() def initialize(self): self.vbox = QVBoxLayout() hbox = QHBoxLayout() bcorner = QPushButton("&Choose Posterior") bcorner.clicked.connect(self.load_posterior) bsave = QPushButton("&Save Figure") bsave.clicked.connect(self.savefig) hbox.addWidget(bcorner) hbox.addWidget(bsave) hbox.addStretch(1) self.vbox.addLayout(hbox) self.vbox.addStretch(1) self.setLayout(self.vbox) self.setMinimumSize(800,800) self.setGeometry(200,0,800,800) self.setWindowTitle('View Posteriors') self.show() def savefig(self): oname = QFileDialog.getSaveFileName(self,"Save Figure",'./','jpg (*.jpg);;png (*.png);;pdf (*.pdf);;eps (*.eps)') self.setFocus() try: self.fig.print_figure(oname[0]) # B/c it's a canvas not a figure.... except: QMessageBox.critical(None,"Could Not Save","Could not save file: %s\n."%(oname[0])) def get_smd_filename(self): return self.parent().parent().get_smd_filename() def load_posterior(self): try: self.loader.close() except: pass self.loader = ui_loader(self,select=True) self.loader.show() def select_callback(self,location): self.loader.close() self.ploc = location self.plot_corner() def plot_corner(self): fn = self.get_smd_filename() f = b.smd.load(fn) g = f[self.ploc] if g.attrs.keys().count('description') > 0: if g.attrs['description'] == "BIASD MCMC result": r = b.smd.read.mcmc(g) f.close() s = r.chain maxauto = np.max((1,int(r.acor.max()))) s = s[:,::maxauto] s = s.reshape((s.shape[0]*s.shape[1],5)) self.new_corner(s) return elif g.attrs['description'] == 'BIASD Laplace posterior': r = b.smd.read.laplace_posterior(g) s = np.random.multivariate_normal(r.mu,r.covar,size=10000) self.new_corner(s) return print 'This is not a posterior...' def new_corner(self,s): try: self.fig.close() except: pass self.fig = FigureCanvas(b.mcmc.plot_corner(s)) self.fig.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding) self.vbox.addWidget(self.fig) def keyPressEvent(self,event): if event.key() == Qt.Key_Escape: self.parent().close() elif event.key() == Qt.Key_C: self.load_posterior() elif event.key() == Qt.Key_S: self.savefig() class ui_posterior(QMainWindow): def __init__(self,parent=None): super(QMainWindow,self).__init__(parent) self.ui = posterior(self) self.setCentralWidget(self.ui) self.show() def closeEvent(self,event): self.parent().activateWindow() self.parent().raise_() self.parent().setFocus() if __name__ == '__main__': import sys app = QApplication(sys.argv) w = ui_posterior() sys.exit(app.exec_())
mit
kernc/scikit-learn
sklearn/manifold/isomap.py
50
7515
"""Isomap for manifold learning""" # Author: Jake Vanderplas -- <[email protected]> # License: BSD 3 clause (C) 2011 import numpy as np from ..base import BaseEstimator, TransformerMixin from ..neighbors import NearestNeighbors, kneighbors_graph from ..utils import check_array from ..utils.graph import graph_shortest_path from ..decomposition import KernelPCA from ..preprocessing import KernelCenterer class Isomap(BaseEstimator, TransformerMixin): """Isomap Embedding Non-linear dimensionality reduction through Isometric Mapping Read more in the :ref:`User Guide <isomap>`. Parameters ---------- n_neighbors : integer number of neighbors to consider for each point. n_components : integer number of coordinates for the manifold eigen_solver : ['auto'|'arpack'|'dense'] 'auto' : Attempt to choose the most efficient solver for the given problem. 'arpack' : Use Arnoldi decomposition to find the eigenvalues and eigenvectors. 'dense' : Use a direct solver (i.e. LAPACK) for the eigenvalue decomposition. tol : float Convergence tolerance passed to arpack or lobpcg. not used if eigen_solver == 'dense'. max_iter : integer Maximum number of iterations for the arpack solver. not used if eigen_solver == 'dense'. path_method : string ['auto'|'FW'|'D'] Method to use in finding shortest path. 'auto' : attempt to choose the best algorithm automatically. 'FW' : Floyd-Warshall algorithm. 'D' : Dijkstra's algorithm. neighbors_algorithm : string ['auto'|'brute'|'kd_tree'|'ball_tree'] Algorithm to use for nearest neighbors search, passed to neighbors.NearestNeighbors instance. n_jobs : int, optional (default = 1) The number of parallel jobs to run. If ``-1``, then the number of jobs is set to the number of CPU cores. Attributes ---------- embedding_ : array-like, shape (n_samples, n_components) Stores the embedding vectors. kernel_pca_ : object `KernelPCA` object used to implement the embedding. training_data_ : array-like, shape (n_samples, n_features) Stores the training data. nbrs_ : sklearn.neighbors.NearestNeighbors instance Stores nearest neighbors instance, including BallTree or KDtree if applicable. dist_matrix_ : array-like, shape (n_samples, n_samples) Stores the geodesic distance matrix of training data. References ---------- .. [1] Tenenbaum, J.B.; De Silva, V.; & Langford, J.C. A global geometric framework for nonlinear dimensionality reduction. Science 290 (5500) """ def __init__(self, n_neighbors=5, n_components=2, eigen_solver='auto', tol=0, max_iter=None, path_method='auto', neighbors_algorithm='auto', n_jobs=1): self.n_neighbors = n_neighbors self.n_components = n_components self.eigen_solver = eigen_solver self.tol = tol self.max_iter = max_iter self.path_method = path_method self.neighbors_algorithm = neighbors_algorithm self.n_jobs = n_jobs def _fit_transform(self, X): X = check_array(X) self.nbrs_ = NearestNeighbors(n_neighbors=self.n_neighbors, algorithm=self.neighbors_algorithm, n_jobs=self.n_jobs) self.nbrs_.fit(X) self.training_data_ = self.nbrs_._fit_X self.kernel_pca_ = KernelPCA(n_components=self.n_components, kernel="precomputed", eigen_solver=self.eigen_solver, tol=self.tol, max_iter=self.max_iter, n_jobs=self.n_jobs) kng = kneighbors_graph(self.nbrs_, self.n_neighbors, mode='distance', n_jobs=self.n_jobs) self.dist_matrix_ = graph_shortest_path(kng, method=self.path_method, directed=False) G = self.dist_matrix_ ** 2 G *= -0.5 self.embedding_ = self.kernel_pca_.fit_transform(G) def reconstruction_error(self): """Compute the reconstruction error for the embedding. Returns ------- reconstruction_error : float Notes ------- The cost function of an isomap embedding is ``E = frobenius_norm[K(D) - K(D_fit)] / n_samples`` Where D is the matrix of distances for the input data X, D_fit is the matrix of distances for the output embedding X_fit, and K is the isomap kernel: ``K(D) = -0.5 * (I - 1/n_samples) * D^2 * (I - 1/n_samples)`` """ G = -0.5 * self.dist_matrix_ ** 2 G_center = KernelCenterer().fit_transform(G) evals = self.kernel_pca_.lambdas_ return np.sqrt(np.sum(G_center ** 2) - np.sum(evals ** 2)) / G.shape[0] def fit(self, X, y=None): """Compute the embedding vectors for data X Parameters ---------- X : {array-like, sparse matrix, BallTree, KDTree, NearestNeighbors} Sample data, shape = (n_samples, n_features), in the form of a numpy array, precomputed tree, or NearestNeighbors object. Returns ------- self : returns an instance of self. """ self._fit_transform(X) return self def fit_transform(self, X, y=None): """Fit the model from data in X and transform X. Parameters ---------- X: {array-like, sparse matrix, BallTree, KDTree} Training vector, where n_samples in the number of samples and n_features is the number of features. Returns ------- X_new: array-like, shape (n_samples, n_components) """ self._fit_transform(X) return self.embedding_ def transform(self, X): """Transform X. This is implemented by linking the points X into the graph of geodesic distances of the training data. First the `n_neighbors` nearest neighbors of X are found in the training data, and from these the shortest geodesic distances from each point in X to each point in the training data are computed in order to construct the kernel. The embedding of X is the projection of this kernel onto the embedding vectors of the training set. Parameters ---------- X: array-like, shape (n_samples, n_features) Returns ------- X_new: array-like, shape (n_samples, n_components) """ X = check_array(X) distances, indices = self.nbrs_.kneighbors(X, return_distance=True) # Create the graph of shortest distances from X to self.training_data_ # via the nearest neighbors of X. # This can be done as a single array operation, but it potentially # takes a lot of memory. To avoid that, use a loop: G_X = np.zeros((X.shape[0], self.training_data_.shape[0])) for i in range(X.shape[0]): G_X[i] = np.min(self.dist_matrix_[indices[i]] + distances[i][:, None], 0) G_X **= 2 G_X *= -0.5 return self.kernel_pca_.transform(G_X)
bsd-3-clause
peter-kiechle/tactile-sensors
python/step_detection/step_detection_tactile_sensor.py
1
5264
# -*- coding: utf-8 -*- import os, sys print("CWD: " + os.getcwd() ) config_path = os.path.abspath('../matplotlib/') sys.path.append(config_path) lib_path = os.path.abspath('../../lib') sys.path.append(lib_path) # Load configuration file (before pyplot) import configuration as config import numpy as np import scipy.ndimage as ndi import cv2 import matplotlib.pyplot as plt import framemanager_python # Force reloading of external library (convenient during active development) reload(framemanager_python) # Taken from http://stackoverflow.com/questions/4494404/find-large-number-of-consecutive-values-fulfilling-condition-in-a-numpy-array # Author: Joe Kington def contiguous_regions(condition): """Finds contiguous True regions of the boolean array "condition". Returns a 2D array where the first column is the start index of the region and the second column is the end index.""" # Find the indicies of changes in "condition" d = np.diff(condition) idx, = d.nonzero() # We need to start things after the change in "condition". Therefore, # we'll shift the index by 1 to the right. idx += 1 if condition[0]: # If the start of condition is True prepend a 0 idx = np.r_[0, idx] if condition[-1]: # If the end of condition is True, append the length of the array idx = np.r_[idx, condition.size] # Edit # Reshape the result into two columns idx.shape = (-1,2) return idx profileName = os.path.abspath("some_steps.dsa") frameManager = framemanager_python.FrameManagerWrapper() frameManager.load_profile(profileName); numTSFrames = frameManager.get_tsframe_count(); starttime = frameManager.get_tsframe_timestamp(0) stoptime = frameManager.get_tsframe_timestamp(numTSFrames) max_matrix_1 = frameManager.get_max_matrix_list(1) max_matrix_5 = frameManager.get_max_matrix_list(5) # Time stamps timestamps = frameManager.get_tsframe_timestamp_list() timestamps = (timestamps-timestamps[0]) / 1000.0 # Relative timestamps in seconds # Simple smoothing #filtered_matrix_5 = ndi.filters.median_filter(max_matrix_5, size=5, mode='reflect') #filtered_matrix_5 = ndi.uniform_filter1d(max_matrix_5, size=10, mode='reflect') # Edge detection sobel = ndi.sobel(max_matrix_5, mode='reflect') #laplace = ndi.laplace(max_matrix_5, mode='reflect') # Too sensitive to noise #gaussian_laplace = ndi.filters.gaussian_laplace(max_matrix_5, sigma=1.0, mode='reflect') #gaussian_gradient_magnitude = ndi.filters.gaussian_gradient_magnitude(max_matrix_5, sigma=1.0, mode='reflect') max_matrix_5_cv = (max_matrix_5/(4096.0/255.0)).astype(np.uint8) # Scale [0..255], convert to CV_8U canny = cv2.Canny(max_matrix_5_cv, 10, 20) # Hysteresis Thresholding: canny = canny.astype(np.float64) * (sobel.max()/255.0) # Scale to comparable scale #--------------------------------- # Simple step detection algorithm #--------------------------------- # Find all non-zero sequences # Throw small sequencs away. Actual grasps are remaining # For more elaborated methods: http://en.wikipedia.org/wiki/Step_detection thresh_sequence = 10 # Minimum length of a sequence to be considered a "grasp" grasp_begin = [] grasp_end = [] for start, stop in contiguous_regions(max_matrix_5 != 0): if (stop-start) > thresh_sequence: grasp_begin.append([start, max_matrix_5[start]]) grasp_end.append([stop-1, max_matrix_5[stop-1]]) ############ # Plotting ############ text_width = 6.30045 # LaTeX text width in inches golden_ratio = (1 + np.sqrt(5) ) / 2.0 size_factor = 1.0 figure_width = size_factor*text_width #figure_height = (figure_width / golden_ratio) figure_height = 1.3 * figure_width figure_size = [figure_width, figure_height] config.load_config_large() fig = plt.figure(figsize=figure_size) # Axis 1 ax1 = fig.add_subplot(2,1,1) ax1.plot(max_matrix_5, "-", label="Max Matrix 5") #ax1.plot(filtered_matrix_5, "-", marker="x", markersize=4, label="Median Matrix 5") ax1.plot([p[0] for p in grasp_begin], [p[1] for p in grasp_begin], "o", markersize=8, color="green", label="Grasp begin") ax1.plot([p[0] for p in grasp_end], [p[1] for p in grasp_end], "o", markersize=8, color="red", label="Grasp end") #ax1.set_xlim([xmin,xmax]) ax1.set_ylim([0, 1.2*np.max(max_matrix_5)]) ax1.set_xlabel("# Frames") ax1.set_ylabel("Raw Sensor Value", rotation=90) ax1.set_title("Step detection by finding long non-zero sequences in tactile sensor readings", y=1.10) # Second axis for time ax1_time = ax1.twiny() dummy = ax1_time.plot(timestamps, np.ones([timestamps.size])) dummy.pop(0).remove() ax1_time.set_xlabel("Time [s]") ax1.legend(loc = 'upper left') # Axis 2 ax2 = fig.add_subplot(2,1,2, sharex=ax1) ax2.plot(sobel, label="Sobel") #ax2.plot(laplace, label="Laplace") #ax2.plot(gaussian_laplace, label="Gaussian laplace") #ax2.plot(gaussian_gradient_magnitude, label="Gaussian gradient magnitude") ax2.plot(canny, label="Canny") ax2.set_xlabel("# Frames") ax2.set_ylabel("Filtered", rotation=90) ax2.legend(loc = 'lower left') fig.tight_layout() #plt.show() plotname = "step_detection_tactile_sensors" fig.savefig(plotname+".pdf", pad_inches=0, dpi=fig.dpi) # pdf #fig.savefig(plotname+".pgf", pad_inches=0, dpi=fig.dpi) # pgf plt.close()
gpl-3.0
shaunstanislaus/pandashells
pandashells/test/plot_lib_tests.py
7
10281
#! /usr/bin/env python import os import tempfile import shutil from unittest import TestCase from pandashells.lib import plot_lib, arg_lib import argparse from mock import patch, MagicMock import matplotlib as mpl import pylab as pl import pandas as pd from dateutil.parser import parse class PlotLibTests(TestCase): def setUp(self): pl.plot(range(10)) self.dir_name = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.dir_name) pl.clf() @patch('pandashells.lib.plot_lib.pl.show') def test_show_calls_pylab_show(self, show_mock): """show() call pylab.show() """ args = MagicMock(savefig=[]) plot_lib.show(args) self.assertTrue(show_mock.called) def test_show_creates_png_file(self): """show() saves a png file """ file_name = os.path.join(self.dir_name, 'plot.png') args = MagicMock(savefig=[file_name]) plot_lib.show(args) self.assertTrue(os.path.isfile(file_name)) def test_show_creates_html_file(self): """show() saves a png file """ file_name = os.path.join(self.dir_name, 'plot.html') args = MagicMock(savefig=[file_name]) xlabel = 'my_xlabel_string' pl.xlabel(xlabel) plot_lib.show(args) with open(file_name) as f: self.assertTrue(xlabel in f.read()) def test_set_plot_styling(self): """set_plot_styling() alters mpl.rcParams """ args = MagicMock( plot_context=['talk'], plot_theme=['darkgrid'], plot_palette=['muted'], ) mpl.rcParams['axes.color_cycle'] = ['m', 'c'] mpl.rcParams['axes.labelsize'] = 1 mpl.rcParams['axes.titlesize'] = 1 rc_pre = dict(mpl.rcParams) plot_lib.set_plot_styling(args) rc_post = dict(mpl.rcParams) self.assertNotEqual( rc_pre['axes.color_cycle'], rc_post['axes.color_cycle']) self.assertNotEqual( rc_pre['axes.labelsize'], rc_post['axes.labelsize']) self.assertNotEqual( rc_pre['axes.titlesize'], rc_post['axes.titlesize']) def test_set_plot_limits_no_args(self): """set_limits() properly does nothing when nothing specified """ args = MagicMock(savefig='', xlim=[], ylim=[]) plot_lib.set_limits(args) self.assertEqual(pl.gca().get_xlim(), (0.0, 9.0)) self.assertEqual(pl.gca().get_ylim(), (0.0, 9.0)) def test_set_plot_limits(self): """set_limits() properly sets limits """ args = MagicMock(savefig='', xlim=[-2, 2], ylim=[-3, 3]) plot_lib.set_limits(args) self.assertEqual(pl.gca().get_xlim(), (-2.0, 2.0)) self.assertEqual(pl.gca().get_ylim(), (-3.0, 3.0)) def test_set_log_scale(self): args = MagicMock(savefig='', xlog=True, ylog=True) plot_lib.set_scale(args) self.assertEqual(pl.gca().get_xscale(), 'log') self.assertEqual(pl.gca().get_yscale(), 'log') def test_keep_lin_scale(self): args = MagicMock(savefig='', xlog=False, ylog=False) plot_lib.set_scale(args) self.assertEqual(pl.gca().get_xscale(), 'linear') self.assertEqual(pl.gca().get_yscale(), 'linear') def test_set_labels_titles_no_args(self): """set_labels_title() properly does nothing when nothing specified """ args = MagicMock(savefig='', title=[], xlabel=[], ylabel=[]) plot_lib.set_labels_title(args) self.assertEqual(pl.gca().get_title(), '') self.assertEqual(pl.gca().get_xlabel(), '') self.assertEqual(pl.gca().get_ylabel(), '') def test_set_labels_titles(self): """set_labels_title() properly sets labels and titles """ args = MagicMock(savefig='', title=['t'], xlabel=['x'], ylabel=['y']) plot_lib.set_labels_title(args) self.assertEqual(pl.gca().get_title(), 't') self.assertEqual(pl.gca().get_xlabel(), 'x') self.assertEqual(pl.gca().get_ylabel(), 'y') @patch('pandashells.lib.plot_lib.pl.legend') def test_set_legend_no_args(self, legend_mock): """set_legend() properly does nothing when nothing specified """ args = MagicMock(savefig='', legend=[]) plot_lib.set_legend(args) self.assertFalse(legend_mock.called) @patch('pandashells.lib.plot_lib.pl.legend') def test_set_legend_best(self, legend_mock): """set_legend() properly calls legend when specified """ args = MagicMock(savefig='', legend=['best']) plot_lib.set_legend(args) legend_mock.assert_called_with(loc='best') @patch('pandashells.lib.plot_lib.pl.legend') def test_set_legend_int(self, legend_mock): """set_legend() properly calls legend when specified """ args = MagicMock(savefig='', legend=['3']) plot_lib.set_legend(args) legend_mock.assert_called_with(loc=3) def test_set_grid_no_grid(self): """set_grid() properly does nothing when no_grid set """ args = MagicMock(savefig='', no_grid=True) plot_lib.set_grid(args) self.assertFalse(pl.gca().xaxis._gridOnMajor) def test_set_grid_with_grid(self): """set_grid() properly sets grid when specified """ args = MagicMock(savefig='', no_grid=False) plot_lib.set_grid(args) self.assertTrue(pl.gca().xaxis._gridOnMajor) @patch('pandashells.lib.plot_lib.sys.stderr') @patch('pandashells.lib.plot_lib.sys.exit') def test_ensure_xy_args_bad(self, exit_mock, stderr_mock): """ensure_xy_args() exits when args are bad """ stderr_mock.write = MagicMock() args = MagicMock(x=None, y=True) plot_lib.ensure_xy_args(args) self.assertTrue(exit_mock.called) @patch('pandashells.lib.plot_lib.sys.stderr') @patch('pandashells.lib.plot_lib.sys.exit') def test_ensure_xy_args_good(self, exit_mock, stderr_mock): """ensure_xy_args() doesn't exit when args okay """ stderr_mock.write = MagicMock() args = MagicMock(x=None, y=None) plot_lib.ensure_xy_args(args) self.assertFalse(exit_mock.called) @patch('pandashells.lib.plot_lib.sys.stderr') @patch('pandashells.lib.plot_lib.sys.exit') def test_ensure_xy_omission_state_bad(self, exit_mock, stderr_mock): """ensure_xy_omission_state() identifies bad inputs """ stderr_mock.write = MagicMock() args = MagicMock(x=None, y=None) df = MagicMock(columns=[1, 2, 3]) plot_lib.ensure_xy_omission_state(args, df) self.assertTrue(exit_mock.called) @patch('pandashells.lib.plot_lib.sys.stderr') @patch('pandashells.lib.plot_lib.sys.exit') def test_ensure_xy_omission_state_good(self, exit_mock, stderr_mock): """ensure_xy_omission_state() identifies bad inputs """ stderr_mock.write = MagicMock() args = MagicMock(x=None, y=None) df = MagicMock(columns=[1, 2]) plot_lib.ensure_xy_omission_state(args, df) self.assertFalse(exit_mock.called) def test_autofill_plot_fields_and_labels_do_nothing(self): """autofill_plot_fields_and_labels does no filling """ args = MagicMock(x=None, xlabel='xpre', ylabel='ypre') df = MagicMock(columns=[1]) plot_lib.autofill_plot_fields_and_labels(args, df) self.assertEqual(args.xlabel, 'xpre') self.assertEqual(args.ylabel, 'ypre') def test_autofill_plot_fields_and_labels_2_cols(self): """autofill_plot_labels() appropriately handles 2 column frame """ args = MagicMock(x=None, xlabel=None, ylabel=None) df = MagicMock(columns=['x', 'y']) plot_lib.autofill_plot_fields_and_labels(args, df) self.assertEqual(args.x, ['x']) self.assertEqual(args.y, ['y']) self.assertEqual(args.xlabel, ['x']) self.assertEqual(args.ylabel, ['y']) def test_str_to_date_float(self): x = pd.Series([1., 2., 3.]) self.assertEqual(list(x), list(plot_lib.str_to_date(x))) def test_str_to_date_str(self): x = pd.Series(['1/1/2014', '1/2/2014', '1/3/2014']) expected = [parse(e) for e in x] self.assertEqual(expected, list(plot_lib.str_to_date(x))) @patch('pandashells.lib.plot_lib.pl.plot') def test_draw_traces(self, plot_mock): args = MagicMock(savefig='', x='x', y='y') df = pd.DataFrame([[1, 1], [2, 2]], columns=['x', 'y']) plot_lib.draw_traces(args, df) self.assertTrue(plot_mock.called) def test_draw_xy_plot(self): """draw_xy_plot() properly produces an output html file """ out_file = os.path.join(self.dir_name, 'test.html') argv = ( 'p.plot -x x -y btrace ctrace -s o- --xlabel myxlabel ' '--ylabel myylabel --title mytitle --theme darkgrid ' '--context talk --palette muted -a .5 --nogrid ' '--legend best --xlim 0 10 --ylim -10 10 ' '--savefig {}'.format(out_file) ).split() with patch('pandashells.lib.plot_lib.sys.argv', argv): pl.clf() df = pd.DataFrame( { 'x': range(10), 'btrace': [-x for x in range(10)], 'ctrace': [x for x in range(10)] }) parser = argparse.ArgumentParser() arg_lib.add_args( parser, 'io_in', 'xy_plotting', 'decorating', 'example') parser.add_argument( "-a", "--alpha", help="Set opacity", nargs=1, default=[1.], type=float) args = parser.parse_args() plot_lib.draw_xy_plot(args, df) with open(out_file) as f: html = f.read() self.assertTrue('myxlabel' in html) self.assertTrue('myylabel' in html) self.assertTrue('mytitle' in html) self.assertTrue('btrace' in html) self.assertTrue('ctrace' in html) self.assertTrue('1' in html) self.assertTrue('10' in html)
bsd-2-clause
astocko/statsmodels
statsmodels/tsa/statespace/tests/test_tools.py
19
4268
""" Tests for tools Author: Chad Fulton License: Simplified-BSD """ from __future__ import division, absolute_import, print_function import numpy as np import pandas as pd from statsmodels.tsa.statespace import tools # from .results import results_sarimax from numpy.testing import ( assert_equal, assert_array_equal, assert_almost_equal, assert_raises ) class TestCompanionMatrix(object): cases = [ (2, np.array([[0,1],[0,0]])), ([1,-1,-2], np.array([[1,1],[2,0]])), ([1,-1,-2,-3], np.array([[1,1,0],[2,0,1],[3,0,0]])) ] def test_cases(self): for polynomial, result in self.cases: assert_equal(tools.companion_matrix(polynomial), result) class TestDiff(object): x = np.arange(10) cases = [ # diff = 1 ([1,2,3], 1, None, 1, [1, 1]), # diff = 2 (x, 2, None, 1, [0]*8), # diff = 1, seasonal_diff=1, k_seasons=4 (x, 1, 1, 4, [0]*5), (x**2, 1, 1, 4, [8]*5), (x**3, 1, 1, 4, [60, 84, 108, 132, 156]), # diff = 1, seasonal_diff=2, k_seasons=2 (x, 1, 2, 2, [0]*5), (x**2, 1, 2, 2, [0]*5), (x**3, 1, 2, 2, [24]*5), (x**4, 1, 2, 2, [240, 336, 432, 528, 624]), ] def test_cases(self): # Basic cases for series, diff, seasonal_diff, k_seasons, result in self.cases: # Test numpy array x = tools.diff(series, diff, seasonal_diff, k_seasons) assert_almost_equal(x, result) # Test as Pandas Series series = pd.Series(series) # Rewrite to test as n-dimensional array series = np.c_[series, series] result = np.c_[result, result] # Test Numpy array x = tools.diff(series, diff, seasonal_diff, k_seasons) assert_almost_equal(x, result) # Test as Pandas Dataframe series = pd.DataFrame(series) x = tools.diff(series, diff, seasonal_diff, k_seasons) assert_almost_equal(x, result) class TestIsInvertible(object): cases = [ ([1, -0.5], True), ([1, 1-1e-9], True), ([1, 1], False), ([1, 0.9,0.1], True), (np.array([1,0.9,0.1]), True), (pd.Series([1,0.9,0.1]), True) ] def test_cases(self): for polynomial, invertible in self.cases: assert_equal(tools.is_invertible(polynomial), invertible) class TestConstrainStationaryUnivariate(object): cases = [ (np.array([2.]), -2./((1+2.**2)**0.5)) ] def test_cases(self): for unconstrained, constrained in self.cases: result = tools.constrain_stationary_univariate(unconstrained) assert_equal(result, constrained) class TestValidateMatrixShape(object): # name, shape, nrows, ncols, nobs valid = [ ('TEST', (5,2), 5, 2, None), ('TEST', (5,2), 5, 2, 10), ('TEST', (5,2,10), 5, 2, 10), ] invalid = [ ('TEST', (5,), 5, None, None), ('TEST', (5,1,1,1), 5, 1, None), ('TEST', (5,2), 10, 2, None), ('TEST', (5,2), 5, 1, None), ('TEST', (5,2,10), 5, 2, None), ('TEST', (5,2,10), 5, 2, 5), ] def test_valid_cases(self): for args in self.valid: # Just testing that no exception is raised tools.validate_matrix_shape(*args) def test_invalid_cases(self): for args in self.invalid: assert_raises( ValueError, tools.validate_matrix_shape, *args ) class TestValidateVectorShape(object): # name, shape, nrows, ncols, nobs valid = [ ('TEST', (5,), 5, None), ('TEST', (5,), 5, 10), ('TEST', (5,10), 5, 10), ] invalid = [ ('TEST', (5,2,10), 5, 10), ('TEST', (5,), 10, None), ('TEST', (5,10), 5, None), ('TEST', (5,10), 5, 5), ] def test_valid_cases(self): for args in self.valid: # Just testing that no exception is raised tools.validate_vector_shape(*args) def test_invalid_cases(self): for args in self.invalid: assert_raises( ValueError, tools.validate_vector_shape, *args )
bsd-3-clause
Parallel-in-Time/pySDC
pySDC/playgrounds/deprecated/fwsw/plot_stab_vs_m.py
1
3424
import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from pySDC.implementations.problem_classes.FastWaveSlowWave_Scalar import swfw_scalar from pylab import rcParams from pySDC.core import CollocationClasses as collclass from pySDC.core import Hooks as hookclass from pySDC.core import Level as lvl from pySDC.core import Step as stepclass from pySDC.implementations.datatype_classes import mesh, rhs_imex_mesh from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order as imex if __name__ == "__main__": mvals = np.arange(2,10) kvals = [3, 5, 7] lambda_fast = 10j lambda_slow = 3j stabval = np.zeros((np.size(kvals), np.size(mvals))) for i in range(0,np.size(mvals)): pparams = {} # the following are not used in the computation pparams['lambda_s'] = np.array([0.0]) pparams['lambda_f'] = np.array([0.0]) pparams['u0'] = 1.0 swparams = {} # swparams['collocation_class'] = collclass.CollGaussLobatto # swparams['collocation_class'] = collclass.CollGaussLegendre swparams['collocation_class'] = collclass.CollGaussRadau_Right swparams['num_nodes'] = mvals[i] do_coll_update = True # # ...this is functionality copied from test_imexsweeper. Ideally, it should be available in one place. # step = stepclass.step(params={}) L = lvl.level(problem_class=swfw_scalar, problem_params=pparams, dtype_u=mesh, dtype_f=rhs_imex_mesh, sweeper_class=imex, sweeper_params=swparams, level_params={}, hook_class=hookclass.hooks, id="stability") step.register_level(L) step.status.dt = 1.0 # Needs to be 1.0, change dt through lambdas step.status.time = 0.0 u0 = step.levels[0].prob.u_exact(step.status.time) step.init_step(u0) nnodes = step.levels[0].sweep.coll.num_nodes level = step.levels[0] problem = level.prob QE = level.sweep.QE[1:,1:] QI = level.sweep.QI[1:,1:] Q = level.sweep.coll.Qmat[1:,1:] LHS, RHS = level.sweep.get_scalar_problems_sweeper_mats( lambdas = [ lambda_fast, lambda_slow ] ) for k in range(0,np.size(kvals)): Kmax = kvals[k] Mat_sweep = level.sweep.get_scalar_problems_manysweep_mat( nsweeps = Kmax, lambdas = [ lambda_fast, lambda_slow ] ) if do_coll_update: stab_fh = 1.0 + (lambda_fast + lambda_slow)*level.sweep.coll.weights.dot(Mat_sweep.dot(np.ones(nnodes))) else: q = np.zeros(nnodes) q[nnodes-1] = 1.0 stab_fh = q.dot(Mat_sweep.dot(np.ones(nnodes))) stabval[k,i] = np.absolute(stab_fh) rcParams['figure.figsize'] = 2.5, 2.5 fig = plt.figure() fs = 8 plt.plot(mvals, stabval[0,:], 'o-', color='b', label=(r"K=%1i" % kvals[0])) plt.plot(mvals, stabval[1,:], 's-', color='r', label=(r"K=%1i" % kvals[1])) plt.plot(mvals, stabval[2,:], 'd-', color='g', label=(r"K=%1i" % kvals[2])) plt.plot(mvals, 1.0+0.0*mvals, '--', color='k') plt.xlabel('Number of nodes M', fontsize=fs) plt.ylabel(r'Modulus of stability function $\left| R \right|$', fontsize=fs) plt.ylim([0.0, 1.8]) plt.legend(loc='lower right', fontsize=fs, prop={'size':fs}) plt.gca().get_xaxis().get_major_formatter().labelOnlyBase = False plt.gca().get_xaxis().set_major_formatter(ScalarFormatter()) plt.show() # filename = 'stablimit-M'+str(mvals[0])+'.pdf' # fig.savefig(filename, bbox_inches='tight') # call(["pdfcrop", filename, filename])
bsd-2-clause
huobaowangxi/scikit-learn
examples/linear_model/plot_sgd_weighted_samples.py
344
1458
""" ===================== SGD: Weighted samples ===================== Plot decision function of a weighted dataset, where the size of points is proportional to its weight. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model # we create 20 points np.random.seed(0) X = np.r_[np.random.randn(10, 2) + [1, 1], np.random.randn(10, 2)] y = [1] * 10 + [-1] * 10 sample_weight = 100 * np.abs(np.random.randn(20)) # and assign a bigger weight to the last 10 samples sample_weight[:10] *= 10 # plot the weighted data points xx, yy = np.meshgrid(np.linspace(-4, 5, 500), np.linspace(-4, 5, 500)) plt.figure() plt.scatter(X[:, 0], X[:, 1], c=y, s=sample_weight, alpha=0.9, cmap=plt.cm.bone) ## fit the unweighted model clf = linear_model.SGDClassifier(alpha=0.01, n_iter=100) clf.fit(X, y) Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) no_weights = plt.contour(xx, yy, Z, levels=[0], linestyles=['solid']) ## fit the weighted model clf = linear_model.SGDClassifier(alpha=0.01, n_iter=100) clf.fit(X, y, sample_weight=sample_weight) Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) samples_weights = plt.contour(xx, yy, Z, levels=[0], linestyles=['dashed']) plt.legend([no_weights.collections[0], samples_weights.collections[0]], ["no weights", "with weights"], loc="lower left") plt.xticks(()) plt.yticks(()) plt.show()
bsd-3-clause
ChristianKniep/QNIB
serverfiles/usr/local/lib/networkx-1.6/examples/algorithms/blockmodel.py
32
3009
#!/usr/bin/env python # encoding: utf-8 """ Example of creating a block model using the blockmodel function in NX. Data used is the Hartford, CT drug users network: @article{, title = {Social Networks of Drug Users in {High-Risk} Sites: Finding the Connections}, volume = {6}, shorttitle = {Social Networks of Drug Users in {High-Risk} Sites}, url = {http://dx.doi.org/10.1023/A:1015457400897}, doi = {10.1023/A:1015457400897}, number = {2}, journal = {{AIDS} and Behavior}, author = {Margaret R. Weeks and Scott Clair and Stephen P. Borgatti and Kim Radda and Jean J. Schensul}, month = jun, year = {2002}, pages = {193--206} } """ __author__ = """\n""".join(['Drew Conway <[email protected]>', 'Aric Hagberg <[email protected]>']) from collections import defaultdict import networkx as nx import numpy from scipy.cluster import hierarchy from scipy.spatial import distance import matplotlib.pyplot as plt def create_hc(G): """Creates hierarchical cluster of graph G from distance matrix""" path_length=nx.all_pairs_shortest_path_length(G) distances=numpy.zeros((len(G),len(G))) for u,p in path_length.items(): for v,d in p.items(): distances[u][v]=d # Create hierarchical cluster Y=distance.squareform(distances) Z=hierarchy.complete(Y) # Creates HC using farthest point linkage # This partition selection is arbitrary, for illustrive purposes membership=list(hierarchy.fcluster(Z,t=1.15)) # Create collection of lists for blockmodel partition=defaultdict(list) for n,p in zip(list(range(len(G))),membership): partition[p].append(n) return list(partition.values()) if __name__ == '__main__': G=nx.read_edgelist("hartford_drug.edgelist") # Extract largest connected component into graph H H=nx.connected_component_subgraphs(G)[0] # Makes life easier to have consecutively labeled integer nodes H=nx.convert_node_labels_to_integers(H) # Create parititions with hierarchical clustering partitions=create_hc(H) # Build blockmodel graph BM=nx.blockmodel(H,partitions) # Draw original graph pos=nx.spring_layout(H,iterations=100) fig=plt.figure(1,figsize=(6,10)) ax=fig.add_subplot(211) nx.draw(H,pos,with_labels=False,node_size=10) plt.xlim(0,1) plt.ylim(0,1) # Draw block model with weighted edges and nodes sized by number of internal nodes node_size=[BM.node[x]['nnodes']*10 for x in BM.nodes()] edge_width=[(2*d['weight']) for (u,v,d) in BM.edges(data=True)] # Set positions to mean of positions of internal nodes from original graph posBM={} for n in BM: xy=numpy.array([pos[u] for u in BM.node[n]['graph']]) posBM[n]=xy.mean(axis=0) ax=fig.add_subplot(212) nx.draw(BM,posBM,node_size=node_size,width=edge_width,with_labels=False) plt.xlim(0,1) plt.ylim(0,1) plt.axis('off') plt.savefig('hartford_drug_block_model.png')
gpl-2.0
rrohan/scikit-learn
examples/linear_model/plot_logistic_l1_l2_sparsity.py
384
2601
""" ============================================== L1 Penalty and Sparsity in Logistic Regression ============================================== Comparison of the sparsity (percentage of zero coefficients) of solutions when L1 and L2 penalty are used for different values of C. We can see that large values of C give more freedom to the model. Conversely, smaller values of C constrain the model more. In the L1 penalty case, this leads to sparser solutions. We classify 8x8 images of digits into two classes: 0-4 against 5-9. The visualization shows coefficients of the models for varying C. """ print(__doc__) # Authors: Alexandre Gramfort <[email protected]> # Mathieu Blondel <[email protected]> # Andreas Mueller <[email protected]> # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression from sklearn import datasets from sklearn.preprocessing import StandardScaler digits = datasets.load_digits() X, y = digits.data, digits.target X = StandardScaler().fit_transform(X) # classify small against large digits y = (y > 4).astype(np.int) # Set regularization parameter for i, C in enumerate((100, 1, 0.01)): # turn down tolerance for short training time clf_l1_LR = LogisticRegression(C=C, penalty='l1', tol=0.01) clf_l2_LR = LogisticRegression(C=C, penalty='l2', tol=0.01) clf_l1_LR.fit(X, y) clf_l2_LR.fit(X, y) coef_l1_LR = clf_l1_LR.coef_.ravel() coef_l2_LR = clf_l2_LR.coef_.ravel() # coef_l1_LR contains zeros due to the # L1 sparsity inducing norm sparsity_l1_LR = np.mean(coef_l1_LR == 0) * 100 sparsity_l2_LR = np.mean(coef_l2_LR == 0) * 100 print("C=%.2f" % C) print("Sparsity with L1 penalty: %.2f%%" % sparsity_l1_LR) print("score with L1 penalty: %.4f" % clf_l1_LR.score(X, y)) print("Sparsity with L2 penalty: %.2f%%" % sparsity_l2_LR) print("score with L2 penalty: %.4f" % clf_l2_LR.score(X, y)) l1_plot = plt.subplot(3, 2, 2 * i + 1) l2_plot = plt.subplot(3, 2, 2 * (i + 1)) if i == 0: l1_plot.set_title("L1 penalty") l2_plot.set_title("L2 penalty") l1_plot.imshow(np.abs(coef_l1_LR.reshape(8, 8)), interpolation='nearest', cmap='binary', vmax=1, vmin=0) l2_plot.imshow(np.abs(coef_l2_LR.reshape(8, 8)), interpolation='nearest', cmap='binary', vmax=1, vmin=0) plt.text(-8, 3, "C = %.2f" % C) l1_plot.set_xticks(()) l1_plot.set_yticks(()) l2_plot.set_xticks(()) l2_plot.set_yticks(()) plt.show()
bsd-3-clause
zrhans/pythonanywhere
.virtualenvs/django19/lib/python3.4/site-packages/matplotlib/tests/test_backend_svg.py
7
3551
from __future__ import (absolute_import, division, print_function, unicode_literals) from matplotlib.externals import six import numpy as np from io import BytesIO import xml.parsers.expat import matplotlib.pyplot as plt from matplotlib.testing.decorators import cleanup from matplotlib.testing.decorators import image_comparison @cleanup def test_visibility(): fig = plt.figure() ax = fig.add_subplot(111) x = np.linspace(0, 4 * np.pi, 50) y = np.sin(x) yerr = np.ones_like(y) a, b, c = ax.errorbar(x, y, yerr=yerr, fmt='ko') for artist in b: artist.set_visible(False) fd = BytesIO() fig.savefig(fd, format='svg') fd.seek(0) buf = fd.read() fd.close() parser = xml.parsers.expat.ParserCreate() parser.Parse(buf) # this will raise ExpatError if the svg is invalid @image_comparison(baseline_images=['fill_black_with_alpha'], remove_text=True, extensions=['svg']) def test_fill_black_with_alpha(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.scatter(x=[0, 0.1, 1], y=[0, 0, 0], c='k', alpha=0.1, s=10000) @image_comparison(baseline_images=['noscale'], remove_text=True) def test_noscale(): X, Y = np.meshgrid(np.arange(-5, 5, 1), np.arange(-5, 5, 1)) Z = np.sin(Y ** 2) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.imshow(Z, cmap='gray') plt.rcParams['svg.image_noscale'] = True @cleanup def test_composite_images(): #Test that figures can be saved with and without combining multiple images #(on a single set of axes) into a single composite image. X, Y = np.meshgrid(np.arange(-5, 5, 1), np.arange(-5, 5, 1)) Z = np.sin(Y ** 2) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_xlim(0, 3) ax.imshow(Z, extent=[0, 1, 0, 1]) ax.imshow(Z[::-1], extent=[2, 3, 0, 1]) plt.rcParams['image.composite_image'] = True with BytesIO() as svg: fig.savefig(svg, format="svg") svg.seek(0) buff = svg.read() assert buff.count(six.b('<image ')) == 1 plt.rcParams['image.composite_image'] = False with BytesIO() as svg: fig.savefig(svg, format="svg") svg.seek(0) buff = svg.read() assert buff.count(six.b('<image ')) == 2 @cleanup def test_text_urls(): fig = plt.figure() test_url = "http://test_text_urls.matplotlib.org" fig.suptitle("test_text_urls", url=test_url) fd = BytesIO() fig.savefig(fd, format='svg') fd.seek(0) buf = fd.read().decode() fd.close() expected = '<a xlink:href="{0}">'.format(test_url) assert expected in buf @image_comparison(baseline_images=['bold_font_output'], extensions=['svg']) def test_bold_font_output(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(np.arange(10), np.arange(10)) ax.set_xlabel('nonbold-xlabel') ax.set_ylabel('bold-ylabel', fontweight='bold') ax.set_title('bold-title', fontweight='bold') @image_comparison(baseline_images=['bold_font_output_with_none_fonttype'], extensions=['svg']) def test_bold_font_output_with_none_fonttype(): plt.rcParams['svg.fonttype'] = 'none' fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(np.arange(10), np.arange(10)) ax.set_xlabel('nonbold-xlabel') ax.set_ylabel('bold-ylabel', fontweight='bold') ax.set_title('bold-title', fontweight='bold') if __name__ == '__main__': import nose nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
apache-2.0
Sklearn-HMM/scikit-learn-HMM
sklean-hmm/metrics/scorer.py
2
10497
""" The :mod:`sklearn.metrics.scorer` submodule implements a flexible interface for model selection and evaluation using arbitrary score functions. A scorer object is a callable that can be passed to :class:`sklearn.grid_search.GridSearchCV` or :func:`sklearn.cross_validation.cross_val_score` as the ``scoring`` parameter, to specify how a model should be evaluated. The signature of the call is ``(estimator, X, y)`` where ``estimator`` is the model to be evaluated, ``X`` is the test data and ``y`` is the ground truth labeling (or ``None`` in the case of unsupervised models). """ # Authors: Andreas Mueller <[email protected]> # Lars Buitinck <[email protected]> # Arnaud Joly <[email protected]> # License: Simplified BSD from abc import ABCMeta, abstractmethod from warnings import warn import numpy as np from . import (r2_score, mean_squared_error, accuracy_score, f1_score, roc_auc_score, average_precision_score, precision_score, recall_score, log_loss) from .cluster import adjusted_rand_score from ..utils.multiclass import type_of_target from ..externals import six class _BaseScorer(six.with_metaclass(ABCMeta, object)): def __init__(self, score_func, sign, kwargs): self._kwargs = kwargs self._score_func = score_func self._sign = sign @abstractmethod def __call__(self, estimator, X, y): pass def __repr__(self): kwargs_string = "".join([", %s=%s" % (str(k), str(v)) for k, v in self._kwargs.items()]) return ("make_scorer(%s%s%s%s)" % (self._score_func.__name__, "" if self._sign > 0 else ", greater_is_better=False", self._factory_args(), kwargs_string)) def _factory_args(self): """Return non-default make_scorer arguments for repr.""" return "" class _PredictScorer(_BaseScorer): def __call__(self, estimator, X, y_true): """Evaluate predicted target values for X relative to y_true. Parameters ---------- estimator : object Trained estimator to use for scoring. Must have a predict_proba method; the output of that is used to compute the score. X : array-like or sparse matrix Test data that will be fed to estimator.predict. y_true : array-like Gold standard target values for X. Returns ------- score : float Score function applied to prediction of estimator on X. """ y_pred = estimator.predict(X) return self._sign * self._score_func(y_true, y_pred, **self._kwargs) class _ProbaScorer(_BaseScorer): def __call__(self, clf, X, y): """Evaluate predicted probabilities for X relative to y_true. Parameters ---------- clf : object Trained classifier to use for scoring. Must have a predict_proba method; the output of that is used to compute the score. X : array-like or sparse matrix Test data that will be fed to clf.predict_proba. y : array-like Gold standard target values for X. These must be class labels, not probabilities. Returns ------- score : float Score function applied to prediction of estimator on X. """ y_pred = clf.predict_proba(X) return self._sign * self._score_func(y, y_pred, **self._kwargs) def _factory_args(self): return ", needs_proba=True" class _ThresholdScorer(_BaseScorer): def __call__(self, clf, X, y): """Evaluate decision function output for X relative to y_true. Parameters ---------- clf : object Trained classifier to use for scoring. Must have either a decision_function method or a predict_proba method; the output of that is used to compute the score. X : array-like or sparse matrix Test data that will be fed to clf.decision_function or clf.predict_proba. y : array-like Gold standard target values for X. These must be class labels, not decision function values. Returns ------- score : float Score function applied to prediction of estimator on X. """ y_type = type_of_target(y) if y_type not in ("binary", "multilabel-indicator"): raise ValueError("{0} format is not supported".format(y_type)) try: y_pred = clf.decision_function(X) # For multi-output multi-class estimator if isinstance(y_pred, list): y_pred = np.vstack(p for p in y_pred).T except (NotImplementedError, AttributeError): y_pred = clf.predict_proba(X) if y_type == "binary": y_pred = y_pred[:, 1] elif isinstance(y_pred, list): y_pred = np.vstack([p[:, -1] for p in y_pred]).T return self._sign * self._score_func(y, y_pred, **self._kwargs) def _factory_args(self): return ", needs_threshold=True" def _deprecate_loss_and_score_funcs( loss_func=None, score_func=None, scoring=None, score_overrides_loss=False): scorer = None if loss_func is not None or score_func is not None: if loss_func is not None: warn("Passing a loss function is " "deprecated and will be removed in 0.15. " "Either use strings or score objects. " "The relevant new parameter is called ''scoring''. ", category=DeprecationWarning, stacklevel=2) scorer = make_scorer(loss_func, greater_is_better=False) if score_func is not None: warn("Passing function as ``score_func`` is " "deprecated and will be removed in 0.15. " "Either use strings or score objects. " "The relevant new parameter is called ''scoring''.", category=DeprecationWarning, stacklevel=2) if loss_func is None or score_overrides_loss: scorer = make_scorer(score_func) else: scorer = get_scorer(scoring) return scorer def get_scorer(scoring): if isinstance(scoring, six.string_types): try: scorer = SCORERS[scoring] except KeyError: raise ValueError('%r is not a valid scoring value. ' 'Valid options are %s' % (scoring, sorted(SCORERS.keys()))) else: scorer = scoring return scorer def make_scorer(score_func, greater_is_better=True, needs_proba=False, needs_threshold=False, **kwargs): """Make a scorer from a performance metric or loss function. This factory function wraps scoring functions for use in GridSearchCV and cross_val_score. It takes a score function, such as ``accuracy_score``, ``mean_squared_error``, ``adjusted_rand_index`` or ``average_precision`` and returns a callable that scores an estimator's output. Parameters ---------- score_func : callable, Score function (or loss function) with signature ``score_func(y, y_pred, **kwargs)``. greater_is_better : boolean, default=True Whether score_func is a score function (default), meaning high is good, or a loss function, meaning low is good. In the latter case, the scorer object will sign-flip the outcome of the score_func. needs_proba : boolean, default=False Whether score_func requires predict_proba to get probability estimates out of a classifier. needs_threshold : boolean, default=False Whether score_func takes a continuous decision certainty. This only works for binary classification using estimators that have either a decision_function or predict_proba method. For example ``average_precision`` or the area under the roc curve can not be computed using discrete predictions alone. **kwargs : additional arguments Additional parameters to be passed to score_func. Returns ------- scorer : callable Callable object that returns a scalar score; greater is better. Examples -------- >>> from sklearn.metrics import fbeta_score, make_scorer >>> ftwo_scorer = make_scorer(fbeta_score, beta=2) >>> ftwo_scorer make_scorer(fbeta_score, beta=2) >>> from sklearn.grid_search import GridSearchCV >>> from sklearn.svm import LinearSVC >>> grid = GridSearchCV(LinearSVC(), param_grid={'C': [1, 10]}, ... scoring=ftwo_scorer) """ sign = 1 if greater_is_better else -1 if needs_proba and needs_threshold: raise ValueError("Set either needs_proba or needs_threshold to True," " but not both.") if needs_proba: cls = _ProbaScorer elif needs_threshold: cls = _ThresholdScorer else: cls = _PredictScorer return cls(score_func, sign, kwargs) # Standard regression scores r2_scorer = make_scorer(r2_score) mean_squared_error_scorer = make_scorer(mean_squared_error, greater_is_better=False) # Standard Classification Scores accuracy_scorer = make_scorer(accuracy_score) f1_scorer = make_scorer(f1_score) # Score functions that need decision values roc_auc_scorer = make_scorer(roc_auc_score, greater_is_better=True, needs_threshold=True) average_precision_scorer = make_scorer(average_precision_score, needs_threshold=True) precision_scorer = make_scorer(precision_score) recall_scorer = make_scorer(recall_score) # Score function for probabilistic classification log_loss_scorer = make_scorer(log_loss, greater_is_better=False, needs_proba=True) # Clustering scores adjusted_rand_scorer = make_scorer(adjusted_rand_score) SCORERS = dict(r2=r2_scorer, mean_squared_error=mean_squared_error_scorer, accuracy=accuracy_scorer, f1=f1_scorer, roc_auc=roc_auc_scorer, average_precision=average_precision_scorer, precision=precision_scorer, recall=recall_scorer, log_loss=log_loss_scorer, adjusted_rand_score=adjusted_rand_scorer)
bsd-3-clause
danialjahed/IDS-KDDcup
UnderstandingData/look at Datasets.py
1
1143
import pandas as pd import matplotlib.pyplot as plt import seaborn #Load train dataset Train_Data = pd.read_csv("../DataSets/kddcup.data_10_percent_corrected.csv",header=None) print("train :",Train_Data.shape) #visulize data variety labels = Train_Data.iloc[:][41] labels_count = labels.value_counts() plt.bar(range(len(labels_count.index)),labels_count.values) plt.xticks(range(len(labels_count.index)),labels_count.index,fontsize=12,rotation=90) plt.savefig("labels_variety(for Training Dataset).png") #checking missing values of Traindata print(Train_Data.isnull().values.any()) # print(Train_Data.isnull().sum()) #Load test dataset Test_Data = pd.read_csv("../DataSets/corrected.csv",header=None) print("test :", Test_Data.shape) #checking missing values of Testdata print(Test_Data.isnull().values.any()) # print(Test_Data.isnull().sum()) #visulize data variety labels = Test_Data.iloc[:][41] labels_count = labels.value_counts() plt.bar(range(len(labels_count.index)),labels_count.values) plt.xticks(range(len(labels_count.index)),labels_count.index,fontsize=8,rotation=90) plt.savefig("labels_variety(for Testing Dataset).png")
gpl-3.0
victorbergelin/scikit-learn
sklearn/metrics/tests/test_classification.py
28
53546
from __future__ import division, print_function import numpy as np from scipy import linalg from functools import partial from itertools import product import warnings from sklearn import datasets from sklearn import svm from sklearn.datasets import make_multilabel_classification from sklearn.preprocessing import LabelBinarizer, MultiLabelBinarizer from sklearn.preprocessing import label_binarize from sklearn.utils.fixes import np_version from sklearn.utils.validation import check_random_state from sklearn.utils.testing import assert_raises, clean_warning_registry from sklearn.utils.testing import assert_raise_message from sklearn.utils.testing import assert_equal 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_warns from sklearn.utils.testing import assert_no_warnings from sklearn.utils.testing import assert_warns_message from sklearn.utils.testing import assert_not_equal from sklearn.utils.testing import ignore_warnings from sklearn.metrics import accuracy_score from sklearn.metrics import average_precision_score from sklearn.metrics import classification_report from sklearn.metrics import cohen_kappa_score from sklearn.metrics import confusion_matrix from sklearn.metrics import f1_score from sklearn.metrics import fbeta_score from sklearn.metrics import hamming_loss from sklearn.metrics import hinge_loss from sklearn.metrics import jaccard_similarity_score from sklearn.metrics import log_loss from sklearn.metrics import matthews_corrcoef from sklearn.metrics import precision_recall_fscore_support from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import zero_one_loss from sklearn.metrics import brier_score_loss from sklearn.metrics.classification import _check_targets from sklearn.metrics.base import UndefinedMetricWarning ############################################################################### # Utilities for testing def make_prediction(dataset=None, binary=False): """Make some classification predictions on a toy dataset using a SVC If binary is True restrict to a binary classification problem instead of a multiclass classification problem """ if dataset is None: # import some data to play with dataset = datasets.load_iris() X = dataset.data y = dataset.target if binary: # restrict to a binary classification task X, y = X[y < 2], y[y < 2] n_samples, n_features = X.shape p = np.arange(n_samples) rng = check_random_state(37) rng.shuffle(p) X, y = X[p], y[p] half = int(n_samples / 2) # add noisy features to make the problem harder and avoid perfect results rng = np.random.RandomState(0) X = np.c_[X, rng.randn(n_samples, 200 * n_features)] # run classifier, get class probabilities and label predictions clf = svm.SVC(kernel='linear', probability=True, random_state=0) probas_pred = clf.fit(X[:half], y[:half]).predict_proba(X[half:]) if binary: # only interested in probabilities of the positive case # XXX: do we really want a special API for the binary case? probas_pred = probas_pred[:, 1] y_pred = clf.predict(X[half:]) y_true = y[half:] return y_true, y_pred, probas_pred ############################################################################### # Tests def test_multilabel_accuracy_score_subset_accuracy(): # Dense label indicator matrix format y1 = np.array([[0, 1, 1], [1, 0, 1]]) y2 = np.array([[0, 0, 1], [1, 0, 1]]) assert_equal(accuracy_score(y1, y2), 0.5) assert_equal(accuracy_score(y1, y1), 1) assert_equal(accuracy_score(y2, y2), 1) assert_equal(accuracy_score(y2, np.logical_not(y2)), 0) assert_equal(accuracy_score(y1, np.logical_not(y1)), 0) assert_equal(accuracy_score(y1, np.zeros(y1.shape)), 0) assert_equal(accuracy_score(y2, np.zeros(y1.shape)), 0) with ignore_warnings(): # sequence of sequences is deprecated # List of tuple of label y1 = [(1, 2,), (0, 2,)] y2 = [(2,), (0, 2,)] assert_equal(accuracy_score(y1, y2), 0.5) assert_equal(accuracy_score(y1, y1), 1) assert_equal(accuracy_score(y2, y2), 1) assert_equal(accuracy_score(y2, [(), ()]), 0) assert_equal(accuracy_score(y1, y2, normalize=False), 1) assert_equal(accuracy_score(y1, y1, normalize=False), 2) assert_equal(accuracy_score(y2, y2, normalize=False), 2) assert_equal(accuracy_score(y2, [(), ()], normalize=False), 0) def test_precision_recall_f1_score_binary(): # Test Precision Recall and F1 Score for binary classification task y_true, y_pred, _ = make_prediction(binary=True) # detailed measures for each class p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average=None) assert_array_almost_equal(p, [0.73, 0.85], 2) assert_array_almost_equal(r, [0.88, 0.68], 2) assert_array_almost_equal(f, [0.80, 0.76], 2) assert_array_equal(s, [25, 25]) # individual scoring function that can be used for grid search: in the # binary class case the score is the value of the measure for the positive # class (e.g. label == 1). This is deprecated for average != 'binary'. assert_dep_warning = partial(assert_warns, DeprecationWarning) for kwargs, my_assert in [({}, assert_no_warnings), ({'average': 'binary'}, assert_no_warnings), ({'average': 'micro'}, assert_dep_warning)]: ps = my_assert(precision_score, y_true, y_pred, **kwargs) assert_array_almost_equal(ps, 0.85, 2) rs = my_assert(recall_score, y_true, y_pred, **kwargs) assert_array_almost_equal(rs, 0.68, 2) fs = my_assert(f1_score, y_true, y_pred, **kwargs) assert_array_almost_equal(fs, 0.76, 2) assert_almost_equal(my_assert(fbeta_score, y_true, y_pred, beta=2, **kwargs), (1 + 2 ** 2) * ps * rs / (2 ** 2 * ps + rs), 2) @ignore_warnings def test_precision_recall_f_binary_single_class(): # Test precision, recall and F1 score behave with a single positive or # negative class # Such a case may occur with non-stratified cross-validation assert_equal(1., precision_score([1, 1], [1, 1])) assert_equal(1., recall_score([1, 1], [1, 1])) assert_equal(1., f1_score([1, 1], [1, 1])) assert_equal(0., precision_score([-1, -1], [-1, -1])) assert_equal(0., recall_score([-1, -1], [-1, -1])) assert_equal(0., f1_score([-1, -1], [-1, -1])) @ignore_warnings def test_precision_recall_f_extra_labels(): """Test handling of explicit additional (not in input) labels to PRF """ y_true = [1, 3, 3, 2] y_pred = [1, 1, 3, 2] y_true_bin = label_binarize(y_true, classes=np.arange(5)) y_pred_bin = label_binarize(y_pred, classes=np.arange(5)) data = [(y_true, y_pred), (y_true_bin, y_pred_bin)] for i, (y_true, y_pred) in enumerate(data): # No average: zeros in array actual = recall_score(y_true, y_pred, labels=[0, 1, 2, 3, 4], average=None) assert_array_almost_equal([0., 1., 1., .5, 0.], actual) # Macro average is changed actual = recall_score(y_true, y_pred, labels=[0, 1, 2, 3, 4], average='macro') assert_array_almost_equal(np.mean([0., 1., 1., .5, 0.]), actual) # No effect otheriwse for average in ['micro', 'weighted', 'samples']: if average == 'samples' and i == 0: continue assert_almost_equal(recall_score(y_true, y_pred, labels=[0, 1, 2, 3, 4], average=average), recall_score(y_true, y_pred, labels=None, average=average)) # Error when introducing invalid label in multilabel case # (although it would only affect performance if average='macro'/None) for average in [None, 'macro', 'micro', 'samples']: assert_raises(ValueError, recall_score, y_true_bin, y_pred_bin, labels=np.arange(6), average=average) assert_raises(ValueError, recall_score, y_true_bin, y_pred_bin, labels=np.arange(-1, 4), average=average) @ignore_warnings def test_precision_recall_f_ignored_labels(): """Test a subset of labels may be requested for PRF""" y_true = [1, 1, 2, 3] y_pred = [1, 3, 3, 3] y_true_bin = label_binarize(y_true, classes=np.arange(5)) y_pred_bin = label_binarize(y_pred, classes=np.arange(5)) data = [(y_true, y_pred), (y_true_bin, y_pred_bin)] for i, (y_true, y_pred) in enumerate(data): recall_13 = partial(recall_score, y_true, y_pred, labels=[1, 3]) recall_all = partial(recall_score, y_true, y_pred, labels=None) assert_array_almost_equal([.5, 1.], recall_13(average=None)) assert_almost_equal((.5 + 1.) / 2, recall_13(average='macro')) assert_almost_equal((.5 * 2 + 1. * 1) / 3, recall_13(average='weighted')) assert_almost_equal(2. / 3, recall_13(average='micro')) # ensure the above were meaningful tests: for average in ['macro', 'weighted', 'micro']: assert_not_equal(recall_13(average=average), recall_all(average=average)) def test_average_precision_score_score_non_binary_class(): # Test that average_precision_score function returns an error when trying # to compute average_precision_score for multiclass task. rng = check_random_state(404) y_pred = rng.rand(10) # y_true contains three different class values y_true = rng.randint(0, 3, size=10) assert_raise_message(ValueError, "multiclass format is not supported", average_precision_score, y_true, y_pred) def test_average_precision_score_duplicate_values(): # Duplicate values with precision-recall require a different # processing than when computing the AUC of a ROC, because the # precision-recall curve is a decreasing curve # The following situtation corresponds to a perfect # test statistic, the average_precision_score should be 1 y_true = [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1] y_score = [0, .1, .1, .4, .5, .6, .6, .9, .9, 1, 1] assert_equal(average_precision_score(y_true, y_score), 1) def test_average_precision_score_tied_values(): # Here if we go from left to right in y_true, the 0 values are # are separated from the 1 values, so it appears that we've # Correctly sorted our classifications. But in fact the first two # values have the same score (0.5) and so the first two values # could be swapped around, creating an imperfect sorting. This # imperfection should come through in the end score, making it less # than one. y_true = [0, 1, 1] y_score = [.5, .5, .6] assert_not_equal(average_precision_score(y_true, y_score), 1.) @ignore_warnings def test_precision_recall_fscore_support_errors(): y_true, y_pred, _ = make_prediction(binary=True) # Bad beta assert_raises(ValueError, precision_recall_fscore_support, y_true, y_pred, beta=0.0) # Bad pos_label assert_raises(ValueError, precision_recall_fscore_support, y_true, y_pred, pos_label=2, average='macro') # Bad average option assert_raises(ValueError, precision_recall_fscore_support, [0, 1, 2], [1, 2, 0], average='mega') def test_confusion_matrix_binary(): # Test confusion matrix - binary classification case y_true, y_pred, _ = make_prediction(binary=True) def test(y_true, y_pred): cm = confusion_matrix(y_true, y_pred) assert_array_equal(cm, [[22, 3], [8, 17]]) tp, fp, fn, tn = cm.flatten() num = (tp * tn - fp * fn) den = np.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)) true_mcc = 0 if den == 0 else num / den mcc = matthews_corrcoef(y_true, y_pred) assert_array_almost_equal(mcc, true_mcc, decimal=2) assert_array_almost_equal(mcc, 0.57, decimal=2) test(y_true, y_pred) test([str(y) for y in y_true], [str(y) for y in y_pred]) def test_cohen_kappa(): # These label vectors reproduce the contingency matrix from Artstein and # Poesio (2008), Table 1: np.array([[20, 20], [10, 50]]). y1 = np.array([0] * 40 + [1] * 60) y2 = np.array([0] * 20 + [1] * 20 + [0] * 10 + [1] * 50) kappa = cohen_kappa_score(y1, y2) assert_almost_equal(kappa, .348, decimal=3) assert_equal(kappa, cohen_kappa_score(y2, y1)) # Add spurious labels and ignore them. y1 = np.append(y1, [2] * 4) y2 = np.append(y2, [2] * 4) assert_equal(cohen_kappa_score(y1, y2, labels=[0, 1]), kappa) assert_almost_equal(cohen_kappa_score(y1, y1), 1.) # Multiclass example: Artstein and Poesio, Table 4. y1 = np.array([0] * 46 + [1] * 44 + [2] * 10) y2 = np.array([0] * 52 + [1] * 32 + [2] * 16) assert_almost_equal(cohen_kappa_score(y1, y2), .8013, decimal=4) @ignore_warnings def test_matthews_corrcoef_nan(): assert_equal(matthews_corrcoef([0], [1]), 0.0) assert_equal(matthews_corrcoef([0, 0], [0, 1]), 0.0) def test_precision_recall_f1_score_multiclass(): # Test Precision Recall and F1 Score for multiclass classification task y_true, y_pred, _ = make_prediction(binary=False) # compute scores with default labels introspection p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average=None) assert_array_almost_equal(p, [0.83, 0.33, 0.42], 2) assert_array_almost_equal(r, [0.79, 0.09, 0.90], 2) assert_array_almost_equal(f, [0.81, 0.15, 0.57], 2) assert_array_equal(s, [24, 31, 20]) # averaging tests ps = precision_score(y_true, y_pred, pos_label=1, average='micro') assert_array_almost_equal(ps, 0.53, 2) rs = recall_score(y_true, y_pred, average='micro') assert_array_almost_equal(rs, 0.53, 2) fs = f1_score(y_true, y_pred, average='micro') assert_array_almost_equal(fs, 0.53, 2) ps = precision_score(y_true, y_pred, average='macro') assert_array_almost_equal(ps, 0.53, 2) rs = recall_score(y_true, y_pred, average='macro') assert_array_almost_equal(rs, 0.60, 2) fs = f1_score(y_true, y_pred, average='macro') assert_array_almost_equal(fs, 0.51, 2) ps = precision_score(y_true, y_pred, average='weighted') assert_array_almost_equal(ps, 0.51, 2) rs = recall_score(y_true, y_pred, average='weighted') assert_array_almost_equal(rs, 0.53, 2) fs = f1_score(y_true, y_pred, average='weighted') assert_array_almost_equal(fs, 0.47, 2) assert_raises(ValueError, precision_score, y_true, y_pred, average="samples") assert_raises(ValueError, recall_score, y_true, y_pred, average="samples") assert_raises(ValueError, f1_score, y_true, y_pred, average="samples") assert_raises(ValueError, fbeta_score, y_true, y_pred, average="samples", beta=0.5) # same prediction but with and explicit label ordering p, r, f, s = precision_recall_fscore_support( y_true, y_pred, labels=[0, 2, 1], average=None) assert_array_almost_equal(p, [0.83, 0.41, 0.33], 2) assert_array_almost_equal(r, [0.79, 0.90, 0.10], 2) assert_array_almost_equal(f, [0.81, 0.57, 0.15], 2) assert_array_equal(s, [24, 20, 31]) def test_precision_refcall_f1_score_multilabel_unordered_labels(): # test that labels need not be sorted in the multilabel case y_true = np.array([[1, 1, 0, 0]]) y_pred = np.array([[0, 0, 1, 1]]) for average in ['samples', 'micro', 'macro', 'weighted', None]: p, r, f, s = precision_recall_fscore_support( y_true, y_pred, labels=[3, 0, 1, 2], warn_for=[], average=average) assert_array_equal(p, 0) assert_array_equal(r, 0) assert_array_equal(f, 0) if average is None: assert_array_equal(s, [0, 1, 1, 0]) def test_precision_recall_f1_score_multiclass_pos_label_none(): # Test Precision Recall and F1 Score for multiclass classification task # GH Issue #1296 # initialize data y_true = np.array([0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1]) y_pred = np.array([1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1]) # compute scores with default labels introspection p, r, f, s = precision_recall_fscore_support(y_true, y_pred, pos_label=None, average='weighted') def test_zero_precision_recall(): # Check that pathological cases do not bring NaNs old_error_settings = np.seterr(all='raise') try: y_true = np.array([0, 1, 2, 0, 1, 2]) y_pred = np.array([2, 0, 1, 1, 2, 0]) assert_almost_equal(precision_score(y_true, y_pred, average='weighted'), 0.0, 2) assert_almost_equal(recall_score(y_true, y_pred, average='weighted'), 0.0, 2) assert_almost_equal(f1_score(y_true, y_pred, average='weighted'), 0.0, 2) finally: np.seterr(**old_error_settings) def test_confusion_matrix_multiclass(): # Test confusion matrix - multi-class case y_true, y_pred, _ = make_prediction(binary=False) def test(y_true, y_pred, string_type=False): # compute confusion matrix with default labels introspection cm = confusion_matrix(y_true, y_pred) assert_array_equal(cm, [[19, 4, 1], [4, 3, 24], [0, 2, 18]]) # compute confusion matrix with explicit label ordering labels = ['0', '2', '1'] if string_type else [0, 2, 1] cm = confusion_matrix(y_true, y_pred, labels=labels) assert_array_equal(cm, [[19, 1, 4], [0, 18, 2], [4, 24, 3]]) test(y_true, y_pred) test(list(str(y) for y in y_true), list(str(y) for y in y_pred), string_type=True) def test_confusion_matrix_multiclass_subset_labels(): # Test confusion matrix - multi-class case with subset of labels y_true, y_pred, _ = make_prediction(binary=False) # compute confusion matrix with only first two labels considered cm = confusion_matrix(y_true, y_pred, labels=[0, 1]) assert_array_equal(cm, [[19, 4], [4, 3]]) # compute confusion matrix with explicit label ordering for only subset # of labels cm = confusion_matrix(y_true, y_pred, labels=[2, 1]) assert_array_equal(cm, [[18, 2], [24, 3]]) def test_classification_report_multiclass(): # Test performance report iris = datasets.load_iris() y_true, y_pred, _ = make_prediction(dataset=iris, binary=False) # print classification report with class names expected_report = """\ precision recall f1-score support setosa 0.83 0.79 0.81 24 versicolor 0.33 0.10 0.15 31 virginica 0.42 0.90 0.57 20 avg / total 0.51 0.53 0.47 75 """ report = classification_report( y_true, y_pred, labels=np.arange(len(iris.target_names)), target_names=iris.target_names) assert_equal(report, expected_report) # print classification report with label detection expected_report = """\ precision recall f1-score support 0 0.83 0.79 0.81 24 1 0.33 0.10 0.15 31 2 0.42 0.90 0.57 20 avg / total 0.51 0.53 0.47 75 """ report = classification_report(y_true, y_pred) assert_equal(report, expected_report) def test_classification_report_multiclass_with_digits(): # Test performance report with added digits in floating point values iris = datasets.load_iris() y_true, y_pred, _ = make_prediction(dataset=iris, binary=False) # print classification report with class names expected_report = """\ precision recall f1-score support setosa 0.82609 0.79167 0.80851 24 versicolor 0.33333 0.09677 0.15000 31 virginica 0.41860 0.90000 0.57143 20 avg / total 0.51375 0.53333 0.47310 75 """ report = classification_report( y_true, y_pred, labels=np.arange(len(iris.target_names)), target_names=iris.target_names, digits=5) assert_equal(report, expected_report) # print classification report with label detection expected_report = """\ precision recall f1-score support 0 0.83 0.79 0.81 24 1 0.33 0.10 0.15 31 2 0.42 0.90 0.57 20 avg / total 0.51 0.53 0.47 75 """ report = classification_report(y_true, y_pred) assert_equal(report, expected_report) def test_classification_report_multiclass_with_string_label(): y_true, y_pred, _ = make_prediction(binary=False) y_true = np.array(["blue", "green", "red"])[y_true] y_pred = np.array(["blue", "green", "red"])[y_pred] expected_report = """\ precision recall f1-score support blue 0.83 0.79 0.81 24 green 0.33 0.10 0.15 31 red 0.42 0.90 0.57 20 avg / total 0.51 0.53 0.47 75 """ report = classification_report(y_true, y_pred) assert_equal(report, expected_report) expected_report = """\ precision recall f1-score support a 0.83 0.79 0.81 24 b 0.33 0.10 0.15 31 c 0.42 0.90 0.57 20 avg / total 0.51 0.53 0.47 75 """ report = classification_report(y_true, y_pred, target_names=["a", "b", "c"]) assert_equal(report, expected_report) def test_classification_report_multiclass_with_unicode_label(): y_true, y_pred, _ = make_prediction(binary=False) labels = np.array([u"blue\xa2", u"green\xa2", u"red\xa2"]) y_true = labels[y_true] y_pred = labels[y_pred] expected_report = u"""\ precision recall f1-score support blue\xa2 0.83 0.79 0.81 24 green\xa2 0.33 0.10 0.15 31 red\xa2 0.42 0.90 0.57 20 avg / total 0.51 0.53 0.47 75 """ if np_version[:3] < (1, 7, 0): expected_message = ("NumPy < 1.7.0 does not implement" " searchsorted on unicode data correctly.") assert_raise_message(RuntimeError, expected_message, classification_report, y_true, y_pred) else: report = classification_report(y_true, y_pred) assert_equal(report, expected_report) @ignore_warnings # sequence of sequences is deprecated def test_multilabel_classification_report(): n_classes = 4 n_samples = 50 make_ml = make_multilabel_classification _, y_true_ll = make_ml(n_features=1, n_classes=n_classes, random_state=0, n_samples=n_samples) _, y_pred_ll = make_ml(n_features=1, n_classes=n_classes, random_state=1, n_samples=n_samples) expected_report = """\ precision recall f1-score support 0 0.50 0.67 0.57 24 1 0.51 0.74 0.61 27 2 0.29 0.08 0.12 26 3 0.52 0.56 0.54 27 avg / total 0.45 0.51 0.46 104 """ lb = MultiLabelBinarizer() lb.fit([range(4)]) y_true_bi = lb.transform(y_true_ll) y_pred_bi = lb.transform(y_pred_ll) for y_true, y_pred in [(y_true_ll, y_pred_ll), (y_true_bi, y_pred_bi)]: report = classification_report(y_true, y_pred) assert_equal(report, expected_report) def test_multilabel_zero_one_loss_subset(): # Dense label indicator matrix format y1 = np.array([[0, 1, 1], [1, 0, 1]]) y2 = np.array([[0, 0, 1], [1, 0, 1]]) assert_equal(zero_one_loss(y1, y2), 0.5) assert_equal(zero_one_loss(y1, y1), 0) assert_equal(zero_one_loss(y2, y2), 0) assert_equal(zero_one_loss(y2, np.logical_not(y2)), 1) assert_equal(zero_one_loss(y1, np.logical_not(y1)), 1) assert_equal(zero_one_loss(y1, np.zeros(y1.shape)), 1) assert_equal(zero_one_loss(y2, np.zeros(y1.shape)), 1) with ignore_warnings(): # sequence of sequences is deprecated # List of tuple of label y1 = [(1, 2,), (0, 2,)] y2 = [(2,), (0, 2,)] assert_equal(zero_one_loss(y1, y2), 0.5) assert_equal(zero_one_loss(y1, y1), 0) assert_equal(zero_one_loss(y2, y2), 0) assert_equal(zero_one_loss(y2, [(), ()]), 1) assert_equal(zero_one_loss(y2, [tuple(), (10, )]), 1) def test_multilabel_hamming_loss(): # Dense label indicator matrix format y1 = np.array([[0, 1, 1], [1, 0, 1]]) y2 = np.array([[0, 0, 1], [1, 0, 1]]) assert_equal(hamming_loss(y1, y2), 1 / 6) assert_equal(hamming_loss(y1, y1), 0) assert_equal(hamming_loss(y2, y2), 0) assert_equal(hamming_loss(y2, np.logical_not(y2)), 1) assert_equal(hamming_loss(y1, np.logical_not(y1)), 1) assert_equal(hamming_loss(y1, np.zeros(y1.shape)), 4 / 6) assert_equal(hamming_loss(y2, np.zeros(y1.shape)), 0.5) with ignore_warnings(): # sequence of sequences is deprecated # List of tuple of label y1 = [(1, 2,), (0, 2,)] y2 = [(2,), (0, 2,)] assert_equal(hamming_loss(y1, y2), 1 / 6) assert_equal(hamming_loss(y1, y1), 0) assert_equal(hamming_loss(y2, y2), 0) assert_equal(hamming_loss(y2, [(), ()]), 0.75) assert_equal(hamming_loss(y1, [tuple(), (10, )]), 0.625) assert_almost_equal(hamming_loss(y2, [tuple(), (10, )], classes=np.arange(11)), 0.1818, 2) def test_multilabel_jaccard_similarity_score(): # Dense label indicator matrix format y1 = np.array([[0, 1, 1], [1, 0, 1]]) y2 = np.array([[0, 0, 1], [1, 0, 1]]) # size(y1 \inter y2) = [1, 2] # size(y1 \union y2) = [2, 2] assert_equal(jaccard_similarity_score(y1, y2), 0.75) assert_equal(jaccard_similarity_score(y1, y1), 1) assert_equal(jaccard_similarity_score(y2, y2), 1) assert_equal(jaccard_similarity_score(y2, np.logical_not(y2)), 0) assert_equal(jaccard_similarity_score(y1, np.logical_not(y1)), 0) assert_equal(jaccard_similarity_score(y1, np.zeros(y1.shape)), 0) assert_equal(jaccard_similarity_score(y2, np.zeros(y1.shape)), 0) with ignore_warnings(): # sequence of sequences is deprecated # List of tuple of label y1 = [(1, 2,), (0, 2,)] y2 = [(2,), (0, 2,)] assert_equal(jaccard_similarity_score(y1, y2), 0.75) assert_equal(jaccard_similarity_score(y1, y1), 1) assert_equal(jaccard_similarity_score(y2, y2), 1) assert_equal(jaccard_similarity_score(y2, [(), ()]), 0) # |y3 inter y4 | = [0, 1, 1] # |y3 union y4 | = [2, 1, 3] y3 = [(0,), (1,), (3,)] y4 = [(4,), (4,), (5, 6)] assert_almost_equal(jaccard_similarity_score(y3, y4), 0) # |y5 inter y6 | = [0, 1, 1] # |y5 union y6 | = [2, 1, 3] y5 = [(0,), (1,), (2, 3)] y6 = [(1,), (1,), (2, 0)] assert_almost_equal(jaccard_similarity_score(y5, y6), (1 + 1 / 3) / 3) @ignore_warnings def test_precision_recall_f1_score_multilabel_1(): # Test precision_recall_f1_score on a crafted multilabel example # First crafted example y_true_ll = [(0,), (1,), (2, 3)] y_pred_ll = [(1,), (1,), (2, 0)] lb = LabelBinarizer() lb.fit([range(4)]) y_true_bi = lb.transform(y_true_ll) y_pred_bi = lb.transform(y_pred_ll) for y_true, y_pred in [(y_true_ll, y_pred_ll), (y_true_bi, y_pred_bi)]: p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average=None) #tp = [0, 1, 1, 0] #fn = [1, 0, 0, 1] #fp = [1, 1, 0, 0] # Check per class assert_array_almost_equal(p, [0.0, 0.5, 1.0, 0.0], 2) assert_array_almost_equal(r, [0.0, 1.0, 1.0, 0.0], 2) assert_array_almost_equal(f, [0.0, 1 / 1.5, 1, 0.0], 2) assert_array_almost_equal(s, [1, 1, 1, 1], 2) f2 = fbeta_score(y_true, y_pred, beta=2, average=None) support = s assert_array_almost_equal(f2, [0, 0.83, 1, 0], 2) # Check macro p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="macro") assert_almost_equal(p, 1.5 / 4) assert_almost_equal(r, 0.5) assert_almost_equal(f, 2.5 / 1.5 * 0.25) assert_equal(s, None) assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, average="macro"), np.mean(f2)) # Check micro p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="micro") assert_almost_equal(p, 0.5) assert_almost_equal(r, 0.5) assert_almost_equal(f, 0.5) assert_equal(s, None) assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, average="micro"), (1 + 4) * p * r / (4 * p + r)) # Check weigted p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="weighted") assert_almost_equal(p, 1.5 / 4) assert_almost_equal(r, 0.5) assert_almost_equal(f, 2.5 / 1.5 * 0.25) assert_equal(s, None) assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, average="weighted"), np.average(f2, weights=support)) # Check weigted # |h(x_i) inter y_i | = [0, 1, 1] # |y_i| = [1, 1, 2] # |h(x_i)| = [1, 1, 2] p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="samples") assert_almost_equal(p, 0.5) assert_almost_equal(r, 0.5) assert_almost_equal(f, 0.5) assert_equal(s, None) assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, average="samples"), 0.5) @ignore_warnings def test_precision_recall_f1_score_multilabel_2(): # Test precision_recall_f1_score on a crafted multilabel example 2 # Second crafted example y_true_ll = [(1,), (2,), (2, 3)] y_pred_ll = [(4,), (4,), (2, 1)] lb = LabelBinarizer() lb.fit([range(1, 5)]) y_true_bi = lb.transform(y_true_ll) y_pred_bi = lb.transform(y_pred_ll) for y_true, y_pred in [(y_true_ll, y_pred_ll), (y_true_bi, y_pred_bi)]: # tp = [ 0. 1. 0. 0.] # fp = [ 1. 0. 0. 2.] # fn = [ 1. 1. 1. 0.] p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average=None) assert_array_almost_equal(p, [0.0, 1.0, 0.0, 0.0], 2) assert_array_almost_equal(r, [0.0, 0.5, 0.0, 0.0], 2) assert_array_almost_equal(f, [0.0, 0.66, 0.0, 0.0], 2) assert_array_almost_equal(s, [1, 2, 1, 0], 2) f2 = fbeta_score(y_true, y_pred, beta=2, average=None) support = s assert_array_almost_equal(f2, [0, 0.55, 0, 0], 2) p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="micro") assert_almost_equal(p, 0.25) assert_almost_equal(r, 0.25) assert_almost_equal(f, 2 * 0.25 * 0.25 / 0.5) assert_equal(s, None) assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, average="micro"), (1 + 4) * p * r / (4 * p + r)) p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="macro") assert_almost_equal(p, 0.25) assert_almost_equal(r, 0.125) assert_almost_equal(f, 2 / 12) assert_equal(s, None) assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, average="macro"), np.mean(f2)) p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="weighted") assert_almost_equal(p, 2 / 4) assert_almost_equal(r, 1 / 4) assert_almost_equal(f, 2 / 3 * 2 / 4) assert_equal(s, None) assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, average="weighted"), np.average(f2, weights=support)) p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="samples") # Check weigted # |h(x_i) inter y_i | = [0, 0, 1] # |y_i| = [1, 1, 2] # |h(x_i)| = [1, 1, 2] assert_almost_equal(p, 1 / 6) assert_almost_equal(r, 1 / 6) assert_almost_equal(f, 2 / 4 * 1 / 3) assert_equal(s, None) assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, average="samples"), 0.1666, 2) @ignore_warnings def test_precision_recall_f1_score_with_an_empty_prediction(): y_true_ll = [(1,), (0,), (2, 1,)] y_pred_ll = [tuple(), (3,), (2, 1)] lb = LabelBinarizer() lb.fit([range(4)]) y_true_bi = lb.transform(y_true_ll) y_pred_bi = lb.transform(y_pred_ll) for y_true, y_pred in [(y_true_ll, y_pred_ll), (y_true_bi, y_pred_bi)]: # true_pos = [ 0. 1. 1. 0.] # false_pos = [ 0. 0. 0. 1.] # false_neg = [ 1. 1. 0. 0.] p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average=None) assert_array_almost_equal(p, [0.0, 1.0, 1.0, 0.0], 2) assert_array_almost_equal(r, [0.0, 0.5, 1.0, 0.0], 2) assert_array_almost_equal(f, [0.0, 1 / 1.5, 1, 0.0], 2) assert_array_almost_equal(s, [1, 2, 1, 0], 2) f2 = fbeta_score(y_true, y_pred, beta=2, average=None) support = s assert_array_almost_equal(f2, [0, 0.55, 1, 0], 2) p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="macro") assert_almost_equal(p, 0.5) assert_almost_equal(r, 1.5 / 4) assert_almost_equal(f, 2.5 / (4 * 1.5)) assert_equal(s, None) assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, average="macro"), np.mean(f2)) p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="micro") assert_almost_equal(p, 2 / 3) assert_almost_equal(r, 0.5) assert_almost_equal(f, 2 / 3 / (2 / 3 + 0.5)) assert_equal(s, None) assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, average="micro"), (1 + 4) * p * r / (4 * p + r)) p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="weighted") assert_almost_equal(p, 3 / 4) assert_almost_equal(r, 0.5) assert_almost_equal(f, (2 / 1.5 + 1) / 4) assert_equal(s, None) assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, average="weighted"), np.average(f2, weights=support)) p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="samples") # |h(x_i) inter y_i | = [0, 0, 2] # |y_i| = [1, 1, 2] # |h(x_i)| = [0, 1, 2] assert_almost_equal(p, 1 / 3) assert_almost_equal(r, 1 / 3) assert_almost_equal(f, 1 / 3) assert_equal(s, None) assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, average="samples"), 0.333, 2) def test_precision_recall_f1_no_labels(): y_true = np.zeros((20, 3)) y_pred = np.zeros_like(y_true) # tp = [0, 0, 0] # fn = [0, 0, 0] # fp = [0, 0, 0] # support = [0, 0, 0] # |y_hat_i inter y_i | = [0, 0, 0] # |y_i| = [0, 0, 0] # |y_hat_i| = [0, 0, 0] for beta in [1]: p, r, f, s = assert_warns(UndefinedMetricWarning, precision_recall_fscore_support, y_true, y_pred, average=None, beta=beta) assert_array_almost_equal(p, [0, 0, 0], 2) assert_array_almost_equal(r, [0, 0, 0], 2) assert_array_almost_equal(f, [0, 0, 0], 2) assert_array_almost_equal(s, [0, 0, 0], 2) fbeta = assert_warns(UndefinedMetricWarning, fbeta_score, y_true, y_pred, beta=beta, average=None) assert_array_almost_equal(fbeta, [0, 0, 0], 2) for average in ["macro", "micro", "weighted", "samples"]: p, r, f, s = assert_warns(UndefinedMetricWarning, precision_recall_fscore_support, y_true, y_pred, average=average, beta=beta) assert_almost_equal(p, 0) assert_almost_equal(r, 0) assert_almost_equal(f, 0) assert_equal(s, None) fbeta = assert_warns(UndefinedMetricWarning, fbeta_score, y_true, y_pred, beta=beta, average=average) assert_almost_equal(fbeta, 0) def test_prf_warnings(): # average of per-label scores f, w = precision_recall_fscore_support, UndefinedMetricWarning my_assert = assert_warns_message for average in [None, 'weighted', 'macro']: msg = ('Precision and F-score are ill-defined and ' 'being set to 0.0 in labels with no predicted samples.') my_assert(w, msg, f, [0, 1, 2], [1, 1, 2], average=average) msg = ('Recall and F-score are ill-defined and ' 'being set to 0.0 in labels with no true samples.') my_assert(w, msg, f, [1, 1, 2], [0, 1, 2], average=average) # average of per-sample scores msg = ('Precision and F-score are ill-defined and ' 'being set to 0.0 in samples with no predicted labels.') my_assert(w, msg, f, np.array([[1, 0], [1, 0]]), np.array([[1, 0], [0, 0]]), average='samples') msg = ('Recall and F-score are ill-defined and ' 'being set to 0.0 in samples with no true labels.') my_assert(w, msg, f, np.array([[1, 0], [0, 0]]), np.array([[1, 0], [1, 0]]), average='samples') # single score: micro-average msg = ('Precision and F-score are ill-defined and ' 'being set to 0.0 due to no predicted samples.') my_assert(w, msg, f, np.array([[1, 1], [1, 1]]), np.array([[0, 0], [0, 0]]), average='micro') msg = ('Recall and F-score are ill-defined and ' 'being set to 0.0 due to no true samples.') my_assert(w, msg, f, np.array([[0, 0], [0, 0]]), np.array([[1, 1], [1, 1]]), average='micro') # single postive label msg = ('Precision and F-score are ill-defined and ' 'being set to 0.0 due to no predicted samples.') my_assert(w, msg, f, [1, 1], [-1, -1], average='macro') msg = ('Recall and F-score are ill-defined and ' 'being set to 0.0 due to no true samples.') my_assert(w, msg, f, [-1, -1], [1, 1], average='macro') def test_recall_warnings(): assert_no_warnings(recall_score, np.array([[1, 1], [1, 1]]), np.array([[0, 0], [0, 0]]), average='micro') clean_warning_registry() with warnings.catch_warnings(record=True) as record: warnings.simplefilter('always') recall_score(np.array([[0, 0], [0, 0]]), np.array([[1, 1], [1, 1]]), average='micro') assert_equal(str(record.pop().message), 'Recall is ill-defined and ' 'being set to 0.0 due to no true samples.') def test_precision_warnings(): clean_warning_registry() with warnings.catch_warnings(record=True) as record: warnings.simplefilter('always') precision_score(np.array([[1, 1], [1, 1]]), np.array([[0, 0], [0, 0]]), average='micro') assert_equal(str(record.pop().message), 'Precision is ill-defined and ' 'being set to 0.0 due to no predicted samples.') assert_no_warnings(precision_score, np.array([[0, 0], [0, 0]]), np.array([[1, 1], [1, 1]]), average='micro') def test_fscore_warnings(): clean_warning_registry() with warnings.catch_warnings(record=True) as record: warnings.simplefilter('always') for score in [f1_score, partial(fbeta_score, beta=2)]: score(np.array([[1, 1], [1, 1]]), np.array([[0, 0], [0, 0]]), average='micro') assert_equal(str(record.pop().message), 'F-score is ill-defined and ' 'being set to 0.0 due to no predicted samples.') score(np.array([[0, 0], [0, 0]]), np.array([[1, 1], [1, 1]]), average='micro') assert_equal(str(record.pop().message), 'F-score is ill-defined and ' 'being set to 0.0 due to no true samples.') def test_prf_average_compat(): # Ensure warning if f1_score et al.'s average is implicit for multiclass y_true = [1, 2, 3, 3] y_pred = [1, 2, 3, 1] y_true_bin = [0, 1, 1] y_pred_bin = [0, 1, 0] for metric in [precision_score, recall_score, f1_score, partial(fbeta_score, beta=2)]: score = assert_warns(DeprecationWarning, metric, y_true, y_pred) score_weighted = assert_no_warnings(metric, y_true, y_pred, average='weighted') assert_equal(score, score_weighted, 'average does not act like "weighted" by default') # check binary passes without warning assert_no_warnings(metric, y_true_bin, y_pred_bin) # but binary with pos_label=None should behave like multiclass score = assert_warns(DeprecationWarning, metric, y_true_bin, y_pred_bin, pos_label=None) score_weighted = assert_no_warnings(metric, y_true_bin, y_pred_bin, pos_label=None, average='weighted') assert_equal(score, score_weighted, 'average does not act like "weighted" by default with ' 'binary data and pos_label=None') @ignore_warnings # sequence of sequences is deprecated def test__check_targets(): # Check that _check_targets correctly merges target types, squeezes # output and fails if input lengths differ. IND = 'multilabel-indicator' SEQ = 'multilabel-sequences' MC = 'multiclass' BIN = 'binary' CNT = 'continuous' MMC = 'multiclass-multioutput' MCN = 'continuous-multioutput' # all of length 3 EXAMPLES = [ (IND, np.array([[0, 1, 1], [1, 0, 0], [0, 0, 1]])), # must not be considered binary (IND, np.array([[0, 1], [1, 0], [1, 1]])), (SEQ, [[2, 3], [1], [3]]), (MC, [2, 3, 1]), (BIN, [0, 1, 1]), (CNT, [0., 1.5, 1.]), (MC, np.array([[2], [3], [1]])), (BIN, np.array([[0], [1], [1]])), (CNT, np.array([[0.], [1.5], [1.]])), (MMC, np.array([[0, 2], [1, 3], [2, 3]])), (MCN, np.array([[0.5, 2.], [1.1, 3.], [2., 3.]])), ] # expected type given input types, or None for error # (types will be tried in either order) EXPECTED = { (IND, IND): IND, (SEQ, SEQ): IND, (MC, MC): MC, (BIN, BIN): BIN, (IND, SEQ): None, (MC, SEQ): None, (BIN, SEQ): None, (MC, IND): None, (BIN, IND): None, (BIN, MC): MC, # Disallowed types (CNT, CNT): None, (MMC, MMC): None, (MCN, MCN): None, (IND, CNT): None, (SEQ, CNT): None, (MC, CNT): None, (BIN, CNT): None, (MMC, CNT): None, (MCN, CNT): None, (IND, MMC): None, (SEQ, MMC): None, (MC, MMC): None, (BIN, MMC): None, (MCN, MMC): None, (IND, MCN): None, (SEQ, MCN): None, (MC, MCN): None, (BIN, MCN): None, } for (type1, y1), (type2, y2) in product(EXAMPLES, repeat=2): try: expected = EXPECTED[type1, type2] except KeyError: expected = EXPECTED[type2, type1] if expected is None: assert_raises(ValueError, _check_targets, y1, y2) if type1 != type2: assert_raise_message( ValueError, "Can't handle mix of {0} and {1}".format(type1, type2), _check_targets, y1, y2) else: if type1 not in (BIN, MC, SEQ, IND): assert_raise_message(ValueError, "{0} is not supported".format(type1), _check_targets, y1, y2) else: merged_type, y1out, y2out = _check_targets(y1, y2) assert_equal(merged_type, expected) if merged_type.startswith('multilabel'): assert_equal(y1out.format, 'csr') assert_equal(y2out.format, 'csr') else: assert_array_equal(y1out, np.squeeze(y1)) assert_array_equal(y2out, np.squeeze(y2)) assert_raises(ValueError, _check_targets, y1[:-1], y2) def test_hinge_loss_binary(): y_true = np.array([-1, 1, 1, -1]) pred_decision = np.array([-8.5, 0.5, 1.5, -0.3]) assert_equal(hinge_loss(y_true, pred_decision), 1.2 / 4) y_true = np.array([0, 2, 2, 0]) pred_decision = np.array([-8.5, 0.5, 1.5, -0.3]) assert_equal(hinge_loss(y_true, pred_decision), 1.2 / 4) def test_hinge_loss_multiclass(): pred_decision = np.array([ [0.36, -0.17, -0.58, -0.99], [-0.54, -0.37, -0.48, -0.58], [-1.45, -0.58, -0.38, -0.17], [-0.54, -0.38, -0.48, -0.58], [-2.36, -0.79, -0.27, 0.24], [-1.45, -0.58, -0.38, -0.17] ]) y_true = np.array([0, 1, 2, 1, 3, 2]) dummy_losses = np.array([ 1 - pred_decision[0][0] + pred_decision[0][1], 1 - pred_decision[1][1] + pred_decision[1][2], 1 - pred_decision[2][2] + pred_decision[2][3], 1 - pred_decision[3][1] + pred_decision[3][2], 1 - pred_decision[4][3] + pred_decision[4][2], 1 - pred_decision[5][2] + pred_decision[5][3] ]) dummy_losses[dummy_losses <= 0] = 0 dummy_hinge_loss = np.mean(dummy_losses) assert_equal(hinge_loss(y_true, pred_decision), dummy_hinge_loss) def test_hinge_loss_multiclass_missing_labels_with_labels_none(): y_true = np.array([0, 1, 2, 2]) pred_decision = np.array([ [1.27, 0.034, -0.68, -1.40], [-1.45, -0.58, -0.38, -0.17], [-2.36, -0.79, -0.27, 0.24], [-2.36, -0.79, -0.27, 0.24] ]) error_message = ("Please include all labels in y_true " "or pass labels as third argument") assert_raise_message(ValueError, error_message, hinge_loss, y_true, pred_decision) def test_hinge_loss_multiclass_with_missing_labels(): pred_decision = np.array([ [0.36, -0.17, -0.58, -0.99], [-0.55, -0.38, -0.48, -0.58], [-1.45, -0.58, -0.38, -0.17], [-0.55, -0.38, -0.48, -0.58], [-1.45, -0.58, -0.38, -0.17] ]) y_true = np.array([0, 1, 2, 1, 2]) labels = np.array([0, 1, 2, 3]) dummy_losses = np.array([ 1 - pred_decision[0][0] + pred_decision[0][1], 1 - pred_decision[1][1] + pred_decision[1][2], 1 - pred_decision[2][2] + pred_decision[2][3], 1 - pred_decision[3][1] + pred_decision[3][2], 1 - pred_decision[4][2] + pred_decision[4][3] ]) dummy_losses[dummy_losses <= 0] = 0 dummy_hinge_loss = np.mean(dummy_losses) assert_equal(hinge_loss(y_true, pred_decision, labels=labels), dummy_hinge_loss) def test_hinge_loss_multiclass_invariance_lists(): # Currently, invariance of string and integer labels cannot be tested # in common invariance tests because invariance tests for multiclass # decision functions is not implemented yet. y_true = ['blue', 'green', 'red', 'green', 'white', 'red'] pred_decision = [ [0.36, -0.17, -0.58, -0.99], [-0.55, -0.38, -0.48, -0.58], [-1.45, -0.58, -0.38, -0.17], [-0.55, -0.38, -0.48, -0.58], [-2.36, -0.79, -0.27, 0.24], [-1.45, -0.58, -0.38, -0.17]] dummy_losses = np.array([ 1 - pred_decision[0][0] + pred_decision[0][1], 1 - pred_decision[1][1] + pred_decision[1][2], 1 - pred_decision[2][2] + pred_decision[2][3], 1 - pred_decision[3][1] + pred_decision[3][2], 1 - pred_decision[4][3] + pred_decision[4][2], 1 - pred_decision[5][2] + pred_decision[5][3] ]) dummy_losses[dummy_losses <= 0] = 0 dummy_hinge_loss = np.mean(dummy_losses) assert_equal(hinge_loss(y_true, pred_decision), dummy_hinge_loss) def test_log_loss(): # binary case with symbolic labels ("no" < "yes") y_true = ["no", "no", "no", "yes", "yes", "yes"] y_pred = np.array([[0.5, 0.5], [0.1, 0.9], [0.01, 0.99], [0.9, 0.1], [0.75, 0.25], [0.001, 0.999]]) loss = log_loss(y_true, y_pred) assert_almost_equal(loss, 1.8817971) # multiclass case; adapted from http://bit.ly/RJJHWA y_true = [1, 0, 2] y_pred = [[0.2, 0.7, 0.1], [0.6, 0.2, 0.2], [0.6, 0.1, 0.3]] loss = log_loss(y_true, y_pred, normalize=True) assert_almost_equal(loss, 0.6904911) # check that we got all the shapes and axes right # by doubling the length of y_true and y_pred y_true *= 2 y_pred *= 2 loss = log_loss(y_true, y_pred, normalize=False) assert_almost_equal(loss, 0.6904911 * 6, decimal=6) # check eps and handling of absolute zero and one probabilities y_pred = np.asarray(y_pred) > .5 loss = log_loss(y_true, y_pred, normalize=True, eps=.1) assert_almost_equal(loss, log_loss(y_true, np.clip(y_pred, .1, .9))) # raise error if number of classes are not equal. y_true = [1, 0, 2] y_pred = [[0.2, 0.7], [0.6, 0.5], [0.4, 0.1]] assert_raises(ValueError, log_loss, y_true, y_pred) # case when y_true is a string array object y_true = ["ham", "spam", "spam", "ham"] y_pred = [[0.2, 0.7], [0.6, 0.5], [0.4, 0.1], [0.7, 0.2]] loss = log_loss(y_true, y_pred) assert_almost_equal(loss, 1.0383217, decimal=6) def test_brier_score_loss(): # Check brier_score_loss function y_true = np.array([0, 1, 1, 0, 1, 1]) y_pred = np.array([0.1, 0.8, 0.9, 0.3, 1., 0.95]) true_score = linalg.norm(y_true - y_pred) ** 2 / len(y_true) assert_almost_equal(brier_score_loss(y_true, y_true), 0.0) assert_almost_equal(brier_score_loss(y_true, y_pred), true_score) assert_almost_equal(brier_score_loss(1. + y_true, y_pred), true_score) assert_almost_equal(brier_score_loss(2 * y_true - 1, y_pred), true_score) assert_raises(ValueError, brier_score_loss, y_true, y_pred[1:]) assert_raises(ValueError, brier_score_loss, y_true, y_pred + 1.) assert_raises(ValueError, brier_score_loss, y_true, y_pred - 1.)
bsd-3-clause
lmzintgraf/MultiMAuS
experiments/result_handling.py
1
4477
from os.path import isdir, join, dirname, exists from os import mkdir import pickle import numpy as np import datetime from simulator import parameters import pandas as pd FOLDER_RESULTS = join(dirname(__file__), 'results') FILE_RESULTS_IDX = join(FOLDER_RESULTS, 'curr_idx.txt') def get_result_idx(): for line in open(FILE_RESULTS_IDX): if line.strip(): # line contains eol character(s) return int(line) def update_result_idx(old_result_idx): # increase result counter by one f = open(FILE_RESULTS_IDX, 'w+') f.write(str(old_result_idx + 1)) f.close() def get_params_path(result_idx): return join(FOLDER_RESULTS, '{}_parameters.pkl'.format(result_idx)) def get_transaction_log_path(result_idx): return join(FOLDER_RESULTS, '{}_transaction_log.csv'.format(result_idx)) def get_satisfaction_log_path(result_idx): return join(FOLDER_RESULTS, '{}_satisfaction_log.csv'.format(result_idx)) def save_results(model): # create a folder to save results in if not isdir(FOLDER_RESULTS): mkdir(FOLDER_RESULTS) if not exists(FILE_RESULTS_IDX): f = open(FILE_RESULTS_IDX, 'w+') f.write(str(0)) f.close() result_idx = get_result_idx() # retrieve parameters for current experiment parameters = model.parameters # add the name of the authenticator to the parameters parameters['authenticator'] = model.authenticator.__class__.__name__ # save the parameters pickle.dump(parameters, open(get_params_path(result_idx), 'wb'), pickle.HIGHEST_PROTOCOL) # save the transaction logs agent_vars = model.log_collector.get_agent_vars_dataframe() agent_vars.index = agent_vars.index.droplevel(1) path_transaction_log = get_transaction_log_path(result_idx) agent_vars.to_csv(path_transaction_log, index_label=False) # save the satisfaction per timestep model_vars = model.log_collector.get_model_vars_dataframe() path_satisfaction_log = get_satisfaction_log_path(result_idx) model_vars.to_csv(path_satisfaction_log, index_label=False) # save some customer properties FOLDER_CUST_PROPS = join(FOLDER_RESULTS, '{}_cust_props'.format(result_idx)) mkdir(FOLDER_CUST_PROPS) for i in range(5): # for customers np.save(join(FOLDER_CUST_PROPS, 'cust{}_trans_prob_monthday'.format(i)), model.customers[i].trans_prob_monthday) np.save(join(FOLDER_CUST_PROPS, 'cust{}_trans_prob_month'.format(i)), model.customers[i].trans_prob_month) np.save(join(FOLDER_CUST_PROPS, 'cust{}_trans_prob_hour'.format(i)), model.customers[i].trans_prob_hour) np.save(join(FOLDER_CUST_PROPS, 'cust{}_trans_prob_weekday'.format(i)), model.customers[i].trans_prob_weekday) # for fraudsters np.save(join(FOLDER_CUST_PROPS, 'fraud{}_trans_prob_monthday'.format(i)), model.fraudsters[i].trans_prob_monthday) np.save(join(FOLDER_CUST_PROPS, 'fraud{}_trans_prob_month'.format(i)), model.fraudsters[i].trans_prob_month) np.save(join(FOLDER_CUST_PROPS, 'fraud{}_trans_prob_hour'.format(i)), model.fraudsters[i].trans_prob_hour) np.save(join(FOLDER_CUST_PROPS, 'fraud{}_trans_prob_weekday'.format(i)), model.fraudsters[i].trans_prob_weekday) print("saved results under result index {}".format(result_idx)) update_result_idx(result_idx) def get_parameters(result_idx): return pickle.load(open(get_params_path(result_idx), 'rb')) def check_parameter_consistency(params1): params2 = parameters.get_default_parameters() # make sure we didn't accidentally change the input parameters for key in params1.keys(): try: if isinstance(params1[key], np.ndarray): assert np.sum(params1[key] - params2[key]) == 0 elif isinstance(params1[key], float) or isinstance(params1[key], int): assert params1[key] - params2[key] == 0 elif isinstance(params1[key], datetime.date): pass elif isinstance(params1[key], pd.DataFrame): assert np.sum(params1[key].values - params2[key].values) == 0 elif isinstance(params1[key], list): for i in range(len(params1[key])): assert np.sum(params1[key][i].values - params2[key][i].values) == 0 else: print("unknown type", key, type(params1[key])) except AssertionError: print("!! params changed:", key)
mit
Kongsea/tensorflow
tensorflow/contrib/learn/python/learn/estimators/estimator_test.py
9
53510
# 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 Estimator.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import itertools import json import os import tempfile import numpy as np import six from six.moves import xrange # pylint: disable=redefined-builtin from google.protobuf import text_format from tensorflow.contrib import learn from tensorflow.contrib import lookup from tensorflow.python.training import training_util from tensorflow.contrib.layers.python.layers import feature_column as feature_column_lib from tensorflow.contrib.layers.python.layers import optimizers from tensorflow.contrib.learn.python.learn import experiment from tensorflow.contrib.learn.python.learn import models from tensorflow.contrib.learn.python.learn import monitors as monitors_lib from tensorflow.contrib.learn.python.learn.datasets import base from tensorflow.contrib.learn.python.learn.estimators import _sklearn from tensorflow.contrib.learn.python.learn.estimators import constants from tensorflow.contrib.learn.python.learn.estimators import estimator from tensorflow.contrib.learn.python.learn.estimators import linear from tensorflow.contrib.learn.python.learn.estimators import model_fn from tensorflow.contrib.learn.python.learn.estimators import run_config from tensorflow.contrib.learn.python.learn.utils import input_fn_utils from tensorflow.contrib.metrics.python.ops import metric_ops from tensorflow.contrib.testing.python.framework import util_test from tensorflow.python.client import session as session_lib from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.lib.io import file_io from tensorflow.python.ops import array_ops from tensorflow.python.ops import check_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import parsing_ops from tensorflow.python.ops import variables as variables_lib from tensorflow.python.platform import gfile from tensorflow.python.platform import test from tensorflow.python.saved_model import loader from tensorflow.python.saved_model import tag_constants from tensorflow.python.summary import summary from tensorflow.python.training import basic_session_run_hooks from tensorflow.python.training import checkpoint_state_pb2 from tensorflow.python.training import input as input_lib from tensorflow.python.training import monitored_session from tensorflow.python.training import saver as saver_lib from tensorflow.python.training import session_run_hook from tensorflow.python.util import compat _BOSTON_INPUT_DIM = 13 _IRIS_INPUT_DIM = 4 def boston_input_fn(num_epochs=None): boston = base.load_boston() features = input_lib.limit_epochs( array_ops.reshape( constant_op.constant(boston.data), [-1, _BOSTON_INPUT_DIM]), num_epochs=num_epochs) labels = array_ops.reshape(constant_op.constant(boston.target), [-1, 1]) return features, labels def iris_input_fn(): iris = base.load_iris() features = array_ops.reshape( constant_op.constant(iris.data), [-1, _IRIS_INPUT_DIM]) labels = array_ops.reshape(constant_op.constant(iris.target), [-1]) return features, labels def iris_input_fn_labels_dict(): iris = base.load_iris() features = array_ops.reshape( constant_op.constant(iris.data), [-1, _IRIS_INPUT_DIM]) labels = { 'labels': array_ops.reshape(constant_op.constant(iris.target), [-1]) } return features, labels def boston_eval_fn(): boston = base.load_boston() n_examples = len(boston.target) features = array_ops.reshape( constant_op.constant(boston.data), [n_examples, _BOSTON_INPUT_DIM]) labels = array_ops.reshape( constant_op.constant(boston.target), [n_examples, 1]) return array_ops.concat([features, features], 0), array_ops.concat( [labels, labels], 0) def extract(data, key): if isinstance(data, dict): assert key in data return data[key] else: return data def linear_model_params_fn(features, labels, mode, params): features = extract(features, 'input') labels = extract(labels, 'labels') assert mode in (model_fn.ModeKeys.TRAIN, model_fn.ModeKeys.EVAL, model_fn.ModeKeys.INFER) prediction, loss = (models.linear_regression_zero_init(features, labels)) train_op = optimizers.optimize_loss( loss, training_util.get_global_step(), optimizer='Adagrad', learning_rate=params['learning_rate']) return prediction, loss, train_op def linear_model_fn(features, labels, mode): features = extract(features, 'input') labels = extract(labels, 'labels') assert mode in (model_fn.ModeKeys.TRAIN, model_fn.ModeKeys.EVAL, model_fn.ModeKeys.INFER) if isinstance(features, dict): (_, features), = features.items() prediction, loss = (models.linear_regression_zero_init(features, labels)) train_op = optimizers.optimize_loss( loss, training_util.get_global_step(), optimizer='Adagrad', learning_rate=0.1) return prediction, loss, train_op def linear_model_fn_with_model_fn_ops(features, labels, mode): """Same as linear_model_fn, but returns `ModelFnOps`.""" assert mode in (model_fn.ModeKeys.TRAIN, model_fn.ModeKeys.EVAL, model_fn.ModeKeys.INFER) prediction, loss = (models.linear_regression_zero_init(features, labels)) train_op = optimizers.optimize_loss( loss, training_util.get_global_step(), optimizer='Adagrad', learning_rate=0.1) return model_fn.ModelFnOps( mode=mode, predictions=prediction, loss=loss, train_op=train_op) def logistic_model_no_mode_fn(features, labels): features = extract(features, 'input') labels = extract(labels, 'labels') labels = array_ops.one_hot(labels, 3, 1, 0) prediction, loss = (models.logistic_regression_zero_init(features, labels)) train_op = optimizers.optimize_loss( loss, training_util.get_global_step(), optimizer='Adagrad', learning_rate=0.1) return { 'class': math_ops.argmax(prediction, 1), 'prob': prediction }, loss, train_op VOCAB_FILE_CONTENT = 'emerson\nlake\npalmer\n' EXTRA_FILE_CONTENT = 'kermit\npiggy\nralph\n' def _build_estimator_for_export_tests(tmpdir): def _input_fn(): iris = base.load_iris() return { 'feature': constant_op.constant( iris.data, dtype=dtypes.float32) }, constant_op.constant( iris.target, shape=[150], dtype=dtypes.int32) feature_columns = [ feature_column_lib.real_valued_column( 'feature', dimension=4) ] est = linear.LinearRegressor(feature_columns) est.fit(input_fn=_input_fn, steps=20) feature_spec = feature_column_lib.create_feature_spec_for_parsing( feature_columns) serving_input_fn = input_fn_utils.build_parsing_serving_input_fn(feature_spec) # hack in an op that uses an asset, in order to test asset export. # this is not actually valid, of course. def serving_input_fn_with_asset(): features, labels, inputs = serving_input_fn() vocab_file_name = os.path.join(tmpdir, 'my_vocab_file') vocab_file = gfile.GFile(vocab_file_name, mode='w') vocab_file.write(VOCAB_FILE_CONTENT) vocab_file.close() hashtable = lookup.HashTable( lookup.TextFileStringTableInitializer(vocab_file_name), 'x') features['bogus_lookup'] = hashtable.lookup( math_ops.to_int64(features['feature'])) return input_fn_utils.InputFnOps(features, labels, inputs) return est, serving_input_fn_with_asset def _build_estimator_for_resource_export_test(): def _input_fn(): iris = base.load_iris() return { 'feature': constant_op.constant(iris.data, dtype=dtypes.float32) }, constant_op.constant( iris.target, shape=[150], dtype=dtypes.int32) feature_columns = [ feature_column_lib.real_valued_column('feature', dimension=4) ] def resource_constant_model_fn(unused_features, unused_labels, mode): """A model_fn that loads a constant from a resource and serves it.""" assert mode in (model_fn.ModeKeys.TRAIN, model_fn.ModeKeys.EVAL, model_fn.ModeKeys.INFER) const = constant_op.constant(-1, dtype=dtypes.int64) table = lookup.MutableHashTable( dtypes.string, dtypes.int64, const, name='LookupTableModel') update_global_step = training_util.get_global_step().assign_add(1) if mode in (model_fn.ModeKeys.TRAIN, model_fn.ModeKeys.EVAL): key = constant_op.constant(['key']) value = constant_op.constant([42], dtype=dtypes.int64) train_op_1 = table.insert(key, value) training_state = lookup.MutableHashTable( dtypes.string, dtypes.int64, const, name='LookupTableTrainingState') training_op_2 = training_state.insert(key, value) return (const, const, control_flow_ops.group(train_op_1, training_op_2, update_global_step)) if mode == model_fn.ModeKeys.INFER: key = constant_op.constant(['key']) prediction = table.lookup(key) return prediction, const, update_global_step est = estimator.Estimator(model_fn=resource_constant_model_fn) est.fit(input_fn=_input_fn, steps=1) feature_spec = feature_column_lib.create_feature_spec_for_parsing( feature_columns) serving_input_fn = input_fn_utils.build_parsing_serving_input_fn(feature_spec) return est, serving_input_fn class CheckCallsMonitor(monitors_lib.BaseMonitor): def __init__(self, expect_calls): super(CheckCallsMonitor, self).__init__() self.begin_calls = None self.end_calls = None self.expect_calls = expect_calls def begin(self, max_steps): self.begin_calls = 0 self.end_calls = 0 def step_begin(self, step): self.begin_calls += 1 return {} def step_end(self, step, outputs): self.end_calls += 1 return False def end(self): assert (self.end_calls == self.expect_calls and self.begin_calls == self.expect_calls) def _model_fn_ops( expected_features, expected_labels, actual_features, actual_labels, mode): assert_ops = tuple([ check_ops.assert_equal( expected_features[k], actual_features[k], name='assert_%s' % k) for k in expected_features ] + [ check_ops.assert_equal( expected_labels, actual_labels, name='assert_labels') ]) with ops.control_dependencies(assert_ops): return model_fn.ModelFnOps( mode=mode, predictions=constant_op.constant(0.), loss=constant_op.constant(0.), train_op=training_util.get_global_step().assign_add(1)) def _make_input_fn(features, labels): def _input_fn(): return { k: constant_op.constant(v) for k, v in six.iteritems(features) }, constant_op.constant(labels) return _input_fn class EstimatorModelFnTest(test.TestCase): def testModelFnArgs(self): features = {'x': 42., 'y': 43.} labels = 44. expected_params = {'some_param': 'some_value'} expected_config = run_config.RunConfig() expected_config.i_am_test = True # TODO(ptucker): We have to roll our own mock since Estimator._get_arguments # doesn't work with mock fns. model_fn_call_count = [0] # `features` and `labels` are passed by position, `arg0` and `arg1` here. def _model_fn(arg0, arg1, mode, params, config): model_fn_call_count[0] += 1 self.assertItemsEqual(features.keys(), arg0.keys()) self.assertEqual(model_fn.ModeKeys.TRAIN, mode) self.assertEqual(expected_params, params) self.assertTrue(config.i_am_test) return _model_fn_ops(features, labels, arg0, arg1, mode) est = estimator.Estimator( model_fn=_model_fn, params=expected_params, config=expected_config) self.assertEqual(0, model_fn_call_count[0]) est.fit(input_fn=_make_input_fn(features, labels), steps=1) self.assertEqual(1, model_fn_call_count[0]) def testPartialModelFnArgs(self): features = {'x': 42., 'y': 43.} labels = 44. expected_params = {'some_param': 'some_value'} expected_config = run_config.RunConfig() expected_config.i_am_test = True expected_foo = 45. expected_bar = 46. # TODO(ptucker): We have to roll our own mock since Estimator._get_arguments # doesn't work with mock fns. model_fn_call_count = [0] # `features` and `labels` are passed by position, `arg0` and `arg1` here. def _model_fn(arg0, arg1, foo, mode, params, config, bar): model_fn_call_count[0] += 1 self.assertEqual(expected_foo, foo) self.assertEqual(expected_bar, bar) self.assertItemsEqual(features.keys(), arg0.keys()) self.assertEqual(model_fn.ModeKeys.TRAIN, mode) self.assertEqual(expected_params, params) self.assertTrue(config.i_am_test) return _model_fn_ops(features, labels, arg0, arg1, mode) partial_model_fn = functools.partial( _model_fn, foo=expected_foo, bar=expected_bar) est = estimator.Estimator( model_fn=partial_model_fn, params=expected_params, config=expected_config) self.assertEqual(0, model_fn_call_count[0]) est.fit(input_fn=_make_input_fn(features, labels), steps=1) self.assertEqual(1, model_fn_call_count[0]) def testModelFnWithModelDir(self): expected_param = {'some_param': 'some_value'} expected_model_dir = tempfile.mkdtemp() def _argument_checker(features, labels, mode, params, config=None, model_dir=None): _, _, _ = features, labels, config self.assertEqual(model_fn.ModeKeys.TRAIN, mode) self.assertEqual(expected_param, params) self.assertEqual(model_dir, expected_model_dir) return (constant_op.constant(0.), constant_op.constant(0.), training_util.get_global_step().assign_add(1)) est = estimator.Estimator(model_fn=_argument_checker, params=expected_param, model_dir=expected_model_dir) est.fit(input_fn=boston_input_fn, steps=1) def testInvalidModelFn_no_train_op(self): def _invalid_model_fn(features, labels): # pylint: disable=unused-argument w = variables_lib.Variable(42.0, 'weight') update_global_step = training_util.get_global_step().assign_add(1) with ops.control_dependencies([update_global_step]): loss = 100.0 - w return None, loss, None est = estimator.Estimator(model_fn=_invalid_model_fn) with self.assertRaisesRegexp(ValueError, 'Missing train_op'): est.fit(input_fn=boston_input_fn, steps=1) def testInvalidModelFn_no_loss(self): def _invalid_model_fn(features, labels, mode): # pylint: disable=unused-argument w = variables_lib.Variable(42.0, 'weight') loss = 100.0 - w update_global_step = training_util.get_global_step().assign_add(1) with ops.control_dependencies([update_global_step]): train_op = w.assign_add(loss / 100.0) predictions = loss if mode == model_fn.ModeKeys.EVAL: loss = None return predictions, loss, train_op est = estimator.Estimator(model_fn=_invalid_model_fn) est.fit(input_fn=boston_input_fn, steps=1) with self.assertRaisesRegexp(ValueError, 'Missing loss'): est.evaluate(input_fn=boston_eval_fn, steps=1) def testInvalidModelFn_no_prediction(self): def _invalid_model_fn(features, labels): # pylint: disable=unused-argument w = variables_lib.Variable(42.0, 'weight') loss = 100.0 - w update_global_step = training_util.get_global_step().assign_add(1) with ops.control_dependencies([update_global_step]): train_op = w.assign_add(loss / 100.0) return None, loss, train_op est = estimator.Estimator(model_fn=_invalid_model_fn) est.fit(input_fn=boston_input_fn, steps=1) with self.assertRaisesRegexp(ValueError, 'Missing prediction'): est.evaluate(input_fn=boston_eval_fn, steps=1) with self.assertRaisesRegexp(ValueError, 'Missing prediction'): est.predict(input_fn=boston_input_fn) with self.assertRaisesRegexp(ValueError, 'Missing prediction'): est.predict( input_fn=functools.partial( boston_input_fn, num_epochs=1), as_iterable=True) def testModelFnScaffoldInTraining(self): self.is_init_fn_called = False def _init_fn(scaffold, session): _, _ = scaffold, session self.is_init_fn_called = True def _model_fn_scaffold(features, labels, mode): _, _ = features, labels return model_fn.ModelFnOps( mode=mode, predictions=constant_op.constant(0.), loss=constant_op.constant(0.), train_op=training_util.get_global_step().assign_add(1), scaffold=monitored_session.Scaffold(init_fn=_init_fn)) est = estimator.Estimator(model_fn=_model_fn_scaffold) est.fit(input_fn=boston_input_fn, steps=1) self.assertTrue(self.is_init_fn_called) def testModelFnScaffoldSaverUsage(self): def _model_fn_scaffold(features, labels, mode): _, _ = features, labels variables_lib.Variable(1., 'weight') real_saver = saver_lib.Saver() self.mock_saver = test.mock.Mock( wraps=real_saver, saver_def=real_saver.saver_def) return model_fn.ModelFnOps( mode=mode, predictions=constant_op.constant([[1.]]), loss=constant_op.constant(0.), train_op=training_util.get_global_step().assign_add(1), scaffold=monitored_session.Scaffold(saver=self.mock_saver)) def input_fn(): return { 'x': constant_op.constant([[1.]]), }, constant_op.constant([[1.]]) est = estimator.Estimator(model_fn=_model_fn_scaffold) est.fit(input_fn=input_fn, steps=1) self.assertTrue(self.mock_saver.save.called) est.evaluate(input_fn=input_fn, steps=1) self.assertTrue(self.mock_saver.restore.called) est.predict(input_fn=input_fn) self.assertTrue(self.mock_saver.restore.called) def serving_input_fn(): serialized_tf_example = array_ops.placeholder(dtype=dtypes.string, shape=[None], name='input_example_tensor') features, labels = input_fn() return input_fn_utils.InputFnOps( features, labels, {'examples': serialized_tf_example}) est.export_savedmodel(os.path.join(est.model_dir, 'export'), serving_input_fn) self.assertTrue(self.mock_saver.restore.called) class EstimatorTest(test.TestCase): def testExperimentIntegration(self): exp = experiment.Experiment( estimator=estimator.Estimator(model_fn=linear_model_fn), train_input_fn=boston_input_fn, eval_input_fn=boston_input_fn) exp.test() def testCheckpointSaverHookSuppressesTheDefaultOne(self): saver_hook = test.mock.Mock( spec=basic_session_run_hooks.CheckpointSaverHook) saver_hook.before_run.return_value = None est = estimator.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, steps=1, monitors=[saver_hook]) # test nothing is saved, due to suppressing default saver with self.assertRaises(learn.NotFittedError): est.evaluate(input_fn=boston_input_fn, steps=1) def testCustomConfig(self): test_random_seed = 5783452 class TestInput(object): def __init__(self): self.random_seed = 0 def config_test_input_fn(self): self.random_seed = ops.get_default_graph().seed return constant_op.constant([[1.]]), constant_op.constant([1.]) config = run_config.RunConfig(tf_random_seed=test_random_seed) test_input = TestInput() est = estimator.Estimator(model_fn=linear_model_fn, config=config) est.fit(input_fn=test_input.config_test_input_fn, steps=1) # If input_fn ran, it will have given us the random seed set on the graph. self.assertEquals(test_random_seed, test_input.random_seed) def testRunConfigModelDir(self): config = run_config.RunConfig(model_dir='test_dir') est = estimator.Estimator(model_fn=linear_model_fn, config=config) self.assertEqual('test_dir', est.config.model_dir) self.assertEqual('test_dir', est.model_dir) def testModelDirAndRunConfigModelDir(self): config = run_config.RunConfig(model_dir='test_dir') est = estimator.Estimator(model_fn=linear_model_fn, config=config, model_dir='test_dir') self.assertEqual('test_dir', est.config.model_dir) with self.assertRaisesRegexp( ValueError, 'model_dir are set both in constructor and RunConfig, ' 'but with different'): estimator.Estimator(model_fn=linear_model_fn, config=config, model_dir='different_dir') def testModelDirIsCopiedToRunConfig(self): config = run_config.RunConfig() self.assertIsNone(config.model_dir) est = estimator.Estimator(model_fn=linear_model_fn, model_dir='test_dir', config=config) self.assertEqual('test_dir', est.config.model_dir) self.assertEqual('test_dir', est.model_dir) def testModelDirAsTempDir(self): with test.mock.patch.object(tempfile, 'mkdtemp', return_value='temp_dir'): est = estimator.Estimator(model_fn=linear_model_fn) self.assertEqual('temp_dir', est.config.model_dir) self.assertEqual('temp_dir', est.model_dir) def testCheckInputs(self): est = estimator.SKCompat(estimator.Estimator(model_fn=linear_model_fn)) # Lambdas so we have to different objects to compare right_features = lambda: np.ones(shape=[7, 8], dtype=np.float32) right_labels = lambda: np.ones(shape=[7, 10], dtype=np.int32) est.fit(right_features(), right_labels(), steps=1) # TODO(wicke): This does not fail for np.int32 because of data_feeder magic. wrong_type_features = np.ones(shape=[7, 8], dtype=np.int64) wrong_size_features = np.ones(shape=[7, 10]) wrong_type_labels = np.ones(shape=[7, 10], dtype=np.float32) wrong_size_labels = np.ones(shape=[7, 11]) est.fit(x=right_features(), y=right_labels(), steps=1) with self.assertRaises(ValueError): est.fit(x=wrong_type_features, y=right_labels(), steps=1) with self.assertRaises(ValueError): est.fit(x=wrong_size_features, y=right_labels(), steps=1) with self.assertRaises(ValueError): est.fit(x=right_features(), y=wrong_type_labels, steps=1) with self.assertRaises(ValueError): est.fit(x=right_features(), y=wrong_size_labels, steps=1) def testBadInput(self): est = estimator.Estimator(model_fn=linear_model_fn) self.assertRaisesRegexp( ValueError, 'Either x or input_fn must be provided.', est.fit, x=None, input_fn=None, steps=1) self.assertRaisesRegexp( ValueError, 'Can not provide both input_fn and x or y', est.fit, x='X', input_fn=iris_input_fn, steps=1) self.assertRaisesRegexp( ValueError, 'Can not provide both input_fn and x or y', est.fit, y='Y', input_fn=iris_input_fn, steps=1) self.assertRaisesRegexp( ValueError, 'Can not provide both input_fn and batch_size', est.fit, input_fn=iris_input_fn, batch_size=100, steps=1) self.assertRaisesRegexp( ValueError, 'Inputs cannot be tensors. Please provide input_fn.', est.fit, x=constant_op.constant(1.), steps=1) def testUntrained(self): boston = base.load_boston() est = estimator.SKCompat(estimator.Estimator(model_fn=linear_model_fn)) with self.assertRaises(learn.NotFittedError): _ = est.score(x=boston.data, y=boston.target.astype(np.float64)) with self.assertRaises(learn.NotFittedError): est.predict(x=boston.data) def testContinueTraining(self): boston = base.load_boston() output_dir = tempfile.mkdtemp() est = estimator.SKCompat( estimator.Estimator( model_fn=linear_model_fn, model_dir=output_dir)) float64_labels = boston.target.astype(np.float64) est.fit(x=boston.data, y=float64_labels, steps=50) scores = est.score( x=boston.data, y=float64_labels, metrics={'MSE': metric_ops.streaming_mean_squared_error}) del est # Create another estimator object with the same output dir. est2 = estimator.SKCompat( estimator.Estimator( model_fn=linear_model_fn, model_dir=output_dir)) # Check we can evaluate and predict. scores2 = est2.score( x=boston.data, y=float64_labels, metrics={'MSE': metric_ops.streaming_mean_squared_error}) self.assertAllClose(scores['MSE'], scores2['MSE']) predictions = np.array(list(est2.predict(x=boston.data))) other_score = _sklearn.mean_squared_error(predictions, float64_labels) self.assertAllClose(scores['MSE'], other_score) # Check we can keep training. est2.fit(x=boston.data, y=float64_labels, steps=100) scores3 = est2.score( x=boston.data, y=float64_labels, metrics={'MSE': metric_ops.streaming_mean_squared_error}) self.assertLess(scores3['MSE'], scores['MSE']) def test_checkpoint_contains_relative_paths(self): tmpdir = tempfile.mkdtemp() est = estimator.Estimator( model_dir=tmpdir, model_fn=linear_model_fn_with_model_fn_ops) est.fit(input_fn=boston_input_fn, steps=5) checkpoint_file_content = file_io.read_file_to_string( os.path.join(tmpdir, 'checkpoint')) ckpt = checkpoint_state_pb2.CheckpointState() text_format.Merge(checkpoint_file_content, ckpt) self.assertEqual(ckpt.model_checkpoint_path, 'model.ckpt-5') self.assertAllEqual( ['model.ckpt-1', 'model.ckpt-5'], ckpt.all_model_checkpoint_paths) def test_train_save_copy_reload(self): tmpdir = tempfile.mkdtemp() model_dir1 = os.path.join(tmpdir, 'model_dir1') est1 = estimator.Estimator( model_dir=model_dir1, model_fn=linear_model_fn_with_model_fn_ops) est1.fit(input_fn=boston_input_fn, steps=5) model_dir2 = os.path.join(tmpdir, 'model_dir2') os.renames(model_dir1, model_dir2) est2 = estimator.Estimator( model_dir=model_dir2, model_fn=linear_model_fn_with_model_fn_ops) self.assertEqual(5, est2.get_variable_value('global_step')) est2.fit(input_fn=boston_input_fn, steps=5) self.assertEqual(10, est2.get_variable_value('global_step')) def testEstimatorParams(self): boston = base.load_boston() est = estimator.SKCompat( estimator.Estimator( model_fn=linear_model_params_fn, params={'learning_rate': 0.01})) est.fit(x=boston.data, y=boston.target, steps=100) def testHooksNotChanged(self): est = estimator.Estimator(model_fn=logistic_model_no_mode_fn) # We pass empty array and expect it to remain empty after calling # fit and evaluate. Requires inside to copy this array if any hooks were # added. my_array = [] est.fit(input_fn=iris_input_fn, steps=100, monitors=my_array) _ = est.evaluate(input_fn=iris_input_fn, steps=1, hooks=my_array) self.assertEqual(my_array, []) def testIrisIterator(self): iris = base.load_iris() est = estimator.Estimator(model_fn=logistic_model_no_mode_fn) x_iter = itertools.islice(iris.data, 100) y_iter = itertools.islice(iris.target, 100) estimator.SKCompat(est).fit(x_iter, y_iter, steps=20) eval_result = est.evaluate(input_fn=iris_input_fn, steps=1) x_iter_eval = itertools.islice(iris.data, 100) y_iter_eval = itertools.islice(iris.target, 100) score_result = estimator.SKCompat(est).score(x_iter_eval, y_iter_eval) print(score_result) self.assertItemsEqual(eval_result.keys(), score_result.keys()) self.assertItemsEqual(['global_step', 'loss'], score_result.keys()) predictions = estimator.SKCompat(est).predict(x=iris.data)['class'] self.assertEqual(len(predictions), iris.target.shape[0]) def testIrisIteratorArray(self): iris = base.load_iris() est = estimator.Estimator(model_fn=logistic_model_no_mode_fn) x_iter = itertools.islice(iris.data, 100) y_iter = (np.array(x) for x in iris.target) est.fit(x_iter, y_iter, steps=100) _ = est.evaluate(input_fn=iris_input_fn, steps=1) _ = six.next(est.predict(x=iris.data))['class'] def testIrisIteratorPlainInt(self): iris = base.load_iris() est = estimator.Estimator(model_fn=logistic_model_no_mode_fn) x_iter = itertools.islice(iris.data, 100) y_iter = (v for v in iris.target) est.fit(x_iter, y_iter, steps=100) _ = est.evaluate(input_fn=iris_input_fn, steps=1) _ = six.next(est.predict(x=iris.data))['class'] def testIrisTruncatedIterator(self): iris = base.load_iris() est = estimator.Estimator(model_fn=logistic_model_no_mode_fn) x_iter = itertools.islice(iris.data, 50) y_iter = ([np.int32(v)] for v in iris.target) est.fit(x_iter, y_iter, steps=100) def testTrainStepsIsIncremental(self): est = estimator.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, steps=10) self.assertEqual(10, est.get_variable_value('global_step')) est.fit(input_fn=boston_input_fn, steps=15) self.assertEqual(25, est.get_variable_value('global_step')) def testTrainMaxStepsIsNotIncremental(self): est = estimator.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, max_steps=10) self.assertEqual(10, est.get_variable_value('global_step')) est.fit(input_fn=boston_input_fn, max_steps=15) self.assertEqual(15, est.get_variable_value('global_step')) def testPredict(self): est = estimator.Estimator(model_fn=linear_model_fn) boston = base.load_boston() est.fit(input_fn=boston_input_fn, steps=1) output = list(est.predict(x=boston.data, batch_size=10)) self.assertEqual(len(output), boston.target.shape[0]) def testWithModelFnOps(self): """Test for model_fn that returns `ModelFnOps`.""" est = estimator.Estimator(model_fn=linear_model_fn_with_model_fn_ops) boston = base.load_boston() est.fit(input_fn=boston_input_fn, steps=1) input_fn = functools.partial(boston_input_fn, num_epochs=1) scores = est.evaluate(input_fn=input_fn, steps=1) self.assertIn('loss', scores.keys()) output = list(est.predict(input_fn=input_fn)) self.assertEqual(len(output), boston.target.shape[0]) def testWrongInput(self): def other_input_fn(): return { 'other': constant_op.constant([0, 0, 0]) }, constant_op.constant([0, 0, 0]) est = estimator.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, steps=1) with self.assertRaises(ValueError): est.fit(input_fn=other_input_fn, steps=1) def testMonitorsForFit(self): est = estimator.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, steps=21, monitors=[CheckCallsMonitor(expect_calls=21)]) def testHooksForEvaluate(self): class CheckCallHook(session_run_hook.SessionRunHook): def __init__(self): self.run_count = 0 def after_run(self, run_context, run_values): self.run_count += 1 est = learn.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, steps=1) hook = CheckCallHook() est.evaluate(input_fn=boston_eval_fn, steps=3, hooks=[hook]) self.assertEqual(3, hook.run_count) def testSummaryWriting(self): est = estimator.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, steps=200) est.evaluate(input_fn=boston_input_fn, steps=200) loss_summary = util_test.simple_values_from_events( util_test.latest_events(est.model_dir), ['OptimizeLoss/loss']) self.assertEqual(1, len(loss_summary)) def testSummaryWritingWithSummaryProto(self): def _streaming_mean_squared_error_histogram(predictions, labels, weights=None, metrics_collections=None, updates_collections=None, name=None): metrics, update_ops = metric_ops.streaming_mean_squared_error( predictions, labels, weights=weights, metrics_collections=metrics_collections, updates_collections=updates_collections, name=name) return summary.histogram('histogram', metrics), update_ops est = estimator.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, steps=200) est.evaluate( input_fn=boston_input_fn, steps=200, metrics={'MSE': _streaming_mean_squared_error_histogram}) events = util_test.latest_events(est.model_dir + '/eval') output_values = {} for e in events: if e.HasField('summary'): for v in e.summary.value: output_values[v.tag] = v self.assertTrue('MSE' in output_values) self.assertTrue(output_values['MSE'].HasField('histo')) def testLossInGraphCollection(self): class _LossCheckerHook(session_run_hook.SessionRunHook): def begin(self): self.loss_collection = ops.get_collection(ops.GraphKeys.LOSSES) hook = _LossCheckerHook() est = estimator.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, steps=200, monitors=[hook]) self.assertTrue(hook.loss_collection) def test_export_returns_exported_dirname(self): expected = '/path/to/some_dir' with test.mock.patch.object(estimator, 'export') as mock_export_module: mock_export_module._export_estimator.return_value = expected est = estimator.Estimator(model_fn=linear_model_fn) actual = est.export('/path/to') self.assertEquals(expected, actual) def test_export_savedmodel(self): tmpdir = tempfile.mkdtemp() est, serving_input_fn = _build_estimator_for_export_tests(tmpdir) extra_file_name = os.path.join( compat.as_bytes(tmpdir), compat.as_bytes('my_extra_file')) extra_file = gfile.GFile(extra_file_name, mode='w') extra_file.write(EXTRA_FILE_CONTENT) extra_file.close() assets_extra = {'some/sub/directory/my_extra_file': extra_file_name} export_dir_base = os.path.join( compat.as_bytes(tmpdir), compat.as_bytes('export')) export_dir = est.export_savedmodel( export_dir_base, serving_input_fn, assets_extra=assets_extra) self.assertTrue(gfile.Exists(export_dir_base)) self.assertTrue(gfile.Exists(export_dir)) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes( 'saved_model.pb')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('variables')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('variables/variables.index')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('variables/variables.data-00000-of-00001')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('assets')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('assets/my_vocab_file')))) self.assertEqual( compat.as_bytes(VOCAB_FILE_CONTENT), compat.as_bytes( gfile.GFile( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('assets/my_vocab_file'))).read())) expected_extra_path = os.path.join( compat.as_bytes(export_dir), compat.as_bytes('assets.extra/some/sub/directory/my_extra_file')) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('assets.extra')))) self.assertTrue(gfile.Exists(expected_extra_path)) self.assertEqual( compat.as_bytes(EXTRA_FILE_CONTENT), compat.as_bytes(gfile.GFile(expected_extra_path).read())) expected_vocab_file = os.path.join( compat.as_bytes(tmpdir), compat.as_bytes('my_vocab_file')) # Restore, to validate that the export was well-formed. with ops.Graph().as_default() as graph: with session_lib.Session(graph=graph) as sess: loader.load(sess, [tag_constants.SERVING], export_dir) assets = [ x.eval() for x in graph.get_collection(ops.GraphKeys.ASSET_FILEPATHS) ] self.assertItemsEqual([expected_vocab_file], assets) graph_ops = [x.name for x in graph.get_operations()] self.assertTrue('input_example_tensor' in graph_ops) self.assertTrue('ParseExample/ParseExample' in graph_ops) self.assertTrue('linear/linear/feature/matmul' in graph_ops) self.assertItemsEqual( ['bogus_lookup', 'feature'], [compat.as_str_any(x) for x in graph.get_collection( constants.COLLECTION_DEF_KEY_FOR_INPUT_FEATURE_KEYS)]) # cleanup gfile.DeleteRecursively(tmpdir) def test_export_savedmodel_with_resource(self): tmpdir = tempfile.mkdtemp() est, serving_input_fn = _build_estimator_for_resource_export_test() export_dir_base = os.path.join( compat.as_bytes(tmpdir), compat.as_bytes('export')) export_dir = est.export_savedmodel(export_dir_base, serving_input_fn) self.assertTrue(gfile.Exists(export_dir_base)) self.assertTrue(gfile.Exists(export_dir)) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes( 'saved_model.pb')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('variables')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('variables/variables.index')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('variables/variables.data-00000-of-00001')))) # Restore, to validate that the export was well-formed. with ops.Graph().as_default() as graph: with session_lib.Session(graph=graph) as sess: loader.load(sess, [tag_constants.SERVING], export_dir) graph_ops = [x.name for x in graph.get_operations()] self.assertTrue('input_example_tensor' in graph_ops) self.assertTrue('ParseExample/ParseExample' in graph_ops) self.assertTrue('LookupTableModel' in graph_ops) self.assertFalse('LookupTableTrainingState' in graph_ops) # cleanup gfile.DeleteRecursively(tmpdir) def test_export_savedmodel_with_graph_transforms(self): tmpdir = tempfile.mkdtemp() est, serving_input_fn = _build_estimator_for_export_tests(tmpdir) extra_file_name = os.path.join( compat.as_bytes(tmpdir), compat.as_bytes('my_extra_file')) extra_file = gfile.GFile(extra_file_name, mode='w') extra_file.write(EXTRA_FILE_CONTENT) extra_file.close() assets_extra = {'some/sub/directory/my_extra_file': extra_file_name} export_dir_base = os.path.join( compat.as_bytes(tmpdir), compat.as_bytes('export')) export_dir = est.export_savedmodel( export_dir_base, serving_input_fn, assets_extra=assets_extra, graph_rewrite_specs=[ estimator.GraphRewriteSpec(['tag_1'], []), estimator.GraphRewriteSpec(['tag_2', 'tag_3'], ['strip_unused_nodes'])]) self.assertTrue(gfile.Exists(export_dir_base)) self.assertTrue(gfile.Exists(export_dir)) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes( 'saved_model.pb')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('variables')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('variables/variables.index')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('variables/variables.data-00000-of-00001')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('assets')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('assets/my_vocab_file')))) self.assertEqual( compat.as_bytes(VOCAB_FILE_CONTENT), compat.as_bytes( gfile.GFile( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('assets/my_vocab_file'))).read())) expected_extra_path = os.path.join( compat.as_bytes(export_dir), compat.as_bytes('assets.extra/some/sub/directory/my_extra_file')) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('assets.extra')))) self.assertTrue(gfile.Exists(expected_extra_path)) self.assertEqual( compat.as_bytes(EXTRA_FILE_CONTENT), compat.as_bytes(gfile.GFile(expected_extra_path).read())) expected_vocab_file = os.path.join( compat.as_bytes(tmpdir), compat.as_bytes('my_vocab_file')) # Restore, to validate that the export was well-formed. # tag_1 is untransformed. tags = ['tag_1'] with ops.Graph().as_default() as graph: with session_lib.Session(graph=graph) as sess: loader.load(sess, tags, export_dir) assets = [ x.eval() for x in graph.get_collection(ops.GraphKeys.ASSET_FILEPATHS) ] self.assertItemsEqual([expected_vocab_file], assets) graph_ops = [x.name for x in graph.get_operations()] self.assertTrue('input_example_tensor' in graph_ops) self.assertTrue('ParseExample/ParseExample' in graph_ops) self.assertTrue('linear/linear/feature/matmul' in graph_ops) # Since there were no transforms, both save ops are still present. self.assertTrue('save/SaveV2/tensor_names' in graph_ops) self.assertTrue('save_1/SaveV2/tensor_names' in graph_ops) # Since there were no transforms, the hash table lookup is still there. self.assertTrue('hash_table_Lookup' in graph_ops) # Restore, to validate that the export was well-formed. # tag_2, tag_3 was subjected to strip_unused_nodes. tags = ['tag_2', 'tag_3'] with ops.Graph().as_default() as graph: with session_lib.Session(graph=graph) as sess: loader.load(sess, tags, export_dir) assets = [ x.eval() for x in graph.get_collection(ops.GraphKeys.ASSET_FILEPATHS) ] self.assertItemsEqual([expected_vocab_file], assets) graph_ops = [x.name for x in graph.get_operations()] self.assertTrue('input_example_tensor' in graph_ops) self.assertTrue('ParseExample/ParseExample' in graph_ops) self.assertTrue('linear/linear/feature/matmul' in graph_ops) # The Saver used to restore the checkpoint into the export Session # was not added to the SAVERS collection, so strip_unused_nodes removes # it. The one explicitly created in export_savedmodel is tracked in # the MetaGraphDef saver_def field, so that one is retained. # TODO(soergel): Make Savers sane again. I understand this is all a bit # nuts but for now the test demonstrates what actually happens. self.assertFalse('save/SaveV2/tensor_names' in graph_ops) self.assertTrue('save_1/SaveV2/tensor_names' in graph_ops) # The fake hash table lookup wasn't connected to anything; stripped. self.assertFalse('hash_table_Lookup' in graph_ops) # cleanup gfile.DeleteRecursively(tmpdir) class InferRealValuedColumnsTest(test.TestCase): def testInvalidArgs(self): with self.assertRaisesRegexp(ValueError, 'x or input_fn must be provided'): estimator.infer_real_valued_columns_from_input(None) with self.assertRaisesRegexp(ValueError, 'cannot be tensors'): estimator.infer_real_valued_columns_from_input(constant_op.constant(1.0)) def _assert_single_feature_column(self, expected_shape, expected_dtype, feature_columns): self.assertEqual(1, len(feature_columns)) feature_column = feature_columns[0] self.assertEqual('', feature_column.name) self.assertEqual( { '': parsing_ops.FixedLenFeature( shape=expected_shape, dtype=expected_dtype) }, feature_column.config) def testInt32Input(self): feature_columns = estimator.infer_real_valued_columns_from_input( np.ones( shape=[7, 8], dtype=np.int32)) self._assert_single_feature_column([8], dtypes.int32, feature_columns) def testInt32InputFn(self): feature_columns = estimator.infer_real_valued_columns_from_input_fn( lambda: (array_ops.ones(shape=[7, 8], dtype=dtypes.int32), None)) self._assert_single_feature_column([8], dtypes.int32, feature_columns) def testInt64Input(self): feature_columns = estimator.infer_real_valued_columns_from_input( np.ones( shape=[7, 8], dtype=np.int64)) self._assert_single_feature_column([8], dtypes.int64, feature_columns) def testInt64InputFn(self): feature_columns = estimator.infer_real_valued_columns_from_input_fn( lambda: (array_ops.ones(shape=[7, 8], dtype=dtypes.int64), None)) self._assert_single_feature_column([8], dtypes.int64, feature_columns) def testFloat32Input(self): feature_columns = estimator.infer_real_valued_columns_from_input( np.ones( shape=[7, 8], dtype=np.float32)) self._assert_single_feature_column([8], dtypes.float32, feature_columns) def testFloat32InputFn(self): feature_columns = estimator.infer_real_valued_columns_from_input_fn( lambda: (array_ops.ones(shape=[7, 8], dtype=dtypes.float32), None)) self._assert_single_feature_column([8], dtypes.float32, feature_columns) def testFloat64Input(self): feature_columns = estimator.infer_real_valued_columns_from_input( np.ones( shape=[7, 8], dtype=np.float64)) self._assert_single_feature_column([8], dtypes.float64, feature_columns) def testFloat64InputFn(self): feature_columns = estimator.infer_real_valued_columns_from_input_fn( lambda: (array_ops.ones(shape=[7, 8], dtype=dtypes.float64), None)) self._assert_single_feature_column([8], dtypes.float64, feature_columns) def testBoolInput(self): with self.assertRaisesRegexp( ValueError, 'on integer or non floating types are not supported'): estimator.infer_real_valued_columns_from_input( np.array([[False for _ in xrange(8)] for _ in xrange(7)])) def testBoolInputFn(self): with self.assertRaisesRegexp( ValueError, 'on integer or non floating types are not supported'): # pylint: disable=g-long-lambda estimator.infer_real_valued_columns_from_input_fn( lambda: (constant_op.constant(False, shape=[7, 8], dtype=dtypes.bool), None)) def testStringInput(self): with self.assertRaisesRegexp( ValueError, 'on integer or non floating types are not supported'): # pylint: disable=g-long-lambda estimator.infer_real_valued_columns_from_input( np.array([['%d.0' % i for i in xrange(8)] for _ in xrange(7)])) def testStringInputFn(self): with self.assertRaisesRegexp( ValueError, 'on integer or non floating types are not supported'): # pylint: disable=g-long-lambda estimator.infer_real_valued_columns_from_input_fn( lambda: ( constant_op.constant([['%d.0' % i for i in xrange(8)] for _ in xrange(7)]), None)) def testBostonInputFn(self): feature_columns = estimator.infer_real_valued_columns_from_input_fn( boston_input_fn) self._assert_single_feature_column([_BOSTON_INPUT_DIM], dtypes.float64, feature_columns) def testIrisInputFn(self): feature_columns = estimator.infer_real_valued_columns_from_input_fn( iris_input_fn) self._assert_single_feature_column([_IRIS_INPUT_DIM], dtypes.float64, feature_columns) class ReplicaDeviceSetterTest(test.TestCase): def testVariablesAreOnPs(self): tf_config = {'cluster': {run_config.TaskType.PS: ['fake_ps_0']}} with test.mock.patch.dict('os.environ', {'TF_CONFIG': json.dumps(tf_config)}): config = run_config.RunConfig() with ops.device(estimator._get_replica_device_setter(config)): v = variables_lib.Variable([1, 2]) w = variables_lib.Variable([2, 1]) a = v + w self.assertDeviceEqual('/job:ps/task:0', v.device) self.assertDeviceEqual('/job:ps/task:0', v.initializer.device) self.assertDeviceEqual('/job:ps/task:0', w.device) self.assertDeviceEqual('/job:ps/task:0', w.initializer.device) self.assertDeviceEqual('/job:worker', a.device) def testVariablesAreLocal(self): with ops.device( estimator._get_replica_device_setter(run_config.RunConfig())): v = variables_lib.Variable([1, 2]) w = variables_lib.Variable([2, 1]) a = v + w self.assertDeviceEqual('', v.device) self.assertDeviceEqual('', v.initializer.device) self.assertDeviceEqual('', w.device) self.assertDeviceEqual('', w.initializer.device) self.assertDeviceEqual('', a.device) def testMutableHashTableIsOnPs(self): tf_config = {'cluster': {run_config.TaskType.PS: ['fake_ps_0']}} with test.mock.patch.dict('os.environ', {'TF_CONFIG': json.dumps(tf_config)}): config = run_config.RunConfig() with ops.device(estimator._get_replica_device_setter(config)): default_val = constant_op.constant([-1, -1], dtypes.int64) table = lookup.MutableHashTable(dtypes.string, dtypes.int64, default_val) input_string = constant_op.constant(['brain', 'salad', 'tank']) output = table.lookup(input_string) self.assertDeviceEqual('/job:ps/task:0', table._table_ref.device) self.assertDeviceEqual('/job:ps/task:0', output.device) def testMutableHashTableIsLocal(self): with ops.device( estimator._get_replica_device_setter(run_config.RunConfig())): default_val = constant_op.constant([-1, -1], dtypes.int64) table = lookup.MutableHashTable(dtypes.string, dtypes.int64, default_val) input_string = constant_op.constant(['brain', 'salad', 'tank']) output = table.lookup(input_string) self.assertDeviceEqual('', table._table_ref.device) self.assertDeviceEqual('', output.device) def testTaskIsSetOnWorkerWhenJobNameIsSet(self): tf_config = { 'cluster': { run_config.TaskType.PS: ['fake_ps_0'] }, 'task': { 'type': run_config.TaskType.WORKER, 'index': 3 } } with test.mock.patch.dict('os.environ', {'TF_CONFIG': json.dumps(tf_config)}): config = run_config.RunConfig() with ops.device(estimator._get_replica_device_setter(config)): v = variables_lib.Variable([1, 2]) w = variables_lib.Variable([2, 1]) a = v + w self.assertDeviceEqual('/job:ps/task:0', v.device) self.assertDeviceEqual('/job:ps/task:0', v.initializer.device) self.assertDeviceEqual('/job:ps/task:0', w.device) self.assertDeviceEqual('/job:ps/task:0', w.initializer.device) self.assertDeviceEqual('/job:worker/task:3', a.device) if __name__ == '__main__': test.main()
apache-2.0
kgullikson88/TS23-Scripts
PlotFits.py
1
2665
import sys import itertools import matplotlib.pyplot as plt import numpy as np import FitsUtils if __name__ == "__main__": fileList = [] tellurics = False normalize = False byorder = False # Plots one order at a time pixelscale = False oneplot = False for arg in sys.argv[1:]: if "tellcorr" in arg: tellurics = True elif "-norm" in arg: normalize = True elif "-order" in arg: byorder = True elif "-pix" in arg: pixelscale = True # byorder = True elif "-one" in arg: oneplot = True else: fileList.append(arg) # linestyles = ['k-', 'r-', 'b-', 'g-'] linestyles = itertools.cycle(('-', '--', ':', '-.')) colors = itertools.cycle(('r', 'g', 'b', 'c', 'm', 'y', 'k')) for fnum, fname in enumerate(fileList): #ls = linestyles[fnum % len(linestyles)] col = colors.next() if fnum % 7 == 0: style = linestyles.next() ls = '{}{}'.format(col, style) orders = FitsUtils.MakeXYpoints(fname, extensions=True, x="wavelength", y="flux", cont="continuum", errors="error") print fname, len(orders) if not oneplot: plt.figure(fnum) plt.title(fname) if tellurics: model = FitsUtils.MakeXYpoints(fname, extensions=True, x="wavelength", y="model") for i, order in enumerate(orders): # order.cont = FindContinuum.Continuum(order.x, order.y, lowreject=3, highreject=3) if pixelscale: order.x = np.arange(order.size()) if tellurics: plt.plot(order.x, order.y / order.cont, 'k-') plt.plot(order.x, model[i].y, 'r-') else: if normalize: plt.plot(order.x, order.y / order.cont, ls, label=fname) plt.text(order.x.mean(), 1.1, str(i + 1)) else: if i == 0: plt.plot(order.x, order.y, ls, label=fname) else: plt.plot(order.x, order.y, ls) #plt.plot(order.x, order.cont) plt.xlabel("Wavelength (nm)") plt.ylabel("Flux") plt.gca().get_xaxis().get_major_formatter().set_useOffset(False) if byorder: plt.title("Order %i" % i) plt.show() if not byorder: if 'oneplot': leg = plt.legend(loc='best', fancybox=True) leg.get_frame().set_alpha(0.4) plt.show()
gpl-3.0
f3r/scikit-learn
examples/cluster/plot_kmeans_digits.py
230
4524
""" =========================================================== A demo of K-Means clustering on the handwritten digits data =========================================================== In this example we compare the various initialization strategies for K-means in terms of runtime and quality of the results. As the ground truth is known here, we also apply different cluster quality metrics to judge the goodness of fit of the cluster labels to the ground truth. Cluster quality metrics evaluated (see :ref:`clustering_evaluation` for definitions and discussions of the metrics): =========== ======================================================== Shorthand full name =========== ======================================================== homo homogeneity score compl completeness score v-meas V measure ARI adjusted Rand index AMI adjusted mutual information silhouette silhouette coefficient =========== ======================================================== """ print(__doc__) from time import time import numpy as np import matplotlib.pyplot as plt from sklearn import metrics from sklearn.cluster import KMeans from sklearn.datasets import load_digits from sklearn.decomposition import PCA from sklearn.preprocessing import scale np.random.seed(42) digits = load_digits() data = scale(digits.data) n_samples, n_features = data.shape n_digits = len(np.unique(digits.target)) labels = digits.target sample_size = 300 print("n_digits: %d, \t n_samples %d, \t n_features %d" % (n_digits, n_samples, n_features)) print(79 * '_') print('% 9s' % 'init' ' time inertia homo compl v-meas ARI AMI silhouette') def bench_k_means(estimator, name, data): t0 = time() estimator.fit(data) print('% 9s %.2fs %i %.3f %.3f %.3f %.3f %.3f %.3f' % (name, (time() - t0), estimator.inertia_, metrics.homogeneity_score(labels, estimator.labels_), metrics.completeness_score(labels, estimator.labels_), metrics.v_measure_score(labels, estimator.labels_), metrics.adjusted_rand_score(labels, estimator.labels_), metrics.adjusted_mutual_info_score(labels, estimator.labels_), metrics.silhouette_score(data, estimator.labels_, metric='euclidean', sample_size=sample_size))) bench_k_means(KMeans(init='k-means++', n_clusters=n_digits, n_init=10), name="k-means++", data=data) bench_k_means(KMeans(init='random', n_clusters=n_digits, n_init=10), name="random", data=data) # in this case the seeding of the centers is deterministic, hence we run the # kmeans algorithm only once with n_init=1 pca = PCA(n_components=n_digits).fit(data) bench_k_means(KMeans(init=pca.components_, n_clusters=n_digits, n_init=1), name="PCA-based", data=data) print(79 * '_') ############################################################################### # Visualize the results on PCA-reduced data reduced_data = PCA(n_components=2).fit_transform(data) kmeans = KMeans(init='k-means++', n_clusters=n_digits, n_init=10) kmeans.fit(reduced_data) # Step size of the mesh. Decrease to increase the quality of the VQ. h = .02 # point in the mesh [x_min, m_max]x[y_min, y_max]. # Plot the decision boundary. For that, we will assign a color to each x_min, x_max = reduced_data[:, 0].min() - 1, reduced_data[:, 0].max() + 1 y_min, y_max = reduced_data[:, 1].min() - 1, reduced_data[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) # Obtain labels for each point in mesh. Use last trained model. Z = kmeans.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) plt.figure(1) plt.clf() plt.imshow(Z, interpolation='nearest', extent=(xx.min(), xx.max(), yy.min(), yy.max()), cmap=plt.cm.Paired, aspect='auto', origin='lower') plt.plot(reduced_data[:, 0], reduced_data[:, 1], 'k.', markersize=2) # Plot the centroids as a white X centroids = kmeans.cluster_centers_ plt.scatter(centroids[:, 0], centroids[:, 1], marker='x', s=169, linewidths=3, color='w', zorder=10) plt.title('K-means clustering on the digits dataset (PCA-reduced data)\n' 'Centroids are marked with white cross') plt.xlim(x_min, x_max) plt.ylim(y_min, y_max) plt.xticks(()) plt.yticks(()) plt.show()
bsd-3-clause
crichardson17/starburst_atlas
Low_resolution_sims/DustFree_LowRes/Geneva_Rot_inst/Geneva_Rot_inst_age6/Rest.py
33
7215
import csv import matplotlib.pyplot as plt from numpy import * import scipy.interpolate import math from pylab import * from matplotlib.ticker import MultipleLocator, FormatStrFormatter import matplotlib.patches as patches from matplotlib.path import Path import os # ------------------------------------------------------------------------------------------------------ #inputs for file in os.listdir('.'): if file.endswith(".grd"): inputfile = file for file in os.listdir('.'): if file.endswith(".txt"): inputfile2 = file # ------------------------------------------------------------------------------------------------------ #Patches data #for the Kewley and Levesque data verts = [ (1., 7.97712125471966000000), # left, bottom (1., 9.57712125471966000000), # left, top (2., 10.57712125471970000000), # right, top (2., 8.97712125471966000000), # right, bottom (0., 0.), # ignored ] codes = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY, ] path = Path(verts, codes) # ------------------------ #for the Kewley 01 data verts2 = [ (2.4, 9.243038049), # left, bottom (2.4, 11.0211893), # left, top (2.6, 11.0211893), # right, top (2.6, 9.243038049), # right, bottom (0, 0.), # ignored ] path = Path(verts, codes) path2 = Path(verts2, codes) # ------------------------- #for the Moy et al data verts3 = [ (1., 6.86712125471966000000), # left, bottom (1., 10.18712125471970000000), # left, top (3., 12.18712125471970000000), # right, top (3., 8.86712125471966000000), # right, bottom (0., 0.), # ignored ] path = Path(verts, codes) path3 = Path(verts3, codes) # ------------------------------------------------------------------------------------------------------ #the routine to add patches for others peoples' data onto our plots. def add_patches(ax): patch3 = patches.PathPatch(path3, facecolor='yellow', lw=0) patch2 = patches.PathPatch(path2, facecolor='green', lw=0) patch = patches.PathPatch(path, facecolor='red', lw=0) ax1.add_patch(patch3) ax1.add_patch(patch2) ax1.add_patch(patch) # ------------------------------------------------------------------------------------------------------ #the subplot routine def add_sub_plot(sub_num): numplots = 16 plt.subplot(numplots/4.,4,sub_num) rbf = scipy.interpolate.Rbf(x, y, z[:,sub_num-1], function='linear') zi = rbf(xi, yi) contour = plt.contour(xi,yi,zi, levels, colors='c', linestyles = 'dashed') contour2 = plt.contour(xi,yi,zi, levels2, colors='k', linewidths=1.5) plt.scatter(max_values[line[sub_num-1],2], max_values[line[sub_num-1],3], c ='k',marker = '*') plt.annotate(headers[line[sub_num-1]], xy=(8,11), xytext=(6,8.5), fontsize = 10) plt.annotate(max_values[line[sub_num-1],0], xy= (max_values[line[sub_num-1],2], max_values[line[sub_num-1],3]), xytext = (0, -10), textcoords = 'offset points', ha = 'right', va = 'bottom', fontsize=10) if sub_num == numplots / 2.: print "half the plots are complete" #axis limits yt_min = 8 yt_max = 23 xt_min = 0 xt_max = 12 plt.ylim(yt_min,yt_max) plt.xlim(xt_min,xt_max) plt.yticks(arange(yt_min+1,yt_max,1),fontsize=10) plt.xticks(arange(xt_min+1,xt_max,1), fontsize = 10) if sub_num in [2,3,4,6,7,8,10,11,12,14,15,16]: plt.tick_params(labelleft = 'off') else: plt.tick_params(labelleft = 'on') plt.ylabel('Log ($ \phi _{\mathrm{H}} $)') if sub_num in [1,2,3,4,5,6,7,8,9,10,11,12]: plt.tick_params(labelbottom = 'off') else: plt.tick_params(labelbottom = 'on') plt.xlabel('Log($n _{\mathrm{H}} $)') if sub_num == 1: plt.yticks(arange(yt_min+1,yt_max+1,1),fontsize=10) if sub_num == 13: plt.yticks(arange(yt_min,yt_max,1),fontsize=10) plt.xticks(arange(xt_min,xt_max,1), fontsize = 10) if sub_num == 16 : plt.xticks(arange(xt_min+1,xt_max+1,1), fontsize = 10) # --------------------------------------------------- #this is where the grid information (phi and hdens) is read in and saved to grid. grid = []; with open(inputfile, 'rb') as f: csvReader = csv.reader(f,delimiter='\t') for row in csvReader: grid.append(row); grid = asarray(grid) #here is where the data for each line is read in and saved to dataEmissionlines dataEmissionlines = []; with open(inputfile2, 'rb') as f: csvReader = csv.reader(f,delimiter='\t') headers = csvReader.next() for row in csvReader: dataEmissionlines.append(row); dataEmissionlines = asarray(dataEmissionlines) print "import files complete" # --------------------------------------------------- #for grid phi_values = grid[1:len(dataEmissionlines)+1,6] hdens_values = grid[1:len(dataEmissionlines)+1,7] #for lines headers = headers[1:] Emissionlines = dataEmissionlines[:, 1:] concatenated_data = zeros((len(Emissionlines),len(Emissionlines[0]))) max_values = zeros((len(Emissionlines[0]),4)) #select the scaling factor #for 1215 #incident = Emissionlines[1:,4] #for 4860 incident = Emissionlines[:,57] #take the ratio of incident and all the lines and put it all in an array concatenated_data for i in range(len(Emissionlines)): for j in range(len(Emissionlines[0])): if math.log(4860.*(float(Emissionlines[i,j])/float(Emissionlines[i,57])), 10) > 0: concatenated_data[i,j] = math.log(4860.*(float(Emissionlines[i,j])/float(Emissionlines[i,57])), 10) else: concatenated_data[i,j] == 0 # for 1215 #for i in range(len(Emissionlines)): # for j in range(len(Emissionlines[0])): # if math.log(1215.*(float(Emissionlines[i,j])/float(Emissionlines[i,4])), 10) > 0: # concatenated_data[i,j] = math.log(1215.*(float(Emissionlines[i,j])/float(Emissionlines[i,4])), 10) # else: # concatenated_data[i,j] == 0 #find the maxima to plot onto the contour plots for j in range(len(concatenated_data[0])): max_values[j,0] = max(concatenated_data[:,j]) max_values[j,1] = argmax(concatenated_data[:,j], axis = 0) max_values[j,2] = hdens_values[max_values[j,1]] max_values[j,3] = phi_values[max_values[j,1]] #to round off the maxima max_values[:,0] = [ '%.1f' % elem for elem in max_values[:,0] ] print "data arranged" # --------------------------------------------------- #Creating the grid to interpolate with for contours. gridarray = zeros((len(Emissionlines),2)) gridarray[:,0] = hdens_values gridarray[:,1] = phi_values x = gridarray[:,0] y = gridarray[:,1] #change desired lines here! line = [3,4,15,22,37,53,54,55,57,62,77,88,89,90,92,93] #create z array for this plot z = concatenated_data[:,line[:]] # --------------------------------------------------- # Interpolate print "starting interpolation" xi, yi = linspace(x.min(), x.max(), 10), linspace(y.min(), y.max(), 10) xi, yi = meshgrid(xi, yi) # --------------------------------------------------- print "interpolatation complete; now plotting" #plot plt.subplots_adjust(wspace=0, hspace=0) #remove space between plots levels = arange(10**-1,10, .2) levels2 = arange(10**-2,10**2, 1) plt.suptitle("Rest of the Lines", fontsize=14) # --------------------------------------------------- for i in range(16): add_sub_plot(i) ax1 = plt.subplot(4,4,1) add_patches(ax1) print "complete" plt.savefig('Rest.pdf') plt.clf()
gpl-2.0
317070/kaggle-heart
util_scripts/sunny2npy.py
1
5708
import re import os import fnmatch import shutil import dicom import cv2 #opencv2 import numpy as np import cPickle as pickle np.random.seed(317070) import matplotlib.pyplot as plt SAX_SERIES = { # challenge training "SC-HF-I-1": "0004", "SC-HF-I-2": "0106", "SC-HF-I-4": "0116", "SC-HF-I-5": "0156", "SC-HF-I-6": "0180", "SC-HF-I-7": "0209", "SC-HF-I-8": "0226", "SC-HF-I-9": "0241", "SC-HF-I-10": "0024", "SC-HF-I-11": "0043", "SC-HF-I-12": "0062", "SC-HF-I-40": "0134", "SC-HF-NI-3": "0379", "SC-HF-NI-4": "0501", "SC-HF-NI-7": "0523", "SC-HF-NI-11": "0270", "SC-HF-NI-12": "0286", "SC-HF-NI-13": "0304", "SC-HF-NI-14": "0331", "SC-HF-NI-15": "0359", "SC-HF-NI-31": "0401", "SC-HF-NI-33": "0424", "SC-HF-NI-34": "0446", "SC-HF-NI-36": "0474", "SC-HYP-1": "0550", "SC-HYP-3": "0650", "SC-HYP-6": "0767", "SC-HYP-7": "0007", "SC-HYP-8": "0796", "SC-HYP-9": "0003", "SC-HYP-10": "0579", "SC-HYP-11": "0601", "SC-HYP-12": "0629", "SC-HYP-37": "0702", "SC-HYP-38": "0734", "SC-HYP-40": "0755", "SC-N-2": "0898", "SC-N-3": "0915", "SC-N-5": "0963", "SC-N-6": "0984", "SC-N-7": "1009", "SC-N-9": "1031", "SC-N-10": "0851", "SC-N-11": "0878", "SC-N-40": "0944", } SUNNYBROOK_ROOT_PATH = os.path.expanduser("/mnt/storage/data/dsb15/lv-challenge") TRAIN_CONTOUR_PATH = os.path.join(SUNNYBROOK_ROOT_PATH, "Sunnybrook Cardiac MR Database ContoursPart3", "TrainingDataContours") VALIDATION_CONTOUR_PATH = os.path.join(SUNNYBROOK_ROOT_PATH, "Sunnybrook Cardiac MR Database ContoursPart2", "ValidationDataContours") ONLINE_CONTOUR_PATH = os.path.join(SUNNYBROOK_ROOT_PATH, "Sunnybrook Cardiac MR Database ContoursPart1", "OnlineDataContours") print TRAIN_CONTOUR_PATH TRAIN_IMG_PATH = os.path.join(SUNNYBROOK_ROOT_PATH, "challenge_training") VALIDATION_IMG_PATH = os.path.join(SUNNYBROOK_ROOT_PATH, "challenge_validation") ONLINE_IMG_PATH = os.path.join(SUNNYBROOK_ROOT_PATH, "challenge_online") def shrink_case(case): toks = case.split("-") def shrink_if_number(x): try: cvt = int(x) return str(cvt) except ValueError: return x return "-".join([shrink_if_number(t) for t in toks]) class Contour(object): def __init__(self, ctr_path): self.ctr_path = ctr_path match = re.search(r"/([^/]*)/contours-manual/IRCCI-expert/IM-0001-(\d{4})-icontour-manual.txt", ctr_path) self.case = shrink_case(match.group(1)) self.img_no = int(match.group(2)) def __str__(self): return "<Contour for case %s, image %d>" % (self.case, self.img_no) __repr__ = __str__ def load_contour(contour, img_path): filename = "IM-%s-%04d.dcm" % (SAX_SERIES[contour.case], contour.img_no) full_path = os.path.join(img_path, contour.case, filename) f = dicom.read_file(full_path) img = f.pixel_array.astype(np.int) ctrs = np.loadtxt(contour.ctr_path, delimiter=" ").astype(np.int32) label = np.zeros_like(img, dtype="uint8") cv2.fillPoly(label, [ctrs], 1) return img, label def get_all_contours(contour_path): contours = [os.path.join(dirpath, f) for dirpath, dirnames, files in os.walk(contour_path) for f in fnmatch.filter(files, 'IM-0001-*-icontour-manual.txt') ] print("Shuffle data") np.random.shuffle(contours) print("Number of examples: {:d}".format(len(contours))) extracted = map(Contour, contours) return extracted images = [] labels = [] def export_all_contours(contours, img_path): counter_img = 0 counter_label = 0 batchsz = 100 print("Processing {:d} images and labels...".format(len(contours))) for i, ctr in enumerate(contours): img, label = load_contour(ctr, img_path) images.append(img) labels.append(label) #print ctr #if "SC-HYP-12" in ctr.__str__(): #pass """ if i>-1: plt.figure() mngr = plt.get_current_fig_manager() # to put it into the upper left corner for example: mngr.window.setGeometry(50, 100, 640, 545) plt.suptitle(ctr.__str__() + " #%d" % i) plt.imshow(img * (1-label) + (np.max(img)-img)*(label) ) #plt.imshow(label) plt.show() """ if __name__== "__main__": print("Mapping ground truth contours to images...") ctrs = get_all_contours(TRAIN_CONTOUR_PATH) print("Done mapping ground truth contours to images") print("\nBuilding LMDB for train...") export_all_contours(ctrs, TRAIN_IMG_PATH) print("Mapping ground truth contours to images...") ctrs = get_all_contours(VALIDATION_CONTOUR_PATH) print("Done mapping ground truth contours to images") print("\nBuilding LMDB for train...") export_all_contours(ctrs, VALIDATION_IMG_PATH) print("Mapping ground truth contours to images...") ctrs = get_all_contours(ONLINE_CONTOUR_PATH) print("Done mapping ground truth contours to images") print("\nBuilding LMDB for train...") export_all_contours(ctrs, ONLINE_IMG_PATH) pickle.dump({'images': images, 'labels': labels}, open("/mnt/storage/data/dsb15/pkl_annotated/data.pkl", "wb"), protocol=pickle.HIGHEST_PROTOCOL)
mit
ph4r05/NATSimTools
nfproc.py
1
6424
import os import sys import fileinput import re import random import math from operator import itemgetter, attrgetter import subprocess from optparse import OptionParser import copy import time import argparse from dateutil import parser as dparser import calendar import pylab as P import numpy as np from scipy.stats import binom from scipy.stats import nbinom from scipy.stats import norm from scipy.stats import poisson from scipy.stats import chisquare # Multiple plots from mpl_toolkits.axes_grid1 import host_subplot import mpl_toolkits.axisartist as AA import matplotlib.pyplot as plt # # Data processing here # def graph(plt, x='Sample', y='Port number', loc=1): if loc!=-1: plt.legend(loc=loc) plt.xlabel(x) plt.ylabel(y) #,rotation='horizontal') plt.grid(True) plt.show() plt.close() def nfloat(x): if x=='nan': return 'nan' return float(x) if __name__ == "__main__": parser = argparse.ArgumentParser(description='NAT netflow data processor.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-o','--output', help='Output file name from finder', required=False, default='graph.txt') parser.add_argument('-t','--space', help='Time in ms to wait between packet send', required=False, default=10, type=int) parser.add_argument('-l','--lmbd_start',help='On which lambda to start', required=False, default=-1, type=float) parser.add_argument('-s','--strategy', help='Strategy to use (poisson, i2j, fibo, their, ij, binom, simple)', required=False, default='poisson') parser.add_argument('-r','--rounds', help='Simulation rounds', required=False, type=int, default=1000) parser.add_argument('-e','--errors', help='Maximum steps by algorithm', required=False, type=int, default=1000) parser.add_argument('-d','--dot', help='Graphviz dot illustration', required=False, type=int, default=0) parser.add_argument('-a','--ascii', help='Ascii illustration', required=False, type=int, default=0) parser.add_argument('-n','--nfdump', help='NFdump file', required=False, default=None) parser.add_argument('-m','--nfdump_sorted',help='NFdump sorted file', required=False, default=None) parser.add_argument('-f','--filter', help='NFdump filter', required=False, default=None) parser.add_argument('-g','--hostnet', help='NFdump host address', required=False, default="147.250.") parser.add_argument('--lmbd', help='Default Poisson lambda for simulations', required=False, type=float, default=0.1) parser.add_argument('--pval', help='Graph pvalue', required=False, default=False, action='store_true') parser.add_argument('file', action="store", nargs='+') args = parser.parse_args() keys = [] succ = [] mean = [] styles = ['--bx', '-.g2', ':.r', '--|k', ':m+', '--1c'] #for i, fname in enumerate(args.file): fname=args.file[0] fh = open(fname) dat = fh.readlines() n = 0 last = -1 kk = [] # keys ex = [] # E[X] vx = [] # V[X] ss = [] # ssum pk = [[] for i in range(0,6)] # p-value, key pv = [[] for i in range(0,6)] # p-value ck = [[] for i in range(0,6)] # chi-square, key cv = [[] for i in range(0,6)] # chi-square for d in dat: d = str(d).strip() if d.startswith('#') or d.startswith('New'): continue arr = [nfloat(x) for x in filter(None, d.split('|'))] if len(arr)==0: continue # Process the file, E[X], V[X], SUM if arr[0] > n: n=int(arr[0]) if last != arr[0]: kk.append(arr[0]) ex.append(arr[2]) vx.append(arr[3]) ss.append(arr[4]) idx = int(arr[1]) # Distribution if arr[5] != 'nan': pk[idx].append(arr[0]) ck[idx].append(arr[0]) pv[idx].append(arr[5]) cv[idx].append(arr[6]) # last last = arr[0] # Process output to nicely looking graph x = np.array(range(0, n)) # hypothesis tests results hypo_0 = len(filter(lambda x: x >= 0.05, pv[0])) hypo_4 = len(filter(lambda x: x >= 0.05, pv[4])) print "Statistical data" print "Mean EX %03.4f; Median EX %03.4f; V[Mean] %03.4f; Mean VX %03.4f; Median VX %03.4f;" % (np.mean(ex), np.median(ex), np.var(ex), np.mean(vx), np.median(vx)) print "Hypothesis testing result" print "Poisson: %01.5f; median p-value: %01.8f; median chi-square: %01.8f" % (hypo_0/float(len(pk[0])), np.median(pv[0]), np.median(cv[0])) print "NBinom: %01.5f; median p-value: %01.8f; median chi-square: %01.8f" % (hypo_4/float(len(pk[4])), np.median(pv[4]), np.median(cv[4])) print "%01.3f & %01.3f & %03.4f & %03.4f & %03.4f" % ((1 - hypo_0/float(len(pk[0]))) * 100, (1 - hypo_4/float(len(pk[4]))) * 100, np.mean(ex), np.var(ex), np.mean(vx)) # e,x ex_np = np.array(ex) vx_np = np.array(vx) exvx = np.abs(vx_np / ex_np) plt.plot(x, ex_np, 'b+', label="E[X]") #plt.plot(x, vx_np, 'r3', label="V[X]") graph(plt) # # Histogram for E[X] # P.grid(True) P.Figure() P.hist(ex_np, 20, normed=0, histtype='bar') P.legend() graph(plt, x='$E[X]$', y='Count', loc=-1) # # Histogram for dispersion # #P.grid(True) #P.Figure() #P.hist(exvx, 20, normed=1, histtype='bar') #P.legend() #graph(plt, x='$E[X] / V[X]$', y='Count', loc=-1) # # P-value histogram # # p-value with critical region pk_p = np.array(pk[0]) # poisson, key pk_n = np.array(pk[4]) # nbin, key pv_p = np.array(pv[0]) # poisson, value pv_n = np.array(pv[4]) # nbin, value # critical region plt.axvspan(0.0, 0.05, facecolor='r', alpha=0.6) # Stacked histogram for poisson and negative binomial P.grid(True) P.Figure() P.hist([pv_p, pv_n], 20, normed=0, histtype='bar', color=['green', 'blue'], label=['Po', 'NB']) P.legend() graph(plt, x='p-value', y='Count', loc=-1) # # P-value scatter plot # plt.plot(pk_p, pv_p, 'g+', label="Po") plt.plot(pk_n, pv_n, 'b3', label="NB") plt.axhspan(0.0, 0.05, facecolor='r', alpha=0.5) # p-value reqion graph(plt, y='p-value', loc=-1)
apache-2.0
radhikapc/foundation-homework
homework10/Homework10-Radhika-Reddit.py
1
4414
# coding: utf-8 # In[4]: import requests from bs4 import BeautifulSoup headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} response = requests.get("https://www.reddit.com/", headers=headers) doc = BeautifulSoup(response.text, 'html.parser') # In[5]: import pandas as pd # In[6]: #doc # #### The title of the post # In[7]: def title(my_dict): title = doc.find_all("p", { 'class': 'title'}) for i in title: return (i.text.strip()) title(doc) # #### The number of votes it has (the number between the up and down arrows) # In[8]: def votes(my_dict): voted = doc.find_all("div", { 'class': 'score unvoted'}) for i in voted: #print(i.text) if i.text == "•": return 0 else: return (i.text.strip()) votes(doc) # In[9]: #### The number of comments it has # In[10]: def comments(my_dict): comm = doc.find_all("li", { 'class': 'first'}) for i in comm: if i.text == "comment": return "no comments" else: return (i.text.strip()) comments(doc) # In[11]: #comm = doc.find_all("li", { 'class': 'first'}) #for i in comm: #if i.text == "comment": #print(0) #else: #print(i.text) # #### What subreddit it is from (e.g. /r/AskReddit, /r/todayilearned) # In[12]: #sub = doc.find_all ("p", {'class': 'tagline'}) #for i in sub: #subred = doc.find_all("a", {'class': 'subreddit hover may-blank'}) #for i in subred: #print(i.text) # In[13]: def subreddit(my_dict): sub = doc.find_all ("p", {'class': 'tagline'}) for i in sub: subred = doc.find_all("a", {'class': 'subreddit hover may-blank'}) for i in subred: return (i.text.strip()) subreddit(doc) # #### When it was posted (get a TIMESTAMP, e.g. 2016-06-22T12:33:58+00:00, not "4 hours ago") # In[14]: def timestamp(my_dict): sub = doc.find_all ("p", {'class': 'tagline'}) for i in sub: time_tag = i.find('time')['datetime'] return time_tag timestamp(doc) # In[15]: #sub = doc.find_all ("p", {'class': 'tagline'}) #for i in sub: # time_tag = i.find('time')['datetime'] #print(time_tag) # #### The URL to the post itself # In[16]: def url(my_dict): url_all = doc.find_all ("p", {'class': 'title'}) for i in url_all: url_tag = i.find('a')['href'] return url_tag url(doc) # In[17]: #url = doc.find_all ("p", {'class': 'title'}) #for i in url: #url_tag = i.find('a')['href'] #print(url_tag) # #### The URL of the thumbnail image associated with the post # In[18]: def image(my_dict): image = doc.find_all("a", {'class': 'thumbnail may-blank '}) for i in image: x = i.find('img')['src'] return x image(doc) # In[19]: #image = doc.find_all("a", {'class': 'thumbnail may-blank '}) #for i in image: #x = i.find('img')['src'] #print(x) # ### Creating a CSV # In[22]: all_redit = [] this_story = {} # Grab their headlines and bylines this_story['TITLE']= title(doc) this_story['Votes'] = votes(doc) this_story['Comments']= comments(doc) this_story['Subredit'] = subreddit(doc) this_story['Timestamp'] = timestamp(doc) this_story['URL'] = url(doc) this_story['URL of Thumbnail'] = image(doc) all_redit.append(this_story) # In[24]: #all_redit # In[ ]: redit_df = pd.DataFrame(all_redit) redit_df.head() # In[ ]: redit_df.to_csv("redit-data.csv") # In[ ]: import time # In[ ]: datestring = time.strftime("%Y-%m-%d-%H-%M") datestring # In[ ]: now = time.strftime("%B %d, %Y") now # In[ ]: filename = "redit-data-" + datestring + ".csv" my_file = redit_df.to_csv(filename, index=False) # In[ ]: key = 'key-f5edb244ca7303dc63f079a4cdb97f73' sandbox = 'sandbox3b984a674a954bcf8c5f2dca397bc3c1.mailgun.org' recipient = '[email protected]' # In[27]: request_url = 'https://api.mailgun.net/v2/{0}/messages'.format(sandbox) request = requests.post(request_url, auth=('api', key), files=[("attachment", open("my_file"))], data={ 'from': '[email protected]', 'to': recipient, 'subject': "Reddit This Morning:" + now, 'text': 'Reddit Updates from My Server', }) print('Status: {0}'.format(request.status_code)) print('Body: {0}'.format(request.text)) # In[ ]:
mit
ContinuumIO/blaze
blaze/server/tests/test_client.py
3
4346
from __future__ import absolute_import, division, print_function import pytest pytest.importorskip('flask') from pandas import DataFrame from blaze import compute, by, into, discover from blaze import data as bz_data from blaze.expr import Expr, symbol, Field from blaze.dispatch import dispatch from blaze.server import Server from blaze.server.client import Client from blaze.utils import example df = DataFrame([['Alice', 100], ['Bob', 200]], columns=['name', 'amount']) df2 = DataFrame([['Charlie', 100], ['Dan', 200]], columns=['name', 'amount']) tdata = {'accounts': df, 'accounts2': df} server = Server(tdata) add_server = Server(tdata, allow_add=True) test = server.app.test_client() test_add = add_server.app.test_client() from blaze.server import client client.requests = test # OMG monkey patching def test_client(): c = Client('localhost:6363') assert str(discover(c)) == str(discover(tdata)) t = symbol('t', discover(c)) expr = t.accounts.amount.sum() assert compute(expr, c) == 300 assert 'name' in t.accounts.fields assert isinstance(t.accounts.name, Field) assert compute(t.accounts.name, c) == ['Alice', 'Bob'] def test_expr_client_interactive(): c = Client('localhost:6363') t = bz_data(c) assert compute(t.accounts.name) == ['Alice', 'Bob'] assert (into(set, compute(by(t.accounts.name, min=t.accounts.amount.min(), max=t.accounts.amount.max()))) == set([('Alice', 100, 100), ('Bob', 200, 200)])) def test_compute_client_with_multiple_datasets(): c = bz_data('blaze://localhost:6363') s = symbol('s', discover(c)) assert compute(s.accounts.amount.sum() + s.accounts2.amount.sum(), {s: c}) == 600 def test_bz_data(): c = bz_data('blaze://localhost:6363') assert isinstance(c.data, Client) assert str(discover(c)) == str(discover(tdata)) def test_bz_data_default_port(): ec = bz_data('blaze://localhost') assert str(discover(ec)) == str(discover(tdata)) def test_bz_data_non_default_port(): ec = bz_data('blaze://localhost:6364') assert ec.data.url == 'http://localhost:6364' def test_bz_data_all_in_one(): ec = bz_data('blaze://localhost:6363') assert str(discover(ec)) == str(discover(tdata)) class CustomExpr(Expr): __slots__ = '_hash', '_child' @property def dshape(self): return self._child.dshape @dispatch(CustomExpr, DataFrame) def compute_up(expr, tdata, **kwargs): return tdata def test_custom_expressions(): ec = Client('localhost:6363') t = symbol('t', discover(ec)) assert list(map(tuple, compute(CustomExpr(t.accounts), ec))) == into(list, df) def test_client_dataset_fails(): with pytest.raises(ValueError): bz_data('blaze://localhost::accounts') with pytest.raises(ValueError): bz_data('blaze://localhost::accounts') def test_client_dataset(): d = bz_data('blaze://localhost') assert list(map(tuple, into(list, d.accounts))) == into(list, df) def test_client_cant_add_dataset(): ec = Client('localhost:6363') with pytest.raises(ValueError) as excinfo: ec.add('iris', example('iris.csv')) assert "Server does not support" in str(excinfo.value) def test_client_add_dataset(): client.requests = test_add # OMG more monkey patching ec = Client('localhost:6363') ec.add('iris', example('iris.csv')) assert 'iris' in ec.dshape.measure.dict iris_data = bz_data(example('iris.csv')) assert ec.dshape.measure.dict['iris'] == iris_data.dshape def test_client_add_dataset_failure(): client.requests = test_add # OMG more monkey patching ec = Client('localhost:6363') with pytest.raises(ValueError) as exc: ec.add('iris2', example('iris.csv'), -1, bad_arg='value') assert '422 UNPROCESSABLE ENTITY' in str(exc.value) def test_client_add_dataset_with_args(): client.requests = test_add # OMG more monkey patching ec = Client('localhost:6363') ec.add('teams', 'sqlite:///' + example('teams.db'), 'teams', primary_key='teamID') assert 'teams' in ec.dshape.measure.dict teams_data = bz_data('sqlite:///' + example('teams.db') + '::teams') assert ec.dshape.measure.dict['teams'] == teams_data.dshape
bsd-3-clause
bchappet/dnfpy
src/test_dnfpy/model/testImageColorSelection.py
1
1031
import numpy as np import unittest from dnfpy.model.imageColorSelection import ImageColorSelection import matplotlib.pyplot as plt import cv2 import dnfpy.view.staticViewMatplotlib as view import os def show2Img(im1,im2): view.plotArrays(dict(im1=im1,im2=im2)) plt.show() class TestImageColorSelection(unittest.TestCase): def setUp(self): path = os.path.dirname(os.path.realpath(__file__)) self.testDir =path + "/testFiles/" self.img = cv2.imread(self.testDir + "exampleFinger.png") self.uut = ImageColorSelection("uut",size = self.img.shape[0], image = self.img,dt=0.1,color='red',reverseColors=False,thresh=20, lowHSV=np.array([150,50,50]),highHSV = np.array([20,255,255])) def test_red(self): self.uut.compute() show2Img(self.img,self.uut.getData()) def test_gray(self): self.uut.setArg(color='gray') self.uut.compute() show2Img(self.img,self.uut.getData()) if __name__ == "__main__": unittest.main()
gpl-2.0
pablocarderam/genetargeter
gRNAScores/azimuth/predict.py
1
20980
from copy import deepcopy from multiprocessing import Pool from time import time import numpy as np from scipy.stats import spearmanr from sklearn.metrics import roc_curve, auc from sklearn.model_selection import StratifiedKFold from sklearn.preprocessing import LabelEncoder from .metrics import ndcg_at_k_ties from .models import DNN, GP, baselines, ensembles, regression from .util import spearmanr_nonan, concatenate_feature_sets def fill_in_truth_and_predictions( truth, predictions, fold, y_all, y_pred, learn_options, test ): truth[fold]["ranks"] = np.hstack( ( truth[fold]["ranks"], y_all[learn_options["rank-transformed target name"]].values[test].flatten(), ) ) truth[fold]["thrs"] = np.hstack( ( truth[fold]["thrs"], y_all[learn_options["binary target name"]].values[test].flatten(), ) ) if "raw_target_name" in learn_options: truth[fold]["raw"] = np.hstack( ( truth[fold]["raw"], y_all[learn_options["raw target name"]].values[test].flatten(), ) ) predictions[fold] = np.hstack((predictions[fold], y_pred.flatten())) return truth, predictions def construct_filename(learn_options, TEST): if "V" in learn_options: filename = f"V{learn_options['V']}" else: filename = "offV1" if TEST: filename = "TEST." filename += learn_options["method"] filename += f'.order{learn_options["order"]}' filename += learn_options["target_name"] if learn_options["method"] == "linreg" and learn_options["penalty"] is not None: filename += f".{learn_options['penalty']}" filename += "." + learn_options["cv"] if learn_options["training_metric"] == "NDCG": filename += f".NDGC_{learn_options['NDGC_k']}" elif learn_options["training_metric"] == "AUC": filename += ".AUC" elif learn_options["training_metric"] == "spearmanr": filename += ".spearman" print(f"filename = {filename}") return filename def extract_fpr_tpr_for_fold(aucs, y_binary, test, y_pred): if len(np.unique(y_binary)) > 2: raise AssertionError("if using AUC need binary targets") fpr, tpr, _ = roc_curve(y_binary[test], y_pred) roc_auc = auc(fpr, tpr) aucs.append(roc_auc) def extract_NDCG_for_fold(metrics, y_ground_truth, test, y_pred, learn_options): NDCG_fold = ndcg_at_k_ties( y_ground_truth[test].flatten(), y_pred.flatten(), learn_options["NDGC_k"] ) metrics.append(NDCG_fold) def extract_spearman_for_fold(metrics, y_ground_truth, test, y_pred): spearman = np.nan_to_num( spearmanr(y_ground_truth[test].flatten(), y_pred.flatten())[0] ) if np.isnan(spearman): raise AssertionError("found nan spearman") metrics.append(spearman) def get_train_test(test_gene, y_all, train_genes=None): # this is a bit convoluted because the train_genes+test_genes may not add up to all genes # for e.g. when we load up V3, but then use only V2, etc. not_test = y_all.index.get_level_values("Target gene").values != test_gene if train_genes is not None: in_train_genes = np.zeros(not_test.shape, dtype=bool) for t_gene in train_genes: in_train_genes = np.logical_or( in_train_genes, (y_all.index.get_level_values("Target gene").values == t_gene), ) train = np.logical_and(not_test, in_train_genes) else: train = not_test # y_all['test'] as to do with extra pairs in V2 if test_gene == "dummy": test = train else: test = y_all.index.get_level_values("Target gene").values == test_gene # convert to indices test = np.where(test)[0] train = np.where(train)[0] return train, test def cross_validate(y_all, feature_sets, learn_options=None, TEST=False, CV=True): # feature_sets is a dictionary of "set name" to pandas.DataFrame # one set might be single-nucleotide, position-independent features of order X, for e.g. # Method: "GPy" or "linreg" # Metric: NDCG (learning to rank metric, Normalized Discounted Cumulative Gain); AUC # Output: cv_score_median, gene_rocs # When CV=False, it trains on everything (and tests on everything, just to fit the code) # print(f"range of y_all is [{np.min(y_all[learn_options['target_name']].values)}, " # f"{np.max(y_all[learn_options['target_name']].values)}]") allowed_methods = [ "GPy", "linreg", "AdaBoostRegressor", "AdaBoostClassifier", "DecisionTreeRegressor", "RandomForestRegressor", "ARDRegression", "mean", "random", "DNN", "lasso_ensemble", "doench", "logregL1", "sgrna_from_doench", "SVC", "xu_et_al", ] if learn_options["method"] not in allowed_methods: raise AssertionError("invalid method: {learn_options['method']}") if ( learn_options["method"] != "linreg" or learn_options["penalty"] != "L2" ) and learn_options["weighted"] is not None: raise AssertionError( f"{learn_options['method']} {learn_options['weighted']} weighted " f"only works with linreg L2 right now" ) # construct filename from options filename = construct_filename(learn_options, TEST) print("Cross-validating genes...") t2 = time() y = np.array(y_all[learn_options["target_name"]].values[:, None], dtype=np.float64) # concatenate feature sets in to one nparray, and get dimension of each inputs, _, dimsum, feature_names = concatenate_feature_sets(feature_sets) if not CV: if learn_options["cv"] != "gene": raise AssertionError( "Must use gene-CV when CV is False (I need to use all of the " "genes and stratified complicates that)" ) # set-up for cross-validation # for outer loop, the one Doench et al use genes for if learn_options["cv"] == "stratified": if "extra_pairs" in learn_options or learn_options["extra pairs"]: raise AssertionError( "can't use extra pairs with stratified CV need to figure out how to properly " "account for genes affected by two drugs" ) label_encoder = LabelEncoder() label_encoder.fit(y_all["Target gene"].values) gene_classes = label_encoder.transform(y_all["Target gene"].values) if "n_folds" in learn_options: n_splits = learn_options["n_folds"] elif ( learn_options["train_genes"] is not None and learn_options["test_genes"] is not None ): n_splits = len(learn_options["test_genes"]) else: n_splits = len(learn_options["all_genes"]) skf = StratifiedKFold(n_splits=n_splits, shuffle=True) cv = skf.split(np.zeros(len(gene_classes), dtype=np.bool), gene_classes) fold_labels = [f"fold{i:d}" for i in range(1, n_splits + 1)] if learn_options["num_genes_remove_train"] is not None: raise NotImplementedError elif learn_options["cv"] == "gene": cv = [] if not CV: train_test_tmp = get_train_test( "dummy", y_all ) # get train, test split using a dummy gene # train_tmp, test_tmp = train_test_tmp # not a typo, using training set to test on as well, just for this case. # Test set is not used for internal cross-val, etc. anyway. # train_test_tmp = (train_tmp, train_tmp) cv.append(train_test_tmp) fold_labels = ["dummy_for_no_cv"] # learn_options['all_genes'] elif ( learn_options["train_genes"] is not None and learn_options["test_genes"] is not None ): if ( learn_options["train_genes"] is None or learn_options["test_genes"] is None ): raise AssertionError("use both or neither") for i, gene in enumerate(learn_options["test_genes"]): cv.append(get_train_test(gene, y_all, learn_options["train_genes"])) fold_labels = learn_options["test_genes"] # if train and test genes are seperate, there should be only one fold # train_test_disjoint = set.isdisjoint(set(learn_options["train_genes"].tolist()), # set(learn_options["test_genes"].tolist())) else: for i, gene in enumerate(learn_options["all_genes"]): train_test_tmp = get_train_test(gene, y_all) cv.append(train_test_tmp) fold_labels = learn_options["all_genes"] if learn_options["num_genes_remove_train"] is not None: for i, (train, test) in enumerate(cv): unique_genes = np.random.permutation( np.unique(np.unique(y_all["Target gene"][train])) ) genes_to_keep = unique_genes[ 0 : len(unique_genes) - learn_options["num_genes_remove_train"] ] filtered_train = [] for j, gene in enumerate(y_all["Target gene"]): if j in train and gene in genes_to_keep: filtered_train.append(j) cv_i_orig = deepcopy(cv[i]) cv[i] = (filtered_train, test) if learn_options["num_genes_remove_train"] == 0: if np.any(cv_i_orig[0] != cv[i][0]): raise AssertionError() if np.any(cv_i_orig[1] != cv[i][1]): raise AssertionError() print( f"# train/train after/before is {len(cv[i][0])}, {len(cv_i_orig[0])}" ) print( f"# test/test after/before is {len(cv[i][1])}, {len(cv_i_orig[1])}" ) else: raise Exception(f"invalid cv options given: {learn_options['cv']}") cv = [c for c in cv] # make list from generator, so can subset for TEST case if TEST: ind_to_use = [0] # [0,1] cv = [cv[i] for i in ind_to_use] fold_labels = [fold_labels[i] for i in ind_to_use] truth = dict( [ (t, dict([(m, np.array([])) for m in ["raw", "ranks", "thrs"]])) for t in fold_labels ] ) predictions = dict([(t, np.array([])) for t in fold_labels]) m = {} metrics = [] # do the cross-validation num_proc = learn_options["num_proc"] X = inputs if num_proc > 1: num_proc = np.min([num_proc, len(cv)]) print(f"using multiprocessing with {num_proc} procs -- one for each fold") jobs = [] pool = Pool(processes=num_proc) for i, fold in enumerate(cv): train, test = fold print( f"working on fold {i+1} of {len(cv)}, with {len(train)} train and {len(test)} test" ) if learn_options["method"] == "GPy": job = pool.apply_async( GP.gp_on_fold, args=(feature_sets, train, test, y, y_all, learn_options), ) elif learn_options["method"] == "linreg": job = pool.apply_async( regression.linreg_on_fold, args=(train, test, y, y_all, X, learn_options, fold), ) elif learn_options["method"] == "logregL1": job = pool.apply_async( regression.logreg_on_fold, args=(train, test, y, y_all, X, learn_options), ) elif learn_options["method"] == "AdaBoostRegressor": job = pool.apply_async( ensembles.adaboost_on_fold, args=(train, test, y, y_all, X, learn_options, False), ) elif learn_options["method"] == "AdaBoostClassifier": job = pool.apply_async( ensembles.adaboost_on_fold, args=(train, test, y, y_all, X, learn_options, True), ) elif learn_options["method"] == "DecisionTreeRegressor": job = pool.apply_async( ensembles.decisiontree_on_fold, args=(train, test, y, X) ) elif learn_options["method"] == "RandomForestRegressor": job = pool.apply_async( ensembles.randomforest_on_fold, args=(train, test, y, X) ) elif learn_options["method"] == "ARDRegression": job = pool.apply_async( regression.ARDRegression_on_fold, args=(train, test, y, X) ) elif learn_options["method"] == "random": job = pool.apply_async(baselines.random_on_fold, args=(test)) elif learn_options["method"] == "mean": job = pool.apply_async(baselines.mean_on_fold, args=(train, test, y)) elif learn_options["method"] == "SVC": job = pool.apply_async( baselines.SVC_on_fold, args=(train, test, y_all, X, learn_options) ) elif learn_options["method"] == "DNN": job = pool.apply_async( DNN.DNN_on_fold, args=(train, test, y_all, X, learn_options) ) elif learn_options["method"] == "lasso_ensemble": job = pool.apply_async( ensembles.LASSOs_ensemble_on_fold, args=(feature_sets, train, test, y, y_all, X, learn_options), ) elif learn_options["method"] == "doench": job = pool.apply_async( baselines.doench_on_fold, args=(train, test, y, y_all, X, learn_options), ) elif learn_options["method"] == "sgrna_from_doench": job = pool.apply_async( baselines.sgrna_from_doench_on_fold, args=(feature_sets, test, X) ) elif learn_options["method"] == "xu_et_al": job = pool.apply_async( baselines.xu_et_al_on_fold, args=(test, X, learn_options) ) else: raise Exception(f"did not find method={learn_options['method']}") jobs.append(job) pool.close() pool.join() print(f"finished fold {i + 1}") for i, fold in enumerate(cv): # i in range(0,len(jobs)): y_pred, m[i] = jobs[i].get() train, test = fold if learn_options["training_metric"] == "AUC": extract_fpr_tpr_for_fold( aucs=metrics, y_binary=y_all[learn_options["ground_truth_label"]].values, test=test, y_pred=y_pred, ) elif learn_options["training_metric"] == "NDCG": extract_NDCG_for_fold( metrics=metrics, y_ground_truth=y_all[learn_options["ground_truth_label"]].values, test=test, y_pred=y_pred, learn_options=learn_options, ) elif learn_options["training_metric"] == "spearmanr": extract_spearman_for_fold( metrics=metrics, y_ground_truth=y_all[learn_options["ground_truth_label"]].values, test=test, y_pred=y_pred, ) else: raise Exception( f"invalid 'training_metric' in learn_options: {learn_options['training_metric']}" ) truth, predictions = fill_in_truth_and_predictions( truth, predictions, fold_labels[i], y_all, y_pred, learn_options, test ) pool.terminate() else: # non parallel version for i, fold in enumerate(cv): train, test = fold if learn_options["method"] == "GPy": y_pred, m[i] = GP.gp_on_fold( feature_sets, train, test, y, y_all, learn_options ) elif learn_options["method"] == "linreg": y_pred, m[i] = regression.linreg_on_fold( train, test, y, y_all, X, learn_options ) elif learn_options["method"] == "logregL1": y_pred, m[i] = regression.logreg_on_fold( train, test, y, y_all, X, learn_options ) elif learn_options["method"] == "AdaBoostRegressor": y_pred, m[i] = ensembles.adaboost_on_fold( train, test, y, y_all, X, learn_options, classification=False ) elif learn_options["method"] == "AdaBoostClassifier": y_pred, m[i] = ensembles.adaboost_on_fold( train, test, y, y_all, X, learn_options, classification=True ) elif learn_options["method"] == "DecisionTreeRegressor": y_pred, m[i] = ensembles.decisiontree_on_fold(train, test, y, X) elif learn_options["method"] == "RandomForestRegressor": y_pred, m[i] = ensembles.randomforest_on_fold(train, test, y, X) elif learn_options["method"] == "ARDRegression": y_pred, m[i] = regression.ARDRegression_on_fold(train, test, y, X) elif learn_options["method"] == "random": y_pred, m[i] = baselines.random_on_fold(test) elif learn_options["method"] == "mean": y_pred, m[i] = baselines.mean_on_fold(train, test, y) elif learn_options["method"] == "SVC": y_pred, m[i] = baselines.SVC_on_fold( train, test, y_all, X, learn_options ) elif learn_options["method"] == "DNN": y_pred, m[i] = DNN.DNN_on_fold(train, test, y_all, X, learn_options) elif learn_options["method"] == "lasso_ensemble": y_pred, m[i] = ensembles.LASSOs_ensemble_on_fold( feature_sets, train, test, y, y_all, X, learn_options ) elif learn_options["method"] == "doench": y_pred, m[i] = baselines.doench_on_fold( train, test, y, y_all, X, learn_options ) elif learn_options["method"] == "sgrna_from_doench": y_pred, m[i] = baselines.sgrna_from_doench_on_fold( feature_sets, test, X ) elif learn_options["method"] == "xu_et_al": y_pred, m[i] = baselines.xu_et_al_on_fold(test, X, learn_options) else: raise Exception(f"invalid method found: {learn_options['method']}") if learn_options["training_metric"] == "AUC": # fills in truth and predictions extract_fpr_tpr_for_fold( aucs=metrics, y_binary=y_all[learn_options["ground_truth_label"]].values, test=test, y_pred=y_pred, ) elif learn_options["training_metric"] == "NDCG": extract_NDCG_for_fold( metrics=metrics, y_ground_truth=y_all[learn_options["ground_truth_label"]].values, test=test, y_pred=y_pred, learn_options=learn_options, ) elif learn_options["training_metric"] == "spearmanr": extract_spearman_for_fold( metrics=metrics, y_ground_truth=y_all[learn_options["ground_truth_label"]].values, test=test, y_pred=y_pred, ) truth, predictions = fill_in_truth_and_predictions( truth, predictions, fold_labels[i], y_all, y_pred, learn_options, test ) print(f"\t\tRMSE: {np.sqrt(((y_pred - y[test]) ** 2).mean())}") print( f"\t\tSpearman correlation: {np.nan_to_num(spearmanr_nonan(y[test], y_pred)[0])}" ) print(f"\t\tfinished fold/gene {i + 1} of {len(fold_labels)}") cv_median_metric = [np.median(metrics)] gene_pred = [(truth, predictions)] print( f"\t\tmedian {learn_options['training_metric']} across gene folds: {cv_median_metric[-1]:.3f}" ) t3 = time() print(f"\t\tElapsed time for cv is {(t3 - t2):.{2}} seconds") return metrics, gene_pred, fold_labels, m, dimsum, filename, feature_names
mit
jstoxrocky/statsmodels
statsmodels/graphics/tests/test_factorplots.py
27
1513
import numpy as np from nose import SkipTest from pandas import Series from statsmodels.graphics.factorplots import interaction_plot try: import matplotlib.pyplot as plt import matplotlib have_matplotlib = True except ImportError: have_matplotlib = False class TestInteractionPlot(object): @classmethod def setupClass(cls): if not have_matplotlib: raise SkipTest('matplotlib not available') np.random.seed(12345) cls.weight = np.random.randint(1,4,size=60) cls.duration = np.random.randint(1,3,size=60) cls.days = np.log(np.random.randint(1,30, size=60)) def test_plot_both(self): fig = interaction_plot(self.weight, self.duration, self.days, colors=['red','blue'], markers=['D','^'], ms=10) plt.close(fig) def test_plot_rainbow(self): fig = interaction_plot(self.weight, self.duration, self.days, markers=['D','^'], ms=10) plt.close(fig) def test_plot_pandas(self): weight = Series(self.weight, name='Weight') duration = Series(self.duration, name='Duration') days = Series(self.days, name='Days') fig = interaction_plot(weight, duration, days, markers=['D','^'], ms=10) ax = fig.axes[0] trace = ax.get_legend().get_title().get_text() assert trace == 'Duration' assert ax.get_ylabel() == 'mean of Days' assert ax.get_xlabel() == 'Weight' plt.close(fig)
bsd-3-clause
RomainBrault/scikit-learn
sklearn/preprocessing/label.py
28
28237
# Authors: Alexandre Gramfort <[email protected]> # Mathieu Blondel <[email protected]> # Olivier Grisel <[email protected]> # Andreas Mueller <[email protected]> # Joel Nothman <[email protected]> # Hamzeh Alsalhi <[email protected]> # License: BSD 3 clause from collections import defaultdict import itertools import array import numpy as np import scipy.sparse as sp from ..base import BaseEstimator, TransformerMixin from ..utils.fixes import np_version from ..utils.fixes import sparse_min_max from ..utils.fixes import astype from ..utils.fixes import in1d from ..utils import column_or_1d from ..utils.validation import check_array from ..utils.validation import check_is_fitted from ..utils.validation import _num_samples from ..utils.multiclass import unique_labels from ..utils.multiclass import type_of_target from ..externals import six zip = six.moves.zip map = six.moves.map __all__ = [ 'label_binarize', 'LabelBinarizer', 'LabelEncoder', 'MultiLabelBinarizer', ] def _check_numpy_unicode_bug(labels): """Check that user is not subject to an old numpy bug Fixed in master before 1.7.0: https://github.com/numpy/numpy/pull/243 """ if np_version[:3] < (1, 7, 0) and labels.dtype.kind == 'U': raise RuntimeError("NumPy < 1.7.0 does not implement searchsorted" " on unicode data correctly. Please upgrade" " NumPy to use LabelEncoder with unicode inputs.") class LabelEncoder(BaseEstimator, TransformerMixin): """Encode labels with value between 0 and n_classes-1. Read more in the :ref:`User Guide <preprocessing_targets>`. Attributes ---------- classes_ : array of shape (n_class,) Holds the label for each class. Examples -------- `LabelEncoder` can be used to normalize labels. >>> from sklearn import preprocessing >>> le = preprocessing.LabelEncoder() >>> le.fit([1, 2, 2, 6]) LabelEncoder() >>> le.classes_ array([1, 2, 6]) >>> le.transform([1, 1, 2, 6]) #doctest: +ELLIPSIS array([0, 0, 1, 2]...) >>> le.inverse_transform([0, 0, 1, 2]) array([1, 1, 2, 6]) It can also be used to transform non-numerical labels (as long as they are hashable and comparable) to numerical labels. >>> le = preprocessing.LabelEncoder() >>> le.fit(["paris", "paris", "tokyo", "amsterdam"]) LabelEncoder() >>> list(le.classes_) ['amsterdam', 'paris', 'tokyo'] >>> le.transform(["tokyo", "tokyo", "paris"]) #doctest: +ELLIPSIS array([2, 2, 1]...) >>> list(le.inverse_transform([2, 2, 1])) ['tokyo', 'tokyo', 'paris'] See also -------- sklearn.preprocessing.OneHotEncoder : encode categorical integer features using a one-hot aka one-of-K scheme. """ def fit(self, y): """Fit label encoder Parameters ---------- y : array-like of shape (n_samples,) Target values. Returns ------- self : returns an instance of self. """ y = column_or_1d(y, warn=True) _check_numpy_unicode_bug(y) self.classes_ = np.unique(y) return self def fit_transform(self, y): """Fit label encoder and return encoded labels Parameters ---------- y : array-like of shape [n_samples] Target values. Returns ------- y : array-like of shape [n_samples] """ y = column_or_1d(y, warn=True) _check_numpy_unicode_bug(y) self.classes_, y = np.unique(y, return_inverse=True) return y def transform(self, y): """Transform labels to normalized encoding. Parameters ---------- y : array-like of shape [n_samples] Target values. Returns ------- y : array-like of shape [n_samples] """ check_is_fitted(self, 'classes_') y = column_or_1d(y, warn=True) classes = np.unique(y) _check_numpy_unicode_bug(classes) if len(np.intersect1d(classes, self.classes_)) < len(classes): diff = np.setdiff1d(classes, self.classes_) raise ValueError("y contains new labels: %s" % str(diff)) return np.searchsorted(self.classes_, y) def inverse_transform(self, y): """Transform labels back to original encoding. Parameters ---------- y : numpy array of shape [n_samples] Target values. Returns ------- y : numpy array of shape [n_samples] """ check_is_fitted(self, 'classes_') diff = np.setdiff1d(y, np.arange(len(self.classes_))) if diff: raise ValueError("y contains new labels: %s" % str(diff)) y = np.asarray(y) return self.classes_[y] class LabelBinarizer(BaseEstimator, TransformerMixin): """Binarize labels in a one-vs-all fashion Several regression and binary classification algorithms are available in the scikit. A simple way to extend these algorithms to the multi-class classification case is to use the so-called one-vs-all scheme. At learning time, this simply consists in learning one regressor or binary classifier per class. In doing so, one needs to convert multi-class labels to binary labels (belong or does not belong to the class). LabelBinarizer makes this process easy with the transform method. At prediction time, one assigns the class for which the corresponding model gave the greatest confidence. LabelBinarizer makes this easy with the inverse_transform method. Read more in the :ref:`User Guide <preprocessing_targets>`. Parameters ---------- neg_label : int (default: 0) Value with which negative labels must be encoded. pos_label : int (default: 1) Value with which positive labels must be encoded. sparse_output : boolean (default: False) True if the returned array from transform is desired to be in sparse CSR format. Attributes ---------- classes_ : array of shape [n_class] Holds the label for each class. y_type_ : str, Represents the type of the target data as evaluated by utils.multiclass.type_of_target. Possible type are 'continuous', 'continuous-multioutput', 'binary', 'multiclass', 'multiclass-multioutput', 'multilabel-indicator', and 'unknown'. sparse_input_ : boolean, True if the input data to transform is given as a sparse matrix, False otherwise. Examples -------- >>> from sklearn import preprocessing >>> lb = preprocessing.LabelBinarizer() >>> lb.fit([1, 2, 6, 4, 2]) LabelBinarizer(neg_label=0, pos_label=1, sparse_output=False) >>> lb.classes_ array([1, 2, 4, 6]) >>> lb.transform([1, 6]) array([[1, 0, 0, 0], [0, 0, 0, 1]]) Binary targets transform to a column vector >>> lb = preprocessing.LabelBinarizer() >>> lb.fit_transform(['yes', 'no', 'no', 'yes']) array([[1], [0], [0], [1]]) Passing a 2D matrix for multilabel classification >>> import numpy as np >>> lb.fit(np.array([[0, 1, 1], [1, 0, 0]])) LabelBinarizer(neg_label=0, pos_label=1, sparse_output=False) >>> lb.classes_ array([0, 1, 2]) >>> lb.transform([0, 1, 2, 1]) array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 1, 0]]) See also -------- label_binarize : function to perform the transform operation of LabelBinarizer with fixed classes. sklearn.preprocessing.OneHotEncoder : encode categorical integer features using a one-hot aka one-of-K scheme. """ def __init__(self, neg_label=0, pos_label=1, sparse_output=False): if neg_label >= pos_label: raise ValueError("neg_label={0} must be strictly less than " "pos_label={1}.".format(neg_label, pos_label)) if sparse_output and (pos_label == 0 or neg_label != 0): raise ValueError("Sparse binarization is only supported with non " "zero pos_label and zero neg_label, got " "pos_label={0} and neg_label={1}" "".format(pos_label, neg_label)) self.neg_label = neg_label self.pos_label = pos_label self.sparse_output = sparse_output def fit(self, y): """Fit label binarizer Parameters ---------- y : array of shape [n_samples,] or [n_samples, n_classes] Target values. The 2-d matrix should only contain 0 and 1, represents multilabel classification. Returns ------- self : returns an instance of self. """ self.y_type_ = type_of_target(y) if 'multioutput' in self.y_type_: raise ValueError("Multioutput target data is not supported with " "label binarization") if _num_samples(y) == 0: raise ValueError('y has 0 samples: %r' % y) self.sparse_input_ = sp.issparse(y) self.classes_ = unique_labels(y) return self def fit_transform(self, y): """Fit label binarizer and transform multi-class labels to binary labels. The output of transform is sometimes referred to as the 1-of-K coding scheme. Parameters ---------- y : array or sparse matrix of shape [n_samples,] or \ [n_samples, n_classes] Target values. The 2-d matrix should only contain 0 and 1, represents multilabel classification. Sparse matrix can be CSR, CSC, COO, DOK, or LIL. Returns ------- Y : array or CSR matrix of shape [n_samples, n_classes] Shape will be [n_samples, 1] for binary problems. """ return self.fit(y).transform(y) def transform(self, y): """Transform multi-class labels to binary labels The output of transform is sometimes referred to by some authors as the 1-of-K coding scheme. Parameters ---------- y : array or sparse matrix of shape [n_samples,] or \ [n_samples, n_classes] Target values. The 2-d matrix should only contain 0 and 1, represents multilabel classification. Sparse matrix can be CSR, CSC, COO, DOK, or LIL. Returns ------- Y : numpy array or CSR matrix of shape [n_samples, n_classes] Shape will be [n_samples, 1] for binary problems. """ check_is_fitted(self, 'classes_') y_is_multilabel = type_of_target(y).startswith('multilabel') if y_is_multilabel and not self.y_type_.startswith('multilabel'): raise ValueError("The object was not fitted with multilabel" " input.") return label_binarize(y, self.classes_, pos_label=self.pos_label, neg_label=self.neg_label, sparse_output=self.sparse_output) def inverse_transform(self, Y, threshold=None): """Transform binary labels back to multi-class labels Parameters ---------- Y : numpy array or sparse matrix with shape [n_samples, n_classes] Target values. All sparse matrices are converted to CSR before inverse transformation. threshold : float or None Threshold used in the binary and multi-label cases. Use 0 when: - Y contains the output of decision_function (classifier) Use 0.5 when: - Y contains the output of predict_proba If None, the threshold is assumed to be half way between neg_label and pos_label. Returns ------- y : numpy array or CSR matrix of shape [n_samples] Target values. Notes ----- In the case when the binary labels are fractional (probabilistic), inverse_transform chooses the class with the greatest value. Typically, this allows to use the output of a linear model's decision_function method directly as the input of inverse_transform. """ check_is_fitted(self, 'classes_') if threshold is None: threshold = (self.pos_label + self.neg_label) / 2. if self.y_type_ == "multiclass": y_inv = _inverse_binarize_multiclass(Y, self.classes_) else: y_inv = _inverse_binarize_thresholding(Y, self.y_type_, self.classes_, threshold) if self.sparse_input_: y_inv = sp.csr_matrix(y_inv) elif sp.issparse(y_inv): y_inv = y_inv.toarray() return y_inv def label_binarize(y, classes, neg_label=0, pos_label=1, sparse_output=False): """Binarize labels in a one-vs-all fashion Several regression and binary classification algorithms are available in the scikit. A simple way to extend these algorithms to the multi-class classification case is to use the so-called one-vs-all scheme. This function makes it possible to compute this transformation for a fixed set of class labels known ahead of time. Parameters ---------- y : array-like Sequence of integer labels or multilabel data to encode. classes : array-like of shape [n_classes] Uniquely holds the label for each class. neg_label : int (default: 0) Value with which negative labels must be encoded. pos_label : int (default: 1) Value with which positive labels must be encoded. sparse_output : boolean (default: False), Set to true if output binary array is desired in CSR sparse format Returns ------- Y : numpy array or CSR matrix of shape [n_samples, n_classes] Shape will be [n_samples, 1] for binary problems. Examples -------- >>> from sklearn.preprocessing import label_binarize >>> label_binarize([1, 6], classes=[1, 2, 4, 6]) array([[1, 0, 0, 0], [0, 0, 0, 1]]) The class ordering is preserved: >>> label_binarize([1, 6], classes=[1, 6, 4, 2]) array([[1, 0, 0, 0], [0, 1, 0, 0]]) Binary targets transform to a column vector >>> label_binarize(['yes', 'no', 'no', 'yes'], classes=['no', 'yes']) array([[1], [0], [0], [1]]) See also -------- LabelBinarizer : class used to wrap the functionality of label_binarize and allow for fitting to classes independently of the transform operation """ if not isinstance(y, list): # XXX Workaround that will be removed when list of list format is # dropped y = check_array(y, accept_sparse='csr', ensure_2d=False, dtype=None) else: if _num_samples(y) == 0: raise ValueError('y has 0 samples: %r' % y) if neg_label >= pos_label: raise ValueError("neg_label={0} must be strictly less than " "pos_label={1}.".format(neg_label, pos_label)) if (sparse_output and (pos_label == 0 or neg_label != 0)): raise ValueError("Sparse binarization is only supported with non " "zero pos_label and zero neg_label, got " "pos_label={0} and neg_label={1}" "".format(pos_label, neg_label)) # To account for pos_label == 0 in the dense case pos_switch = pos_label == 0 if pos_switch: pos_label = -neg_label y_type = type_of_target(y) if 'multioutput' in y_type: raise ValueError("Multioutput target data is not supported with label " "binarization") if y_type == 'unknown': raise ValueError("The type of target data is not known") n_samples = y.shape[0] if sp.issparse(y) else len(y) n_classes = len(classes) classes = np.asarray(classes) if y_type == "binary": if n_classes == 1: if sparse_output: return sp.csr_matrix((n_samples, 1), dtype=int) else: Y = np.zeros((len(y), 1), dtype=np.int) Y += neg_label return Y elif len(classes) >= 3: y_type = "multiclass" sorted_class = np.sort(classes) if (y_type == "multilabel-indicator" and classes.size != y.shape[1]): raise ValueError("classes {0} missmatch with the labels {1}" "found in the data".format(classes, unique_labels(y))) if y_type in ("binary", "multiclass"): y = column_or_1d(y) # pick out the known labels from y y_in_classes = in1d(y, classes) y_seen = y[y_in_classes] indices = np.searchsorted(sorted_class, y_seen) indptr = np.hstack((0, np.cumsum(y_in_classes))) data = np.empty_like(indices) data.fill(pos_label) Y = sp.csr_matrix((data, indices, indptr), shape=(n_samples, n_classes)) elif y_type == "multilabel-indicator": Y = sp.csr_matrix(y) if pos_label != 1: data = np.empty_like(Y.data) data.fill(pos_label) Y.data = data else: raise ValueError("%s target data is not supported with label " "binarization" % y_type) if not sparse_output: Y = Y.toarray() Y = astype(Y, int, copy=False) if neg_label != 0: Y[Y == 0] = neg_label if pos_switch: Y[Y == pos_label] = 0 else: Y.data = astype(Y.data, int, copy=False) # preserve label ordering if np.any(classes != sorted_class): indices = np.searchsorted(sorted_class, classes) Y = Y[:, indices] if y_type == "binary": if sparse_output: Y = Y.getcol(-1) else: Y = Y[:, -1].reshape((-1, 1)) return Y def _inverse_binarize_multiclass(y, classes): """Inverse label binarization transformation for multiclass. Multiclass uses the maximal score instead of a threshold. """ classes = np.asarray(classes) if sp.issparse(y): # Find the argmax for each row in y where y is a CSR matrix y = y.tocsr() n_samples, n_outputs = y.shape outputs = np.arange(n_outputs) row_max = sparse_min_max(y, 1)[1] row_nnz = np.diff(y.indptr) y_data_repeated_max = np.repeat(row_max, row_nnz) # picks out all indices obtaining the maximum per row y_i_all_argmax = np.flatnonzero(y_data_repeated_max == y.data) # For corner case where last row has a max of 0 if row_max[-1] == 0: y_i_all_argmax = np.append(y_i_all_argmax, [len(y.data)]) # Gets the index of the first argmax in each row from y_i_all_argmax index_first_argmax = np.searchsorted(y_i_all_argmax, y.indptr[:-1]) # first argmax of each row y_ind_ext = np.append(y.indices, [0]) y_i_argmax = y_ind_ext[y_i_all_argmax[index_first_argmax]] # Handle rows of all 0 y_i_argmax[np.where(row_nnz == 0)[0]] = 0 # Handles rows with max of 0 that contain negative numbers samples = np.arange(n_samples)[(row_nnz > 0) & (row_max.ravel() == 0)] for i in samples: ind = y.indices[y.indptr[i]:y.indptr[i + 1]] y_i_argmax[i] = classes[np.setdiff1d(outputs, ind)][0] return classes[y_i_argmax] else: return classes.take(y.argmax(axis=1), mode="clip") def _inverse_binarize_thresholding(y, output_type, classes, threshold): """Inverse label binarization transformation using thresholding.""" if output_type == "binary" and y.ndim == 2 and y.shape[1] > 2: raise ValueError("output_type='binary', but y.shape = {0}". format(y.shape)) if output_type != "binary" and y.shape[1] != len(classes): raise ValueError("The number of class is not equal to the number of " "dimension of y.") classes = np.asarray(classes) # Perform thresholding if sp.issparse(y): if threshold > 0: if y.format not in ('csr', 'csc'): y = y.tocsr() y.data = np.array(y.data > threshold, dtype=np.int) y.eliminate_zeros() else: y = np.array(y.toarray() > threshold, dtype=np.int) else: y = np.array(y > threshold, dtype=np.int) # Inverse transform data if output_type == "binary": if sp.issparse(y): y = y.toarray() if y.ndim == 2 and y.shape[1] == 2: return classes[y[:, 1]] else: if len(classes) == 1: return np.repeat(classes[0], len(y)) else: return classes[y.ravel()] elif output_type == "multilabel-indicator": return y else: raise ValueError("{0} format is not supported".format(output_type)) class MultiLabelBinarizer(BaseEstimator, TransformerMixin): """Transform between iterable of iterables and a multilabel format Although a list of sets or tuples is a very intuitive format for multilabel data, it is unwieldy to process. This transformer converts between this intuitive format and the supported multilabel format: a (samples x classes) binary matrix indicating the presence of a class label. Parameters ---------- classes : array-like of shape [n_classes] (optional) Indicates an ordering for the class labels sparse_output : boolean (default: False), Set to true if output binary array is desired in CSR sparse format Attributes ---------- classes_ : array of labels A copy of the `classes` parameter where provided, or otherwise, the sorted set of classes found when fitting. Examples -------- >>> from sklearn.preprocessing import MultiLabelBinarizer >>> mlb = MultiLabelBinarizer() >>> mlb.fit_transform([(1, 2), (3,)]) array([[1, 1, 0], [0, 0, 1]]) >>> mlb.classes_ array([1, 2, 3]) >>> mlb.fit_transform([set(['sci-fi', 'thriller']), set(['comedy'])]) array([[0, 1, 1], [1, 0, 0]]) >>> list(mlb.classes_) ['comedy', 'sci-fi', 'thriller'] See also -------- sklearn.preprocessing.OneHotEncoder : encode categorical integer features using a one-hot aka one-of-K scheme. """ def __init__(self, classes=None, sparse_output=False): self.classes = classes self.sparse_output = sparse_output def fit(self, y): """Fit the label sets binarizer, storing `classes_` Parameters ---------- y : iterable of iterables A set of labels (any orderable and hashable object) for each sample. If the `classes` parameter is set, `y` will not be iterated. Returns ------- self : returns this MultiLabelBinarizer instance """ if self.classes is None: classes = sorted(set(itertools.chain.from_iterable(y))) else: classes = self.classes dtype = np.int if all(isinstance(c, int) for c in classes) else object self.classes_ = np.empty(len(classes), dtype=dtype) self.classes_[:] = classes return self def fit_transform(self, y): """Fit the label sets binarizer and transform the given label sets Parameters ---------- y : iterable of iterables A set of labels (any orderable and hashable object) for each sample. If the `classes` parameter is set, `y` will not be iterated. Returns ------- y_indicator : array or CSR matrix, shape (n_samples, n_classes) A matrix such that `y_indicator[i, j] = 1` iff `classes_[j]` is in `y[i]`, and 0 otherwise. """ if self.classes is not None: return self.fit(y).transform(y) # Automatically increment on new class class_mapping = defaultdict(int) class_mapping.default_factory = class_mapping.__len__ yt = self._transform(y, class_mapping) # sort classes and reorder columns tmp = sorted(class_mapping, key=class_mapping.get) # (make safe for tuples) dtype = np.int if all(isinstance(c, int) for c in tmp) else object class_mapping = np.empty(len(tmp), dtype=dtype) class_mapping[:] = tmp self.classes_, inverse = np.unique(class_mapping, return_inverse=True) # ensure yt.indices keeps its current dtype yt.indices = np.array(inverse[yt.indices], dtype=yt.indices.dtype, copy=False) if not self.sparse_output: yt = yt.toarray() return yt def transform(self, y): """Transform the given label sets Parameters ---------- y : iterable of iterables A set of labels (any orderable and hashable object) for each sample. If the `classes` parameter is set, `y` will not be iterated. Returns ------- y_indicator : array or CSR matrix, shape (n_samples, n_classes) A matrix such that `y_indicator[i, j] = 1` iff `classes_[j]` is in `y[i]`, and 0 otherwise. """ check_is_fitted(self, 'classes_') class_to_index = dict(zip(self.classes_, range(len(self.classes_)))) yt = self._transform(y, class_to_index) if not self.sparse_output: yt = yt.toarray() return yt def _transform(self, y, class_mapping): """Transforms the label sets with a given mapping Parameters ---------- y : iterable of iterables class_mapping : Mapping Maps from label to column index in label indicator matrix Returns ------- y_indicator : sparse CSR matrix, shape (n_samples, n_classes) Label indicator matrix """ indices = array.array('i') indptr = array.array('i', [0]) for labels in y: indices.extend(set(class_mapping[label] for label in labels)) indptr.append(len(indices)) data = np.ones(len(indices), dtype=int) return sp.csr_matrix((data, indices, indptr), shape=(len(indptr) - 1, len(class_mapping))) def inverse_transform(self, yt): """Transform the given indicator matrix into label sets Parameters ---------- yt : array or sparse matrix of shape (n_samples, n_classes) A matrix containing only 1s ands 0s. Returns ------- y : list of tuples The set of labels for each sample such that `y[i]` consists of `classes_[j]` for each `yt[i, j] == 1`. """ check_is_fitted(self, 'classes_') if yt.shape[1] != len(self.classes_): raise ValueError('Expected indicator for {0} classes, but got {1}' .format(len(self.classes_), yt.shape[1])) if sp.issparse(yt): yt = yt.tocsr() if len(yt.data) != 0 and len(np.setdiff1d(yt.data, [0, 1])) > 0: raise ValueError('Expected only 0s and 1s in label indicator.') return [tuple(self.classes_.take(yt.indices[start:end])) for start, end in zip(yt.indptr[:-1], yt.indptr[1:])] else: unexpected = np.setdiff1d(yt, [0, 1]) if len(unexpected) > 0: raise ValueError('Expected only 0s and 1s in label indicator. ' 'Also got {0}'.format(unexpected)) return [tuple(self.classes_.compress(indicators)) for indicators in yt]
bsd-3-clause
dhutchis/systemml
src/main/python/systemml/mlcontext.py
1
26980
#------------------------------------------------------------- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. # #------------------------------------------------------------- # Methods to create Script object script_factory_methods = [ 'dml', 'pydml', 'dmlFromResource', 'pydmlFromResource', 'dmlFromFile', 'pydmlFromFile', 'dmlFromUrl', 'pydmlFromUrl' ] # Utility methods util_methods = [ 'jvm_stdout', '_java2py', 'getHopDAG' ] __all__ = ['MLResults', 'MLContext', 'Script', 'Matrix' ] + script_factory_methods + util_methods import os import numpy as np import pandas as pd import threading, time try: import py4j.java_gateway from py4j.java_gateway import JavaObject from pyspark import SparkContext from pyspark.conf import SparkConf import pyspark.mllib.common from pyspark.sql import SparkSession except ImportError: raise ImportError('Unable to import `pyspark`. Hint: Make sure you are running with PySpark.') from .converters import * from .classloader import * _loadedSystemML = False def _get_spark_context(): """ Internal method to get already initialized SparkContext. Developers should always use _get_spark_context() instead of SparkContext._active_spark_context to ensure SystemML loaded. Returns ------- sc: SparkContext SparkContext """ if SparkContext._active_spark_context is not None: sc = SparkContext._active_spark_context global _loadedSystemML if not _loadedSystemML: createJavaObject(sc, 'dummy') _loadedSystemML = True return sc else: raise Exception('Expected spark context to be created.') # This is useful utility class to get the output of the driver JVM from within a Jupyter notebook # Example usage: # with jvm_stdout(): # ml.execute(script) class jvm_stdout(object): """ This is useful utility class to get the output of the driver JVM from within a Jupyter notebook Parameters ---------- parallel_flush: boolean Should flush the stdout in parallel """ def __init__(self, parallel_flush=False): self.util = _get_spark_context()._jvm.org.apache.sysml.api.ml.Utils() self.parallel_flush = parallel_flush self.t = threading.Thread(target=self.flush_stdout) self.stop = False def flush_stdout(self): while not self.stop: time.sleep(1) # flush stdout every 1 second str = self.util.flushStdOut() if str != '': str = str[:-1] if str.endswith('\n') else str print(str) def __enter__(self): self.util.startRedirectStdOut() if self.parallel_flush: self.t.start() def __exit__(self, *args): if self.parallel_flush: self.stop = True self.t.join() print(self.util.stopRedirectStdOut()) def getHopDAG(ml, script, lines=None, conf=None, apply_rewrites=True, with_subgraph=False): """ Compile a DML / PyDML script. Parameters ---------- ml: MLContext instance MLContext instance. script: Script instance Script instance defined with the appropriate input and output variables. lines: list of integers Optional: only display the hops that have begin and end line number equals to the given integers. conf: SparkConf instance Optional spark configuration apply_rewrites: boolean If True, perform static rewrites, perform intra-/inter-procedural analysis to propagate size information into functions and apply dynamic rewrites with_subgraph: boolean If False, the dot graph will be created without subgraphs for statement blocks. Returns ------- hopDAG: string hop DAG in dot format """ if not isinstance(script, Script): raise ValueError("Expected script to be an instance of Script") scriptString = script.scriptString script_java = script.script_java lines = [ int(x) for x in lines ] if lines is not None else [int(-1)] sc = _get_spark_context() if conf is not None: hopDAG = sc._jvm.org.apache.sysml.api.mlcontext.MLContextUtil.getHopDAG(ml._ml, script_java, lines, conf._jconf, apply_rewrites, with_subgraph) else: hopDAG = sc._jvm.org.apache.sysml.api.mlcontext.MLContextUtil.getHopDAG(ml._ml, script_java, lines, apply_rewrites, with_subgraph) return hopDAG def dml(scriptString): """ Create a dml script object based on a string. Parameters ---------- scriptString: string Can be a path to a dml script or a dml script itself. Returns ------- script: Script instance Instance of a script object. """ if not isinstance(scriptString, str): raise ValueError("scriptString should be a string, got %s" % type(scriptString)) return Script(scriptString, scriptType="dml") def dmlFromResource(resourcePath): """ Create a dml script object based on a resource path. Parameters ---------- resourcePath: string Path to a dml script on the classpath. Returns ------- script: Script instance Instance of a script object. """ if not isinstance(resourcePath, str): raise ValueError("resourcePath should be a string, got %s" % type(resourcePath)) return Script(resourcePath, scriptType="dml", isResource=True) def pydml(scriptString): """ Create a pydml script object based on a string. Parameters ---------- scriptString: string Can be a path to a pydml script or a pydml script itself. Returns ------- script: Script instance Instance of a script object. """ if not isinstance(scriptString, str): raise ValueError("scriptString should be a string, got %s" % type(scriptString)) return Script(scriptString, scriptType="pydml") def pydmlFromResource(resourcePath): """ Create a pydml script object based on a resource path. Parameters ---------- resourcePath: string Path to a pydml script on the classpath. Returns ------- script: Script instance Instance of a script object. """ if not isinstance(resourcePath, str): raise ValueError("resourcePath should be a string, got %s" % type(resourcePath)) return Script(resourcePath, scriptType="pydml", isResource=True) def dmlFromFile(filePath): """ Create a dml script object based on a file path. Parameters ---------- filePath: string Path to a dml script. Returns ------- script: Script instance Instance of a script object. """ if not isinstance(filePath, str): raise ValueError("filePath should be a string, got %s" % type(filePath)) return Script(filePath, scriptType="dml", isResource=False, scriptFormat="file") def pydmlFromFile(filePath): """ Create a pydml script object based on a file path. Parameters ---------- filePath: string Path to a pydml script. Returns ------- script: Script instance Instance of a script object. """ if not isinstance(filePath, str): raise ValueError("filePath should be a string, got %s" % type(filePath)) return Script(filePath, scriptType="pydml", isResource=False, scriptFormat="file") def dmlFromUrl(url): """ Create a dml script object based on a url. Parameters ---------- url: string URL to a dml script. Returns ------- script: Script instance Instance of a script object. """ if not isinstance(url, str): raise ValueError("url should be a string, got %s" % type(url)) return Script(url, scriptType="dml", isResource=False, scriptFormat="url") def pydmlFromUrl(url): """ Create a pydml script object based on a url. Parameters ---------- url: string URL to a pydml script. Returns ------- script: Script instance Instance of a script object. """ if not isinstance(url, str): raise ValueError("url should be a string, got %s" % type(url)) return Script(url, scriptType="pydml", isResource=False, scriptFormat="url") def _java2py(sc, obj): """ Convert Java object to Python. """ # TODO: Port this private PySpark function. obj = pyspark.mllib.common._java2py(sc, obj) if isinstance(obj, JavaObject): class_name = obj.getClass().getSimpleName() if class_name == 'Matrix': obj = Matrix(obj, sc) return obj def _py2java(sc, obj): """ Convert Python object to Java. """ if isinstance(obj, SUPPORTED_TYPES): obj = convertToMatrixBlock(sc, obj) else: if isinstance(obj, Matrix): obj = obj._java_matrix # TODO: Port this private PySpark function. obj = pyspark.mllib.common._py2java(sc, obj) return obj class Matrix(object): """ Wrapper around a Java Matrix object. Parameters ---------- javaMatrix: JavaObject A Java Matrix object as returned by calling `ml.execute().get()`. sc: SparkContext SparkContext """ def __init__(self, javaMatrix, sc): self._java_matrix = javaMatrix self._sc = sc def __repr__(self): return "Matrix" def toDF(self): """ Convert the Matrix to a PySpark SQL DataFrame. Returns ------- PySpark SQL DataFrame A PySpark SQL DataFrame representing the matrix, with one "__INDEX" column containing the row index (since Spark DataFrames are unordered), followed by columns of doubles for each column in the matrix. """ jdf = self._java_matrix.toDF() df = _java2py(self._sc, jdf) return df def toNumPy(self): """ Convert the Matrix to a NumPy Array. Returns ------- NumPy Array A NumPy Array representing the Matrix object. """ np_array = convertToNumPyArr(self._sc, self._java_matrix.toMatrixBlock()) return np_array class MLResults(object): """ Wrapper around a Java ML Results object. Parameters ---------- results: JavaObject A Java MLResults object as returned by calling `ml.execute()`. sc: SparkContext SparkContext """ def __init__(self, results, sc): self._java_results = results self._sc = sc def __repr__(self): return "MLResults" def get(self, *outputs): """ Parameters ---------- outputs: string, list of strings Output variables as defined inside the DML script. """ outs = [_java2py(self._sc, self._java_results.get(out)) for out in outputs] if len(outs) == 1: return outs[0] return outs class Script(object): """ Instance of a DML/PyDML Script. Parameters ---------- scriptString: string Can be either a file path to a DML script or a DML script itself. scriptType: string Script language, either "dml" for DML (R-like) or "pydml" for PyDML (Python-like). isResource: boolean If true, scriptString is a path to a resource on the classpath scriptFormat: string Optional script format, either "auto" or "url" or "file" or "resource" or "string" """ def __init__(self, scriptString, scriptType="dml", isResource=False, scriptFormat="auto"): self.sc = _get_spark_context() self.scriptString = scriptString self.scriptType = scriptType self.isResource = isResource if scriptFormat != "auto": if scriptFormat == "url" and self.scriptType == "dml": self.script_java = self.sc._jvm.org.apache.sysml.api.mlcontext.ScriptFactory.dmlFromUrl(scriptString) elif scriptFormat == "url" and self.scriptType == "pydml": self.script_java = self.sc._jvm.org.apache.sysml.api.mlcontext.ScriptFactory.pydmlFromUrl(scriptString) elif scriptFormat == "file" and self.scriptType == "dml": self.script_java = self.sc._jvm.org.apache.sysml.api.mlcontext.ScriptFactory.dmlFromFile(scriptString) elif scriptFormat == "file" and self.scriptType == "pydml": self.script_java = self.sc._jvm.org.apache.sysml.api.mlcontext.ScriptFactory.pydmlFromFile(scriptString) elif isResource and self.scriptType == "dml": self.script_java = self.sc._jvm.org.apache.sysml.api.mlcontext.ScriptFactory.dmlFromResource(scriptString) elif isResource and self.scriptType == "pydml": self.script_java = self.sc._jvm.org.apache.sysml.api.mlcontext.ScriptFactory.pydmlFromResource(scriptString) elif scriptFormat == "string" and self.scriptType == "dml": self.script_java = self.sc._jvm.org.apache.sysml.api.mlcontext.ScriptFactory.dml(scriptString) elif scriptFormat == "string" and self.scriptType == "pydml": self.script_java = self.sc._jvm.org.apache.sysml.api.mlcontext.ScriptFactory.pydml(scriptString) else: raise ValueError('Unsupported script format' + scriptFormat) elif self.scriptType == "dml": if scriptString.endswith(".dml"): if scriptString.startswith("http"): self.script_java = self.sc._jvm.org.apache.sysml.api.mlcontext.ScriptFactory.dmlFromUrl(scriptString) elif os.path.exists(scriptString): self.script_java = self.sc._jvm.org.apache.sysml.api.mlcontext.ScriptFactory.dmlFromFile(scriptString) elif self.isResource == True: self.script_java = self.sc._jvm.org.apache.sysml.api.mlcontext.ScriptFactory.dmlFromResource(scriptString) else: raise ValueError("path: %s does not exist" % scriptString) else: self.script_java = self.sc._jvm.org.apache.sysml.api.mlcontext.ScriptFactory.dml(scriptString) elif self.scriptType == "pydml": if scriptString.endswith(".pydml"): if scriptString.startswith("http"): self.script_java = self.sc._jvm.org.apache.sysml.api.mlcontext.ScriptFactory.pydmlFromUrl(scriptString) elif os.path.exists(scriptString): self.script_java = self.sc._jvm.org.apache.sysml.api.mlcontext.ScriptFactory.pydmlFromFile(scriptString) elif self.isResource == True: self.script_java = self.sc._jvm.org.apache.sysml.api.mlcontext.ScriptFactory.pydmlFromResource(scriptString) else: raise ValueError("path: %s does not exist" % scriptString) else: self.script_java = self.sc._jvm.org.apache.sysml.api.mlcontext.ScriptFactory.pydml(scriptString) def getScriptString(self): """ Obtain the script string (in unicode). """ return self.script_java.getScriptString() def setScriptString(self, scriptString): """ Set the script string. Parameters ---------- scriptString: string Can be either a file path to a DML script or a DML script itself. """ self.scriptString = scriptString self.script_java.setScriptString(scriptString) return self def getInputVariables(self): """ Obtain the input variable names. """ return self.script_java.getInputVariables() def getOutputVariables(self): """ Obtain the output variable names. """ return self.script_java.getOutputVariables() def clearIOS(self): """ Clear the inputs, outputs, and symbol table. """ self.script_java.clearIOS() return self def clearIO(self): """ Clear the inputs and outputs, but not the symbol table. """ self.script_java.clearIO() return self def clearAll(self): """ Clear the script string, inputs, outputs, and symbol table. """ self.script_java.clearAll() return self def clearInputs(self): """ Clear the inputs. """ self.script_java.clearInputs() return self def clearOutputs(self): """ Clear the outputs. """ self.script_java.clearOutputs() return self def clearSymbolTable(self): """ Clear the symbol table. """ self.script_java.clearSymbolTable() return self def results(self): """ Obtain the results of the script execution. """ return MLResults(self.script_java.results(), self.sc) def getResults(self): """ Obtain the results of the script execution. """ return MLResults(self.script_java.getResults(), self.sc) def setResults(self, results): """ Set the results of the script execution. """ self.script_java.setResults(results._java_results) return self def isDML(self): """ Is the script type DML? """ return self.script_java.isDML() def isPYDML(self): """ Is the script type DML? """ return self.script_java.isPYDML() def getScriptExecutionString(self): """ Generate the script execution string, which adds read/load/write/save statements to the beginning and end of the script to execute. """ return self.script_java.getScriptExecutionString() def __repr__(self): return "Script" def info(self): """ Display information about the script as a String. This consists of the script type, inputs, outputs, input parameters, input variables, output variables, the symbol table, the script string, and the script execution string. """ return self.script_java.info() def displayInputs(self): """ Display the script inputs. """ return self.script_java.displayInputs() def displayOutputs(self): """ Display the script outputs. """ return self.script_java.displayOutputs() def displayInputParameters(self): """ Display the script input parameters. """ return self.script_java.displayInputParameters() def displayInputVariables(self): """ Display the script input variables. """ return self.script_java.displayInputVariables() def displayOutputVariables(self): """ Display the script output variables. """ return self.script_java.displayOutputVariables() def displaySymbolTable(self): """ Display the script symbol table. """ return self.script_java.displaySymbolTable() def getName(self): """ Obtain the script name. """ return self.script_java.getName() def setName(self, name): """ Set the script name. """ self.script_java.setName(name) return self def getScriptType(self): """ Obtain the script type. """ return self.scriptType def input(self, *args, **kwargs): """ Parameters ---------- args: name, value tuple where name is a string, and currently supported value formats are double, string, dataframe, rdd, and list of such object. kwargs: dict of name, value pairs To know what formats are supported for name and value, look above. """ if args and len(args) != 2: raise ValueError("Expected name, value pair.") elif args: self._setInput(args[0], args[1]) for name, value in kwargs.items(): self._setInput(name, value) return self def _setInput(self, key, val): # `in` is a reserved word ("keyword") in Python, so `script_java.in(...)` is not # allowed. Therefore, we use the following code in which we retrieve a function # representing `script_java.in`, and then call it with the arguments. This is in # lieu of adding a new `input` method on the JVM side, as that would complicate use # from Scala/Java. if isinstance(val, py4j.java_gateway.JavaObject): py4j.java_gateway.get_method(self.script_java, "in")(key, val) else: py4j.java_gateway.get_method(self.script_java, "in")(key, _py2java(self.sc, val)) def output(self, *names): """ Parameters ---------- names: string, list of strings Output variables as defined inside the DML script. """ for val in names: self.script_java.out(val) return self class MLContext(object): """ Wrapper around the new SystemML MLContext. Parameters ---------- sc: SparkContext or SparkSession An instance of pyspark.SparkContext or pyspark.sql.SparkSession. """ def __init__(self, sc): if isinstance(sc, pyspark.sql.session.SparkSession): sc = sc._sc elif not isinstance(sc, SparkContext): raise ValueError("Expected sc to be a SparkContext or SparkSession, got " % str(type(sc))) self._sc = sc self._ml = createJavaObject(sc, 'mlcontext') def __repr__(self): return "MLContext" def execute(self, script): """ Execute a DML / PyDML script. Parameters ---------- script: Script instance Script instance defined with the appropriate input and output variables. Returns ------- ml_results: MLResults MLResults instance. """ if not isinstance(script, Script): raise ValueError("Expected script to be an instance of Script") scriptString = script.scriptString script_java = script.script_java return MLResults(self._ml.execute(script_java), self._sc) def setStatistics(self, statistics): """ Whether or not to output statistics (such as execution time, elapsed time) about script executions. Parameters ---------- statistics: boolean """ self._ml.setStatistics(bool(statistics)) return self def setGPU(self, enable): """ Whether or not to enable GPU. Parameters ---------- enable: boolean """ self._ml.setGPU(bool(enable)) return self def setForceGPU(self, enable): """ Whether or not to force the usage of GPU operators. Parameters ---------- enable: boolean """ self._ml.setForceGPU(bool(enable)) return self def setStatisticsMaxHeavyHitters(self, maxHeavyHitters): """ The maximum number of heavy hitters that are printed as part of the statistics. Parameters ---------- maxHeavyHitters: int """ self._ml.setStatisticsMaxHeavyHitters(maxHeavyHitters) return self def setExplain(self, explain): """ Explanation about the program. Mainly intended for developers. Parameters ---------- explain: boolean """ self._ml.setExplain(bool(explain)) return self def setExplainLevel(self, explainLevel): """ Set explain level. Parameters ---------- explainLevel: string Can be one of "hops", "runtime", "recompile_hops", "recompile_runtime" or in the above in upper case. """ self._ml.setExplainLevel(explainLevel) return self def setConfigProperty(self, propertyName, propertyValue): """ Set configuration property, such as setConfigProperty("sysml.localtmpdir", "/tmp/systemml"). Parameters ---------- propertyName: String propertyValue: String """ self._ml.setConfigProperty(propertyName, propertyValue) return self def setConfig(self, configFilePath): """ Set SystemML configuration based on a configuration file. Parameters ---------- configFilePath: String """ self._ml.setConfig(configFilePath) return self def resetConfig(self): """ Reset configuration settings to default values. """ self._ml.resetConfig() return self def version(self): """Display the project version.""" return self._ml.version() def buildTime(self): """Display the project build time.""" return self._ml.buildTime() def info(self): """Display the project information.""" return self._ml.info().toString() def isExplain(self): """Returns True if program instruction details should be output, False otherwise.""" return self._ml.isExplain() def isStatistics(self): """Returns True if program execution statistics should be output, False otherwise.""" return self._ml.isStatistics() def isGPU(self): """Returns True if GPU mode is enabled, False otherwise.""" return self._ml.isGPU() def isForceGPU(self): """Returns True if "force" GPU mode is enabled, False otherwise.""" return self._ml.isForceGPU() def close(self): """ Closes this MLContext instance to cleanup buffer pool, static/local state and scratch space. Note the SparkContext is not explicitly closed to allow external reuse. """ self._ml.close() return self
apache-2.0
saiwing-yeung/scikit-learn
examples/linear_model/plot_bayesian_ridge.py
50
2733
""" ========================= Bayesian Ridge Regression ========================= Computes a Bayesian Ridge Regression on a synthetic dataset. See :ref:`bayesian_ridge_regression` for more information on the regressor. Compared to the OLS (ordinary least squares) estimator, the coefficient weights are slightly shifted toward zeros, which stabilises them. As the prior on the weights is a Gaussian prior, the histogram of the estimated weights is Gaussian. The estimation of the model is done by iteratively maximizing the marginal log-likelihood of the observations. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from scipy import stats from sklearn.linear_model import BayesianRidge, LinearRegression ############################################################################### # Generating simulated data with Gaussian weights np.random.seed(0) n_samples, n_features = 100, 100 X = np.random.randn(n_samples, n_features) # Create Gaussian data # Create weights with a precision lambda_ of 4. lambda_ = 4. w = np.zeros(n_features) # Only keep 10 weights of interest relevant_features = np.random.randint(0, n_features, 10) for i in relevant_features: w[i] = stats.norm.rvs(loc=0, scale=1. / np.sqrt(lambda_)) # Create noise with a precision alpha of 50. alpha_ = 50. noise = stats.norm.rvs(loc=0, scale=1. / np.sqrt(alpha_), size=n_samples) # Create the target y = np.dot(X, w) + noise ############################################################################### # Fit the Bayesian Ridge Regression and an OLS for comparison clf = BayesianRidge(compute_score=True) clf.fit(X, y) ols = LinearRegression() ols.fit(X, y) ############################################################################### # Plot true weights, estimated weights and histogram of the weights lw = 2 plt.figure(figsize=(6, 5)) plt.title("Weights of the model") plt.plot(clf.coef_, color='lightgreen', linewidth=lw, label="Bayesian Ridge estimate") plt.plot(w, color='gold', linewidth=lw, label="Ground truth") plt.plot(ols.coef_, color='navy', linestyle='--', label="OLS estimate") plt.xlabel("Features") plt.ylabel("Values of the weights") plt.legend(loc="best", prop=dict(size=12)) plt.figure(figsize=(6, 5)) plt.title("Histogram of the weights") plt.hist(clf.coef_, bins=n_features, color='gold', log=True) plt.scatter(clf.coef_[relevant_features], 5 * np.ones(len(relevant_features)), color='navy', label="Relevant features") plt.ylabel("Features") plt.xlabel("Values of the weights") plt.legend(loc="upper left") plt.figure(figsize=(6, 5)) plt.title("Marginal log-likelihood") plt.plot(clf.scores_, color='navy', linewidth=lw) plt.ylabel("Score") plt.xlabel("Iterations") plt.show()
bsd-3-clause
JsNoNo/scikit-learn
sklearn/decomposition/tests/test_online_lda.py
21
13171
import numpy as np from scipy.linalg import block_diag from scipy.sparse import csr_matrix from scipy.special import psi from sklearn.decomposition import LatentDirichletAllocation from sklearn.decomposition._online_lda import (_dirichlet_expectation_1d, _dirichlet_expectation_2d) from sklearn.utils.testing import assert_allclose from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_greater_equal from sklearn.utils.testing import assert_raises_regexp from sklearn.utils.testing import if_safe_multiprocessing_with_blas from sklearn.utils.validation import NotFittedError from sklearn.externals.six.moves import xrange def _build_sparse_mtx(): # Create 3 topics and each topic has 3 disticnt words. # (Each word only belongs to a single topic.) n_topics = 3 block = n_topics * np.ones((3, 3)) blocks = [block] * n_topics X = block_diag(*blocks) X = csr_matrix(X) return (n_topics, X) def test_lda_default_prior_params(): # default prior parameter should be `1 / topics` # and verbose params should not affect result n_topics, X = _build_sparse_mtx() prior = 1. / n_topics lda_1 = LatentDirichletAllocation(n_topics=n_topics, doc_topic_prior=prior, topic_word_prior=prior, random_state=0) lda_2 = LatentDirichletAllocation(n_topics=n_topics, random_state=0) topic_distr_1 = lda_1.fit_transform(X) topic_distr_2 = lda_2.fit_transform(X) assert_almost_equal(topic_distr_1, topic_distr_2) def test_lda_fit_batch(): # Test LDA batch learning_offset (`fit` method with 'batch' learning) rng = np.random.RandomState(0) n_topics, X = _build_sparse_mtx() lda = LatentDirichletAllocation(n_topics=n_topics, evaluate_every=1, learning_method='batch', random_state=rng) lda.fit(X) correct_idx_grps = [(0, 1, 2), (3, 4, 5), (6, 7, 8)] for component in lda.components_: # Find top 3 words in each LDA component top_idx = set(component.argsort()[-3:][::-1]) assert_true(tuple(sorted(top_idx)) in correct_idx_grps) def test_lda_fit_online(): # Test LDA online learning (`fit` method with 'online' learning) rng = np.random.RandomState(0) n_topics, X = _build_sparse_mtx() lda = LatentDirichletAllocation(n_topics=n_topics, learning_offset=10., evaluate_every=1, learning_method='online', random_state=rng) lda.fit(X) correct_idx_grps = [(0, 1, 2), (3, 4, 5), (6, 7, 8)] for component in lda.components_: # Find top 3 words in each LDA component top_idx = set(component.argsort()[-3:][::-1]) assert_true(tuple(sorted(top_idx)) in correct_idx_grps) def test_lda_partial_fit(): # Test LDA online learning (`partial_fit` method) # (same as test_lda_batch) rng = np.random.RandomState(0) n_topics, X = _build_sparse_mtx() lda = LatentDirichletAllocation(n_topics=n_topics, learning_offset=10., total_samples=100, random_state=rng) for i in xrange(3): lda.partial_fit(X) correct_idx_grps = [(0, 1, 2), (3, 4, 5), (6, 7, 8)] for c in lda.components_: top_idx = set(c.argsort()[-3:][::-1]) assert_true(tuple(sorted(top_idx)) in correct_idx_grps) def test_lda_dense_input(): # Test LDA with dense input. rng = np.random.RandomState(0) n_topics, X = _build_sparse_mtx() lda = LatentDirichletAllocation(n_topics=n_topics, learning_method='batch', random_state=rng) lda.fit(X.toarray()) correct_idx_grps = [(0, 1, 2), (3, 4, 5), (6, 7, 8)] for component in lda.components_: # Find top 3 words in each LDA component top_idx = set(component.argsort()[-3:][::-1]) assert_true(tuple(sorted(top_idx)) in correct_idx_grps) def test_lda_transform(): # Test LDA transform. # Transform result cannot be negative rng = np.random.RandomState(0) X = rng.randint(5, size=(20, 10)) n_topics = 3 lda = LatentDirichletAllocation(n_topics=n_topics, random_state=rng) X_trans = lda.fit_transform(X) assert_true((X_trans > 0.0).any()) def test_lda_fit_transform(): # Test LDA fit_transform & transform # fit_transform and transform result should be the same for method in ('online', 'batch'): rng = np.random.RandomState(0) X = rng.randint(10, size=(50, 20)) lda = LatentDirichletAllocation(n_topics=5, learning_method=method, random_state=rng) X_fit = lda.fit_transform(X) X_trans = lda.transform(X) assert_array_almost_equal(X_fit, X_trans, 4) def test_lda_partial_fit_dim_mismatch(): # test `n_features` mismatch in `partial_fit` rng = np.random.RandomState(0) n_topics = rng.randint(3, 6) n_col = rng.randint(6, 10) X_1 = np.random.randint(4, size=(10, n_col)) X_2 = np.random.randint(4, size=(10, n_col + 1)) lda = LatentDirichletAllocation(n_topics=n_topics, learning_offset=5., total_samples=20, random_state=rng) lda.partial_fit(X_1) assert_raises_regexp(ValueError, r"^The provided data has", lda.partial_fit, X_2) def test_invalid_params(): # test `_check_params` method X = np.ones((5, 10)) invalid_models = ( ('n_topics', LatentDirichletAllocation(n_topics=0)), ('learning_method', LatentDirichletAllocation(learning_method='unknown')), ('total_samples', LatentDirichletAllocation(total_samples=0)), ('learning_offset', LatentDirichletAllocation(learning_offset=-1)), ) for param, model in invalid_models: regex = r"^Invalid %r parameter" % param assert_raises_regexp(ValueError, regex, model.fit, X) def test_lda_negative_input(): # test pass dense matrix with sparse negative input. X = -np.ones((5, 10)) lda = LatentDirichletAllocation() regex = r"^Negative values in data passed" assert_raises_regexp(ValueError, regex, lda.fit, X) def test_lda_no_component_error(): # test `transform` and `perplexity` before `fit` rng = np.random.RandomState(0) X = rng.randint(4, size=(20, 10)) lda = LatentDirichletAllocation() regex = r"^no 'components_' attribute" assert_raises_regexp(NotFittedError, regex, lda.transform, X) assert_raises_regexp(NotFittedError, regex, lda.perplexity, X) def test_lda_transform_mismatch(): # test `n_features` mismatch in partial_fit and transform rng = np.random.RandomState(0) X = rng.randint(4, size=(20, 10)) X_2 = rng.randint(4, size=(10, 8)) n_topics = rng.randint(3, 6) lda = LatentDirichletAllocation(n_topics=n_topics, random_state=rng) lda.partial_fit(X) assert_raises_regexp(ValueError, r"^The provided data has", lda.partial_fit, X_2) @if_safe_multiprocessing_with_blas def test_lda_multi_jobs(): n_topics, X = _build_sparse_mtx() # Test LDA batch training with multi CPU for method in ('online', 'batch'): rng = np.random.RandomState(0) lda = LatentDirichletAllocation(n_topics=n_topics, n_jobs=2, learning_method=method, random_state=rng) lda.fit(X) correct_idx_grps = [(0, 1, 2), (3, 4, 5), (6, 7, 8)] for c in lda.components_: top_idx = set(c.argsort()[-3:][::-1]) assert_true(tuple(sorted(top_idx)) in correct_idx_grps) @if_safe_multiprocessing_with_blas def test_lda_partial_fit_multi_jobs(): # Test LDA online training with multi CPU rng = np.random.RandomState(0) n_topics, X = _build_sparse_mtx() lda = LatentDirichletAllocation(n_topics=n_topics, n_jobs=2, learning_offset=5., total_samples=30, random_state=rng) for i in range(2): lda.partial_fit(X) correct_idx_grps = [(0, 1, 2), (3, 4, 5), (6, 7, 8)] for c in lda.components_: top_idx = set(c.argsort()[-3:][::-1]) assert_true(tuple(sorted(top_idx)) in correct_idx_grps) def test_lda_preplexity_mismatch(): # test dimension mismatch in `perplexity` method rng = np.random.RandomState(0) n_topics = rng.randint(3, 6) n_samples = rng.randint(6, 10) X = np.random.randint(4, size=(n_samples, 10)) lda = LatentDirichletAllocation(n_topics=n_topics, learning_offset=5., total_samples=20, random_state=rng) lda.fit(X) # invalid samples invalid_n_samples = rng.randint(4, size=(n_samples + 1, n_topics)) assert_raises_regexp(ValueError, r'Number of samples', lda.perplexity, X, invalid_n_samples) # invalid topic number invalid_n_topics = rng.randint(4, size=(n_samples, n_topics + 1)) assert_raises_regexp(ValueError, r'Number of topics', lda.perplexity, X, invalid_n_topics) def test_lda_perplexity(): # Test LDA perplexity for batch training # perplexity should be lower after each iteration n_topics, X = _build_sparse_mtx() for method in ('online', 'batch'): lda_1 = LatentDirichletAllocation(n_topics=n_topics, max_iter=1, learning_method=method, total_samples=100, random_state=0) lda_2 = LatentDirichletAllocation(n_topics=n_topics, max_iter=10, learning_method=method, total_samples=100, random_state=0) distr_1 = lda_1.fit_transform(X) perp_1 = lda_1.perplexity(X, distr_1, sub_sampling=False) distr_2 = lda_2.fit_transform(X) perp_2 = lda_2.perplexity(X, distr_2, sub_sampling=False) assert_greater_equal(perp_1, perp_2) perp_1_subsampling = lda_1.perplexity(X, distr_1, sub_sampling=True) perp_2_subsampling = lda_2.perplexity(X, distr_2, sub_sampling=True) assert_greater_equal(perp_1_subsampling, perp_2_subsampling) def test_lda_score(): # Test LDA score for batch training # score should be higher after each iteration n_topics, X = _build_sparse_mtx() for method in ('online', 'batch'): lda_1 = LatentDirichletAllocation(n_topics=n_topics, max_iter=1, learning_method=method, total_samples=100, random_state=0) lda_2 = LatentDirichletAllocation(n_topics=n_topics, max_iter=10, learning_method=method, total_samples=100, random_state=0) lda_1.fit_transform(X) score_1 = lda_1.score(X) lda_2.fit_transform(X) score_2 = lda_2.score(X) assert_greater_equal(score_2, score_1) def test_perplexity_input_format(): # Test LDA perplexity for sparse and dense input # score should be the same for both dense and sparse input n_topics, X = _build_sparse_mtx() lda = LatentDirichletAllocation(n_topics=n_topics, max_iter=1, learning_method='batch', total_samples=100, random_state=0) distr = lda.fit_transform(X) perp_1 = lda.perplexity(X) perp_2 = lda.perplexity(X, distr) perp_3 = lda.perplexity(X.toarray(), distr) assert_almost_equal(perp_1, perp_2) assert_almost_equal(perp_1, perp_3) def test_lda_score_perplexity(): # Test the relationship between LDA score and perplexity n_topics, X = _build_sparse_mtx() lda = LatentDirichletAllocation(n_topics=n_topics, max_iter=10, random_state=0) distr = lda.fit_transform(X) perplexity_1 = lda.perplexity(X, distr, sub_sampling=False) score = lda.score(X) perplexity_2 = np.exp(-1. * (score / np.sum(X.data))) assert_almost_equal(perplexity_1, perplexity_2) def test_lda_empty_docs(): """Test LDA on empty document (all-zero rows).""" Z = np.zeros((5, 4)) for X in [Z, csr_matrix(Z)]: lda = LatentDirichletAllocation(max_iter=750).fit(X) assert_almost_equal(lda.components_.sum(axis=0), np.ones(lda.components_.shape[1])) def test_dirichlet_expectation(): """Test Cython version of Dirichlet expectation calculation.""" x = np.logspace(-100, 10, 10000) expectation = np.empty_like(x) _dirichlet_expectation_1d(x, 0, expectation) assert_allclose(expectation, np.exp(psi(x) - psi(np.sum(x))), atol=1e-19) x = x.reshape(100, 100) assert_allclose(_dirichlet_expectation_2d(x), psi(x) - psi(np.sum(x, axis=1)[:, np.newaxis]), rtol=1e-11, atol=3e-9)
bsd-3-clause
yunfeilu/scikit-learn
sklearn/preprocessing/tests/test_label.py
156
17626
import numpy as np from scipy.sparse import issparse from scipy.sparse import coo_matrix from scipy.sparse import csc_matrix from scipy.sparse import csr_matrix from scipy.sparse import dok_matrix from scipy.sparse import lil_matrix from sklearn.utils.multiclass import type_of_target from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import ignore_warnings from sklearn.preprocessing.label import LabelBinarizer from sklearn.preprocessing.label import MultiLabelBinarizer from sklearn.preprocessing.label import LabelEncoder from sklearn.preprocessing.label import label_binarize from sklearn.preprocessing.label import _inverse_binarize_thresholding from sklearn.preprocessing.label import _inverse_binarize_multiclass from sklearn import datasets iris = datasets.load_iris() def toarray(a): if hasattr(a, "toarray"): a = a.toarray() return a def test_label_binarizer(): lb = LabelBinarizer() # one-class case defaults to negative label inp = ["pos", "pos", "pos", "pos"] expected = np.array([[0, 0, 0, 0]]).T got = lb.fit_transform(inp) assert_array_equal(lb.classes_, ["pos"]) assert_array_equal(expected, got) assert_array_equal(lb.inverse_transform(got), inp) # two-class case inp = ["neg", "pos", "pos", "neg"] expected = np.array([[0, 1, 1, 0]]).T got = lb.fit_transform(inp) assert_array_equal(lb.classes_, ["neg", "pos"]) assert_array_equal(expected, got) to_invert = np.array([[1, 0], [0, 1], [0, 1], [1, 0]]) assert_array_equal(lb.inverse_transform(to_invert), inp) # multi-class case inp = ["spam", "ham", "eggs", "ham", "0"] expected = np.array([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]]) got = lb.fit_transform(inp) assert_array_equal(lb.classes_, ['0', 'eggs', 'ham', 'spam']) assert_array_equal(expected, got) assert_array_equal(lb.inverse_transform(got), inp) def test_label_binarizer_unseen_labels(): lb = LabelBinarizer() expected = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) got = lb.fit_transform(['b', 'd', 'e']) assert_array_equal(expected, got) expected = np.array([[0, 0, 0], [1, 0, 0], [0, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 0]]) got = lb.transform(['a', 'b', 'c', 'd', 'e', 'f']) assert_array_equal(expected, got) def test_label_binarizer_set_label_encoding(): lb = LabelBinarizer(neg_label=-2, pos_label=0) # two-class case with pos_label=0 inp = np.array([0, 1, 1, 0]) expected = np.array([[-2, 0, 0, -2]]).T got = lb.fit_transform(inp) assert_array_equal(expected, got) assert_array_equal(lb.inverse_transform(got), inp) lb = LabelBinarizer(neg_label=-2, pos_label=2) # multi-class case inp = np.array([3, 2, 1, 2, 0]) expected = np.array([[-2, -2, -2, +2], [-2, -2, +2, -2], [-2, +2, -2, -2], [-2, -2, +2, -2], [+2, -2, -2, -2]]) got = lb.fit_transform(inp) assert_array_equal(expected, got) assert_array_equal(lb.inverse_transform(got), inp) @ignore_warnings def test_label_binarizer_errors(): # Check that invalid arguments yield ValueError one_class = np.array([0, 0, 0, 0]) lb = LabelBinarizer().fit(one_class) multi_label = [(2, 3), (0,), (0, 2)] assert_raises(ValueError, lb.transform, multi_label) lb = LabelBinarizer() assert_raises(ValueError, lb.transform, []) assert_raises(ValueError, lb.inverse_transform, []) assert_raises(ValueError, LabelBinarizer, neg_label=2, pos_label=1) assert_raises(ValueError, LabelBinarizer, neg_label=2, pos_label=2) assert_raises(ValueError, LabelBinarizer, neg_label=1, pos_label=2, sparse_output=True) # Fail on y_type assert_raises(ValueError, _inverse_binarize_thresholding, y=csr_matrix([[1, 2], [2, 1]]), output_type="foo", classes=[1, 2], threshold=0) # Sequence of seq type should raise ValueError y_seq_of_seqs = [[], [1, 2], [3], [0, 1, 3], [2]] assert_raises(ValueError, LabelBinarizer().fit_transform, y_seq_of_seqs) # Fail on the number of classes assert_raises(ValueError, _inverse_binarize_thresholding, y=csr_matrix([[1, 2], [2, 1]]), output_type="foo", classes=[1, 2, 3], threshold=0) # Fail on the dimension of 'binary' assert_raises(ValueError, _inverse_binarize_thresholding, y=np.array([[1, 2, 3], [2, 1, 3]]), output_type="binary", classes=[1, 2, 3], threshold=0) # Fail on multioutput data assert_raises(ValueError, LabelBinarizer().fit, np.array([[1, 3], [2, 1]])) assert_raises(ValueError, label_binarize, np.array([[1, 3], [2, 1]]), [1, 2, 3]) def test_label_encoder(): # Test LabelEncoder's transform and inverse_transform methods le = LabelEncoder() le.fit([1, 1, 4, 5, -1, 0]) assert_array_equal(le.classes_, [-1, 0, 1, 4, 5]) assert_array_equal(le.transform([0, 1, 4, 4, 5, -1, -1]), [1, 2, 3, 3, 4, 0, 0]) assert_array_equal(le.inverse_transform([1, 2, 3, 3, 4, 0, 0]), [0, 1, 4, 4, 5, -1, -1]) assert_raises(ValueError, le.transform, [0, 6]) def test_label_encoder_fit_transform(): # Test fit_transform le = LabelEncoder() ret = le.fit_transform([1, 1, 4, 5, -1, 0]) assert_array_equal(ret, [2, 2, 3, 4, 0, 1]) le = LabelEncoder() ret = le.fit_transform(["paris", "paris", "tokyo", "amsterdam"]) assert_array_equal(ret, [1, 1, 2, 0]) def test_label_encoder_errors(): # Check that invalid arguments yield ValueError le = LabelEncoder() assert_raises(ValueError, le.transform, []) assert_raises(ValueError, le.inverse_transform, []) # Fail on unseen labels le = LabelEncoder() le.fit([1, 2, 3, 1, -1]) assert_raises(ValueError, le.inverse_transform, [-1]) def test_sparse_output_multilabel_binarizer(): # test input as iterable of iterables inputs = [ lambda: [(2, 3), (1,), (1, 2)], lambda: (set([2, 3]), set([1]), set([1, 2])), lambda: iter([iter((2, 3)), iter((1,)), set([1, 2])]), ] indicator_mat = np.array([[0, 1, 1], [1, 0, 0], [1, 1, 0]]) inverse = inputs[0]() for sparse_output in [True, False]: for inp in inputs: # With fit_tranform mlb = MultiLabelBinarizer(sparse_output=sparse_output) got = mlb.fit_transform(inp()) assert_equal(issparse(got), sparse_output) if sparse_output: got = got.toarray() assert_array_equal(indicator_mat, got) assert_array_equal([1, 2, 3], mlb.classes_) assert_equal(mlb.inverse_transform(got), inverse) # With fit mlb = MultiLabelBinarizer(sparse_output=sparse_output) got = mlb.fit(inp()).transform(inp()) assert_equal(issparse(got), sparse_output) if sparse_output: got = got.toarray() assert_array_equal(indicator_mat, got) assert_array_equal([1, 2, 3], mlb.classes_) assert_equal(mlb.inverse_transform(got), inverse) assert_raises(ValueError, mlb.inverse_transform, csr_matrix(np.array([[0, 1, 1], [2, 0, 0], [1, 1, 0]]))) def test_multilabel_binarizer(): # test input as iterable of iterables inputs = [ lambda: [(2, 3), (1,), (1, 2)], lambda: (set([2, 3]), set([1]), set([1, 2])), lambda: iter([iter((2, 3)), iter((1,)), set([1, 2])]), ] indicator_mat = np.array([[0, 1, 1], [1, 0, 0], [1, 1, 0]]) inverse = inputs[0]() for inp in inputs: # With fit_tranform mlb = MultiLabelBinarizer() got = mlb.fit_transform(inp()) assert_array_equal(indicator_mat, got) assert_array_equal([1, 2, 3], mlb.classes_) assert_equal(mlb.inverse_transform(got), inverse) # With fit mlb = MultiLabelBinarizer() got = mlb.fit(inp()).transform(inp()) assert_array_equal(indicator_mat, got) assert_array_equal([1, 2, 3], mlb.classes_) assert_equal(mlb.inverse_transform(got), inverse) def test_multilabel_binarizer_empty_sample(): mlb = MultiLabelBinarizer() y = [[1, 2], [1], []] Y = np.array([[1, 1], [1, 0], [0, 0]]) assert_array_equal(mlb.fit_transform(y), Y) def test_multilabel_binarizer_unknown_class(): mlb = MultiLabelBinarizer() y = [[1, 2]] assert_raises(KeyError, mlb.fit(y).transform, [[0]]) mlb = MultiLabelBinarizer(classes=[1, 2]) assert_raises(KeyError, mlb.fit_transform, [[0]]) def test_multilabel_binarizer_given_classes(): inp = [(2, 3), (1,), (1, 2)] indicator_mat = np.array([[0, 1, 1], [1, 0, 0], [1, 0, 1]]) # fit_transform() mlb = MultiLabelBinarizer(classes=[1, 3, 2]) assert_array_equal(mlb.fit_transform(inp), indicator_mat) assert_array_equal(mlb.classes_, [1, 3, 2]) # fit().transform() mlb = MultiLabelBinarizer(classes=[1, 3, 2]) assert_array_equal(mlb.fit(inp).transform(inp), indicator_mat) assert_array_equal(mlb.classes_, [1, 3, 2]) # ensure works with extra class mlb = MultiLabelBinarizer(classes=[4, 1, 3, 2]) assert_array_equal(mlb.fit_transform(inp), np.hstack(([[0], [0], [0]], indicator_mat))) assert_array_equal(mlb.classes_, [4, 1, 3, 2]) # ensure fit is no-op as iterable is not consumed inp = iter(inp) mlb = MultiLabelBinarizer(classes=[1, 3, 2]) assert_array_equal(mlb.fit(inp).transform(inp), indicator_mat) def test_multilabel_binarizer_same_length_sequence(): # Ensure sequences of the same length are not interpreted as a 2-d array inp = [[1], [0], [2]] indicator_mat = np.array([[0, 1, 0], [1, 0, 0], [0, 0, 1]]) # fit_transform() mlb = MultiLabelBinarizer() assert_array_equal(mlb.fit_transform(inp), indicator_mat) assert_array_equal(mlb.inverse_transform(indicator_mat), inp) # fit().transform() mlb = MultiLabelBinarizer() assert_array_equal(mlb.fit(inp).transform(inp), indicator_mat) assert_array_equal(mlb.inverse_transform(indicator_mat), inp) def test_multilabel_binarizer_non_integer_labels(): tuple_classes = np.empty(3, dtype=object) tuple_classes[:] = [(1,), (2,), (3,)] inputs = [ ([('2', '3'), ('1',), ('1', '2')], ['1', '2', '3']), ([('b', 'c'), ('a',), ('a', 'b')], ['a', 'b', 'c']), ([((2,), (3,)), ((1,),), ((1,), (2,))], tuple_classes), ] indicator_mat = np.array([[0, 1, 1], [1, 0, 0], [1, 1, 0]]) for inp, classes in inputs: # fit_transform() mlb = MultiLabelBinarizer() assert_array_equal(mlb.fit_transform(inp), indicator_mat) assert_array_equal(mlb.classes_, classes) assert_array_equal(mlb.inverse_transform(indicator_mat), inp) # fit().transform() mlb = MultiLabelBinarizer() assert_array_equal(mlb.fit(inp).transform(inp), indicator_mat) assert_array_equal(mlb.classes_, classes) assert_array_equal(mlb.inverse_transform(indicator_mat), inp) mlb = MultiLabelBinarizer() assert_raises(TypeError, mlb.fit_transform, [({}), ({}, {'a': 'b'})]) def test_multilabel_binarizer_non_unique(): inp = [(1, 1, 1, 0)] indicator_mat = np.array([[1, 1]]) mlb = MultiLabelBinarizer() assert_array_equal(mlb.fit_transform(inp), indicator_mat) def test_multilabel_binarizer_inverse_validation(): inp = [(1, 1, 1, 0)] mlb = MultiLabelBinarizer() mlb.fit_transform(inp) # Not binary assert_raises(ValueError, mlb.inverse_transform, np.array([[1, 3]])) # The following binary cases are fine, however mlb.inverse_transform(np.array([[0, 0]])) mlb.inverse_transform(np.array([[1, 1]])) mlb.inverse_transform(np.array([[1, 0]])) # Wrong shape assert_raises(ValueError, mlb.inverse_transform, np.array([[1]])) assert_raises(ValueError, mlb.inverse_transform, np.array([[1, 1, 1]])) def test_label_binarize_with_class_order(): out = label_binarize([1, 6], classes=[1, 2, 4, 6]) expected = np.array([[1, 0, 0, 0], [0, 0, 0, 1]]) assert_array_equal(out, expected) # Modified class order out = label_binarize([1, 6], classes=[1, 6, 4, 2]) expected = np.array([[1, 0, 0, 0], [0, 1, 0, 0]]) assert_array_equal(out, expected) out = label_binarize([0, 1, 2, 3], classes=[3, 2, 0, 1]) expected = np.array([[0, 0, 1, 0], [0, 0, 0, 1], [0, 1, 0, 0], [1, 0, 0, 0]]) assert_array_equal(out, expected) def check_binarized_results(y, classes, pos_label, neg_label, expected): for sparse_output in [True, False]: if ((pos_label == 0 or neg_label != 0) and sparse_output): assert_raises(ValueError, label_binarize, y, classes, neg_label=neg_label, pos_label=pos_label, sparse_output=sparse_output) continue # check label_binarize binarized = label_binarize(y, classes, neg_label=neg_label, pos_label=pos_label, sparse_output=sparse_output) assert_array_equal(toarray(binarized), expected) assert_equal(issparse(binarized), sparse_output) # check inverse y_type = type_of_target(y) if y_type == "multiclass": inversed = _inverse_binarize_multiclass(binarized, classes=classes) else: inversed = _inverse_binarize_thresholding(binarized, output_type=y_type, classes=classes, threshold=((neg_label + pos_label) / 2.)) assert_array_equal(toarray(inversed), toarray(y)) # Check label binarizer lb = LabelBinarizer(neg_label=neg_label, pos_label=pos_label, sparse_output=sparse_output) binarized = lb.fit_transform(y) assert_array_equal(toarray(binarized), expected) assert_equal(issparse(binarized), sparse_output) inverse_output = lb.inverse_transform(binarized) assert_array_equal(toarray(inverse_output), toarray(y)) assert_equal(issparse(inverse_output), issparse(y)) def test_label_binarize_binary(): y = [0, 1, 0] classes = [0, 1] pos_label = 2 neg_label = -1 expected = np.array([[2, -1], [-1, 2], [2, -1]])[:, 1].reshape((-1, 1)) yield check_binarized_results, y, classes, pos_label, neg_label, expected # Binary case where sparse_output = True will not result in a ValueError y = [0, 1, 0] classes = [0, 1] pos_label = 3 neg_label = 0 expected = np.array([[3, 0], [0, 3], [3, 0]])[:, 1].reshape((-1, 1)) yield check_binarized_results, y, classes, pos_label, neg_label, expected def test_label_binarize_multiclass(): y = [0, 1, 2] classes = [0, 1, 2] pos_label = 2 neg_label = 0 expected = 2 * np.eye(3) yield check_binarized_results, y, classes, pos_label, neg_label, expected assert_raises(ValueError, label_binarize, y, classes, neg_label=-1, pos_label=pos_label, sparse_output=True) def test_label_binarize_multilabel(): y_ind = np.array([[0, 1, 0], [1, 1, 1], [0, 0, 0]]) classes = [0, 1, 2] pos_label = 2 neg_label = 0 expected = pos_label * y_ind y_sparse = [sparse_matrix(y_ind) for sparse_matrix in [coo_matrix, csc_matrix, csr_matrix, dok_matrix, lil_matrix]] for y in [y_ind] + y_sparse: yield (check_binarized_results, y, classes, pos_label, neg_label, expected) assert_raises(ValueError, label_binarize, y, classes, neg_label=-1, pos_label=pos_label, sparse_output=True) def test_invalid_input_label_binarize(): assert_raises(ValueError, label_binarize, [0, 2], classes=[0, 2], pos_label=0, neg_label=1) def test_inverse_binarize_multiclass(): got = _inverse_binarize_multiclass(csr_matrix([[0, 1, 0], [-1, 0, -1], [0, 0, 0]]), np.arange(3)) assert_array_equal(got, np.array([1, 1, 0]))
bsd-3-clause
ville-k/tensorflow
tensorflow/contrib/learn/python/learn/tests/dataframe/dataframe_test.py
62
3753
# 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 of the DataFrame class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.learn.python import learn from tensorflow.contrib.learn.python.learn.tests.dataframe import mocks from tensorflow.python.framework import dtypes from tensorflow.python.platform import test def setup_test_df(): """Create a dataframe populated with some test columns.""" df = learn.DataFrame() df["a"] = learn.TransformedSeries( [mocks.MockSeries("foobar", mocks.MockTensor("Tensor a", dtypes.int32))], mocks.MockTwoOutputTransform("iue", "eui", "snt"), "out1") df["b"] = learn.TransformedSeries( [mocks.MockSeries("foobar", mocks.MockTensor("Tensor b", dtypes.int32))], mocks.MockTwoOutputTransform("iue", "eui", "snt"), "out2") df["c"] = learn.TransformedSeries( [mocks.MockSeries("foobar", mocks.MockTensor("Tensor c", dtypes.int32))], mocks.MockTwoOutputTransform("iue", "eui", "snt"), "out1") return df class DataFrameTest(test.TestCase): """Test of `DataFrame`.""" def test_create(self): df = setup_test_df() self.assertEqual(df.columns(), frozenset(["a", "b", "c"])) def test_select_columns(self): df = setup_test_df() df2 = df.select_columns(["a", "c"]) self.assertEqual(df2.columns(), frozenset(["a", "c"])) def test_exclude_columns(self): df = setup_test_df() df2 = df.exclude_columns(["a", "c"]) self.assertEqual(df2.columns(), frozenset(["b"])) def test_get_item(self): df = setup_test_df() c1 = df["b"] self.assertEqual( mocks.MockTensor("Mock Tensor 2", dtypes.int32), c1.build()) def test_del_item_column(self): df = setup_test_df() self.assertEqual(3, len(df)) del df["b"] self.assertEqual(2, len(df)) self.assertEqual(df.columns(), frozenset(["a", "c"])) def test_set_item_column(self): df = setup_test_df() self.assertEqual(3, len(df)) col1 = mocks.MockSeries("QuackColumn", mocks.MockTensor("Tensor ", dtypes.int32)) df["quack"] = col1 self.assertEqual(4, len(df)) col2 = df["quack"] self.assertEqual(col1, col2) def test_set_item_column_multi(self): df = setup_test_df() self.assertEqual(3, len(df)) col1 = mocks.MockSeries("QuackColumn", []) col2 = mocks.MockSeries("MooColumn", []) df["quack", "moo"] = [col1, col2] self.assertEqual(5, len(df)) col3 = df["quack"] self.assertEqual(col1, col3) col4 = df["moo"] self.assertEqual(col2, col4) def test_set_item_pandas(self): # TODO(jamieas) pass def test_set_item_numpy(self): # TODO(jamieas) pass def test_build(self): df = setup_test_df() result = df.build() expected = { "a": mocks.MockTensor("Mock Tensor 1", dtypes.int32), "b": mocks.MockTensor("Mock Tensor 2", dtypes.int32), "c": mocks.MockTensor("Mock Tensor 1", dtypes.int32) } self.assertEqual(expected, result) if __name__ == "__main__": test.main()
apache-2.0
RedlineResearch/ardupilot
Tools/mavproxy_modules/lib/magcal_graph_ui.py
108
8248
# Copyright (C) 2016 Intel Corporation. All rights reserved. # # This file is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This file 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/>. import matplotlib.pyplot as plt from matplotlib.backends.backend_wxagg import FigureCanvas from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d.art3d import Poly3DCollection from pymavlink.mavutil import mavlink from MAVProxy.modules.lib import wx_processguard from MAVProxy.modules.lib.wx_loader import wx import geodesic_grid as grid class MagcalPanel(wx.Panel): _status_markup_strings = { mavlink.MAG_CAL_NOT_STARTED: 'Not started', mavlink.MAG_CAL_WAITING_TO_START: 'Waiting to start', mavlink.MAG_CAL_RUNNING_STEP_ONE: 'Step one', mavlink.MAG_CAL_RUNNING_STEP_TWO: 'Step two', mavlink.MAG_CAL_SUCCESS: '<span color="blue">Success</span>', mavlink.MAG_CAL_FAILED: '<span color="red">Failed</span>', } _empty_color = '#7ea6ce' _filled_color = '#4680b9' def __init__(self, *k, **kw): super(MagcalPanel, self).__init__(*k, **kw) facecolor = self.GetBackgroundColour().GetAsString(wx.C2S_HTML_SYNTAX) fig = plt.figure(facecolor=facecolor, figsize=(1,1)) self._canvas = FigureCanvas(self, wx.ID_ANY, fig) self._canvas.SetMinSize((300,300)) self._id_text = wx.StaticText(self, wx.ID_ANY) self._status_text = wx.StaticText(self, wx.ID_ANY) self._completion_pct_text = wx.StaticText(self, wx.ID_ANY) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self._id_text) sizer.Add(self._status_text) sizer.Add(self._completion_pct_text) sizer.Add(self._canvas, proportion=1, flag=wx.EXPAND) self.SetSizer(sizer) ax = fig.add_subplot(111, axis_bgcolor=facecolor, projection='3d') self.configure_plot(ax) def configure_plot(self, ax): extra = .5 lim = grid.radius + extra ax.set_xlim3d(-lim, lim) ax.set_ylim3d(-lim, lim) ax.set_zlim3d(-lim, lim) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') ax.invert_zaxis() ax.invert_xaxis() ax.set_aspect('equal') self._polygons_collection = Poly3DCollection( grid.sections_triangles, edgecolors='#386694', ) ax.add_collection3d(self._polygons_collection) def update_status_from_mavlink(self, m): status_string = self._status_markup_strings.get(m.cal_status, '???') self._status_text.SetLabelMarkup( '<b>Status:</b> %s' % status_string, ) def mavlink_magcal_report(self, m): self.update_status_from_mavlink(m) self._completion_pct_text.SetLabel('') def mavlink_magcal_progress(self, m): facecolors = [] for i, mask in enumerate(m.completion_mask): for j in range(8): section = i * 8 + j if mask & 1 << j: facecolor = self._filled_color else: facecolor = self._empty_color facecolors.append(facecolor) self._polygons_collection.set_facecolors(facecolors) self._canvas.draw() self._id_text.SetLabelMarkup( '<b>Compass id:</b> %d' % m.compass_id ) self._completion_pct_text.SetLabelMarkup( '<b>Completion:</b> %d%%' % m.completion_pct ) self.update_status_from_mavlink(m) _legend_panel = None @staticmethod def legend_panel(*k, **kw): if MagcalPanel._legend_panel: return MagcalPanel._legend_panel p = MagcalPanel._legend_panel = wx.Panel(*k, **kw) sizer = wx.BoxSizer(wx.HORIZONTAL) p.SetSizer(sizer) marker = wx.Panel(p, wx.ID_ANY, size=(10, 10)) marker.SetBackgroundColour(MagcalPanel._empty_color) sizer.Add(marker, flag=wx.ALIGN_CENTER) text = wx.StaticText(p, wx.ID_ANY) text.SetLabel('Sections not hit') sizer.Add(text, border=4, flag=wx.ALIGN_CENTER | wx.LEFT) marker = wx.Panel(p, wx.ID_ANY, size=(10, 10)) marker.SetBackgroundColour(MagcalPanel._filled_color) sizer.Add(marker, border=10, flag=wx.ALIGN_CENTER | wx.LEFT) text = wx.StaticText(p, wx.ID_ANY) text.SetLabel('Sections hit') sizer.Add(text, border=4, flag=wx.ALIGN_CENTER | wx.LEFT) return p class MagcalFrame(wx.Frame): def __init__(self, conn): super(MagcalFrame, self).__init__( None, wx.ID_ANY, title='Magcal Graph', ) self.SetMinSize((300, 300)) self._conn = conn self._main_panel = wx.ScrolledWindow(self, wx.ID_ANY) self._main_panel.SetScrollbars(1, 1, 1, 1) self._magcal_panels = {} self._sizer = wx.BoxSizer(wx.VERTICAL) self._main_panel.SetSizer(self._sizer) idle_text = wx.StaticText(self._main_panel, wx.ID_ANY) idle_text.SetLabelMarkup('<i>No calibration messages received yet...</i>') idle_text.SetForegroundColour('#444444') self._sizer.AddStretchSpacer() self._sizer.Add( idle_text, proportion=0, flag=wx.ALIGN_CENTER | wx.ALL, border=10, ) self._sizer.AddStretchSpacer() self._timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.timer_callback, self._timer) self._timer.Start(200) def add_compass(self, id): if not self._magcal_panels: self._sizer.Clear(deleteWindows=True) self._magcal_panels_sizer = wx.BoxSizer(wx.HORIZONTAL) self._sizer.Add( self._magcal_panels_sizer, proportion=1, flag=wx.EXPAND, ) legend = MagcalPanel.legend_panel(self._main_panel, wx.ID_ANY) self._sizer.Add( legend, proportion=0, flag=wx.ALIGN_CENTER, ) self._magcal_panels[id] = MagcalPanel(self._main_panel, wx.ID_ANY) self._magcal_panels_sizer.Add( self._magcal_panels[id], proportion=1, border=10, flag=wx.EXPAND | wx.ALL, ) def timer_callback(self, evt): close_requested = False mavlink_msgs = {} while self._conn.poll(): m = self._conn.recv() if isinstance(m, str) and m == 'close': close_requested = True continue if m.compass_id not in mavlink_msgs: # Keep the last two messages so that we get the last progress # if the last message is the calibration report. mavlink_msgs[m.compass_id] = [None, m] else: l = mavlink_msgs[m.compass_id] l[0] = l[1] l[1] = m if close_requested: self._timer.Stop() self.Destroy() return if not mavlink_msgs: return needs_fit = False for k in mavlink_msgs: if k not in self._magcal_panels: self.add_compass(k) needs_fit = True if needs_fit: self._sizer.Fit(self) for k, l in mavlink_msgs.items(): for m in l: if not m: continue panel = self._magcal_panels[k] if m.get_type() == 'MAG_CAL_PROGRESS': panel.mavlink_magcal_progress(m) elif m.get_type() == 'MAG_CAL_REPORT': panel.mavlink_magcal_report(m)
gpl-3.0
wind-python/windpowerlib
tests/test_power_output.py
1
10987
""" SPDX-FileCopyrightText: 2019 oemof developer group <[email protected]> SPDX-License-Identifier: MIT """ from typing import Dict import numpy as np import pandas as pd import pytest from numpy.testing import assert_allclose from pandas.util.testing import assert_series_equal from windpowerlib.power_output import ( power_coefficient_curve, power_curve, power_curve_density_correction, ) class TestPowerOutput: def setup_class(self): self.parameters: Dict = { "wind_speed": pd.Series(data=[2.0, 5.5, 7.0]), "density": pd.Series(data=[1.3, 1.3, 1.3]), "rotor_diameter": 80, "power_coefficient_curve_wind_speeds": pd.Series([4.0, 5.0, 6.0]), "power_coefficient_curve_values": pd.Series([0.3, 0.4, 0.5]), } self.parameters2: Dict = { "wind_speed": pd.Series(data=[2.0, 5.5, 7.0]), "density": pd.Series(data=[1.3, 1.3, 1.3]), "density_correction": False, "power_curve_wind_speeds": pd.Series([4.0, 5.0, 6.0]), "power_curve_values": pd.Series([300, 400, 500]), } self.power_output_exp1 = pd.Series( data=[0.0, 450.0, 0.0], name="feedin_power_plant" ) self.power_output_exp2 = pd.Series( data=[0.0, 461.00290572, 0.0], name="feedin_power_plant" ) def test_power_coefficient_curve_1(self): """ Test wind_speed as pd.Series with density and power_coefficient_curve as pd.Series and np.array """ power_output_exp = pd.Series( data=[0.0, 244615.399, 0.0], name="feedin_power_plant" ) assert_series_equal( power_coefficient_curve(**self.parameters), power_output_exp ) parameters = self.parameters parameters["density"].to_numpy() assert_series_equal( power_coefficient_curve(**parameters), power_output_exp ) parameters["power_coefficient_curve_values"] = np.array( parameters["power_coefficient_curve_values"] ) parameters["power_coefficient_curve_wind_speeds"] = np.array( parameters["power_coefficient_curve_wind_speeds"] ) assert_series_equal( power_coefficient_curve(**parameters), power_output_exp ) def test_power_coefficient_curve_output_types(self): """ Test wind_speed as np.array with density and power_coefficient_curve as np.array and pd.Series """ assert isinstance( power_coefficient_curve(**self.parameters), pd.Series ) self.parameters["wind_speed"] = np.array(self.parameters["wind_speed"]) assert isinstance( power_coefficient_curve(**self.parameters), np.ndarray ) def test_power_coefficient_curve_2(self): """TODO: Explain this test""" parameters = self.parameters power_output_exp = np.array([0.0, 244615.399, 0.0]) parameters["wind_speed"] = np.array(parameters["wind_speed"]) assert_allclose( power_coefficient_curve(**parameters), power_output_exp ) parameters["density"] = pd.Series(data=parameters["density"]) assert_allclose( power_coefficient_curve(**parameters), power_output_exp ) assert isinstance(power_coefficient_curve(**parameters), np.ndarray) parameters["power_coefficient_curve_wind_speeds"] = pd.Series( data=parameters["power_coefficient_curve_wind_speeds"] ) parameters["power_coefficient_curve_values"] = pd.Series( data=parameters["power_coefficient_curve_values"] ) assert_allclose( power_coefficient_curve(**parameters), power_output_exp ) assert isinstance(power_coefficient_curve(**parameters), np.ndarray) def test_power_curve_1(self): # Tests without density correction: # Test wind_speed as pd.Series and power_curve as pd.Series and # np.array assert_series_equal( power_curve(**self.parameters2), self.power_output_exp1 ) def test_power_curve_2(self): """TODO: Explain this test""" self.parameters2["power_curve_values"] = np.array( self.parameters2["power_curve_values"] ) self.parameters2["power_curve_wind_speeds"] = np.array( self.parameters2["power_curve_wind_speeds"] ) assert_series_equal( power_curve(**self.parameters2), self.power_output_exp1 ) def test_power_curve_3(self): """ Test wind_speed as np.array and power_curve as pd.Series and np.array """ power_output_exp = np.array(self.power_output_exp1) self.parameters2["wind_speed"] = np.array( self.parameters2["wind_speed"] ) assert_allclose(power_curve(**self.parameters2), power_output_exp) assert isinstance(power_curve(**self.parameters2), np.ndarray) def test_power_curve_4(self): """TODO: Explain this test""" self.parameters2["power_curve_wind_speeds"] = pd.Series( data=self.parameters2["power_curve_wind_speeds"] ) self.parameters2["power_curve_values"] = pd.Series( data=self.parameters2["power_curve_values"] ) assert_allclose( power_curve(**self.parameters2), self.power_output_exp1 ) assert isinstance(power_curve(**self.parameters2), np.ndarray) def test_power_curve_5(self): """ Tests with density correction: Test wind_speed as np.array with density and power_curve as pd.Series and np.array """ power_output_exp = np.array(self.power_output_exp2) self.parameters2["density_correction"] = True assert_allclose(power_curve(**self.parameters2), power_output_exp) assert isinstance(power_curve(**self.parameters2), np.ndarray) def test_power_curve_6(self): """TODO: Explain this test""" self.parameters2["density"] = np.array(self.parameters2["density"]) assert_allclose( power_curve(**self.parameters2), self.power_output_exp2 ) assert isinstance(power_curve(**self.parameters2), np.ndarray) def test_power_curve_7(self): """TODO: Explain this test""" self.parameters2["power_curve_values"] = np.array( self.parameters2["power_curve_values"] ) self.parameters2["power_curve_wind_speeds"] = np.array( self.parameters2["power_curve_wind_speeds"] ) assert_allclose( power_curve(**self.parameters2), self.power_output_exp2 ) assert isinstance(power_curve(**self.parameters2), np.ndarray) def test_power_curve_8(self): """ Test wind_speed as pd.Series with density and power_curve as np. array and pd.Series """ self.parameters2["wind_speed"] = pd.Series( data=self.parameters2["wind_speed"] ) assert_series_equal( power_curve(**self.parameters2), self.power_output_exp2 ) def test_power_curve_9(self): """TODO: Explain this test""" self.parameters2["density"] = pd.Series( data=self.parameters2["density"] ) assert_series_equal( power_curve(**self.parameters2), self.power_output_exp2 ) def test_power_curve_10(self): """TODO: Explain this test""" self.parameters2["power_curve_wind_speeds"] = pd.Series( data=self.parameters2["power_curve_wind_speeds"] ) self.parameters2["power_curve_values"] = pd.Series( data=self.parameters2["power_curve_values"] ) assert_series_equal( power_curve(**self.parameters2), self.power_output_exp2 ) def test_power_curve_density_correction(self): """TODO: Explain and split this test.""" parameters = { "wind_speed": pd.Series(data=[2.0, 5.5, 7.0]), "density": pd.Series(data=[1.3, 1.3, 1.3]), "power_curve_wind_speeds": pd.Series([4.0, 5.0, 6.0]), "power_curve_values": pd.Series([300, 400, 500]), } # Test wind_speed as pd.Series with density and power_curve as # pd.Series and np.array power_output_exp = pd.Series( data=[0.0, 461.00290572, 0.0], name="feedin_power_plant" ) assert_series_equal( power_curve_density_correction(**parameters), power_output_exp ) parameters["density"] = np.array(parameters["density"]) assert_series_equal( power_curve_density_correction(**parameters), power_output_exp ) parameters["power_curve_values"] = np.array( parameters["power_curve_values"] ) parameters["power_curve_wind_speeds"] = np.array( parameters["power_curve_wind_speeds"] ) assert_series_equal( power_curve_density_correction(**parameters), power_output_exp ) # Test wind_speed as np.array with density and power_curve as np.array # and pd.Series parameters["wind_speed"] = np.array(parameters["wind_speed"]) power_output_exp = np.array([0.0, 461.00290572, 0.0]) assert_allclose( power_curve_density_correction(**parameters), power_output_exp ) assert isinstance(power_curve(**parameters), np.ndarray) parameters["density"] = pd.Series(data=parameters["density"]) assert_allclose( power_curve_density_correction(**parameters), power_output_exp ) assert isinstance(power_curve(**parameters), np.ndarray) parameters["power_curve_wind_speeds"] = pd.Series( data=parameters["power_curve_wind_speeds"] ) parameters["power_curve_values"] = pd.Series( data=parameters["power_curve_values"] ) assert_allclose( power_curve_density_correction(**parameters), power_output_exp ) assert isinstance(power_curve(**parameters), np.ndarray) # Raise TypeError due to density is None with pytest.raises(TypeError): parameters["density"] = None power_curve_density_correction(**parameters) def test_wrong_spelling_density_correction(self): parameters = { "wind_speed": pd.Series(data=[2.0, 5.5, 7.0]), "density": pd.Series(data=[1.3, 1.3, 1.3]), "power_curve_wind_speeds": pd.Series([4.0, 5.0, 6.0]), "power_curve_values": pd.Series([300, 400, 500]), } msg = "is an invalid type. `density_correction` must be Boolean" with pytest.raises(TypeError, match=msg): parameters["density_correction"] = None power_curve(**parameters)
mit
neerajhirani/BDA_py_demos
demos_ch10/demo10_1.py
19
4102
"""Bayesian data analysis Chapter 10, demo 1 Rejection sampling example """ from __future__ import division import numpy as np from scipy import stats import matplotlib as mpl import matplotlib.pyplot as plt # edit default plot settings (colours from colorbrewer2.org) plt.rc('font', size=14) plt.rc('lines', color='#377eb8', linewidth=2, markeredgewidth=0) plt.rc('axes', color_cycle=('#377eb8','#e41a1c','#4daf4a', '#984ea3','#ff7f00','#ffff33')) plt.rc('patch', facecolor='#bfe2ff') # fake interesting distribution x = np.linspace(-3, 3, 200) r = np.array([ 1.1 , 1.3 , -0.1 , -0.7 , 0.2 , -0.4 , 0.06, -1.7 , 1.7 , 0.3 , 0.7 , 1.6 , -2.06, -0.74, 0.2 , 0.5 ]) # Estimate the density (named q, to emphesize that it does not need to be # normalized). Parameter bw_method=0.48 is used to mimic the outcome of the # kernelp function in Matlab. q = stats.gaussian_kde(r, bw_method=0.48).evaluate(x) # rejection sampling example g_mean = 0 g_std = 1.1 g = stats.norm.pdf(x, loc=g_mean, scale=g_std) # M is computed by discrete approximation M = np.max(q/g) # prescale g *= M # plot the densities plt.figure() plt.plot(x, q) plt.plot(x, g, linestyle='--') plt.fill_between(x, q) plt.legend((r'$q(\theta|y)$', r'$Mg(\theta)$')) plt.yticks(()) plt.title('Rejection sampling') plt.ylim([0, 1.1*g.max()]) # illustrate one sample r1 = -0.8 zi = np.argmin(np.abs(x-r1)) # find the closest grid point plt.plot((x[zi], x[zi]), (0, q[zi]), color='gray') plt.plot((x[zi], x[zi]), (q[zi], g[zi]), color='gray', linestyle='--') r21 = 0.3 * g[zi] r22 = 0.8 * g[zi] plt.plot(r1, r21, marker='o', color='#4daf4a', markersize=12) plt.plot(r1, r22, marker='o', color='#e41a1c', markersize=12) # add annotations plt.text(x[zi], q[zi], r'$\leftarrow \, q(\theta=r|y)$', fontsize=18) plt.text(x[zi], g[zi], r'$\leftarrow \, g(\theta=r)$', fontsize=18) plt.text(r1-0.1, r21, 'accepted', horizontalalignment='right') plt.text(r1-0.1, r22, 'rejected', horizontalalignment='right') # get nsamp samples nsamp = 200 r1 = stats.norm.rvs(size=nsamp, loc=g_mean, scale=g_std) zi = np.argmin(np.abs(x[:,None] - r1), axis=0) r2 = np.random.rand(nsamp) * g[zi] acc = r2 < q[zi] # plot the densities againg plotgrid = mpl.gridspec.GridSpec(2, 1, height_ratios=[5,1]) fig = plt.figure() ax0 = plt.subplot(plotgrid[0]) plt.plot(x, q) plt.plot(x, g, linestyle='--') plt.fill_between(x, q) plt.xticks(()) plt.yticks(()) plt.title('Rejection sampling') plt.ylim([0, 1.1*g.max()]) plt.xlim((x[0],x[-1])) # the samples plt.scatter(r1[~acc], r2[~acc], 40, color='#ff999a') plt.scatter(r1[acc], r2[acc], 40, color='#4daf4a') plt.legend((r'$q(\theta|y)$', r'$Mg(\theta)$', 'rejected', 'accepted')) # only accepted samples ax1 = plt.subplot(plotgrid[1]) plt.scatter(r1[acc], np.ones(np.count_nonzero(acc)), 40, color='#4daf4a', alpha=0.3) plt.yticks(()) plt.xlim((x[0],x[-1])) # add inter-axis lines transf = fig.transFigure.inverted() for i in range(nsamp): if acc[i] and x[0] < r1[i] and r1[i] < x[-1]: coord1 = transf.transform(ax0.transData.transform([r1[i], r2[i]])) coord2 = transf.transform(ax1.transData.transform([r1[i], 1])) fig.lines.append(mpl.lines.Line2D( (coord1[0], coord2[0]), (coord1[1], coord2[1]), transform=fig.transFigure, alpha=0.2 )) # alternative proposal distribution g = np.empty(x.shape) g[x <= -1.5] = np.linspace(q[0], np.max(q[x<=-1.5]), len(x[x<=-1.5])) g[(x > -1.5) & (x <= 0.2)] = np.linspace( np.max(q[x<=-1.5]), np.max(q[(x>-1.5) & (x<=0.2)]), len(x[(x>-1.5) & (x<=0.2)]) ) g[(x > 0.2) & (x <= 2.3)] = np.linspace( np.max(q[(x>-1.5) & (x<=0.2)]), np.max(q[x>2.3]), len(x[(x>0.2) & (x<=2.3)]) ) g[x > 2.3] = np.linspace(np.max(q[x>2.3]), q[-1], len(x[x>2.3])) M = np.max(q/g) g *= M # plot plt.figure() plt.plot(x, q) plt.plot(x, g, linestyle='--') plt.fill_between(x, q) plt.legend((r'$q(\theta|y)$', r'$Mg(\theta)$')) plt.yticks(()) plt.title('Rejection sampling - alternative proposal distribution') plt.ylim([0, 1.1*g.max()]) plt.show()
gpl-3.0
fspaolo/scikit-learn
sklearn/covariance/tests/test_graph_lasso.py
5
2321
""" Test the graph_lasso module. """ import sys import numpy as np from scipy import linalg from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_array_less from sklearn.covariance import (graph_lasso, GraphLasso, GraphLassoCV, empirical_covariance) from sklearn.datasets.samples_generator import make_sparse_spd_matrix from sklearn.externals.six.moves import StringIO from sklearn.utils import check_random_state def test_graph_lasso(random_state=0): # Sample data from a sparse multivariate normal dim = 20 n_samples = 100 random_state = check_random_state(random_state) prec = make_sparse_spd_matrix(dim, alpha=.95, random_state=random_state) cov = linalg.inv(prec) X = random_state.multivariate_normal(np.zeros(dim), cov, size=n_samples) emp_cov = empirical_covariance(X) for alpha in (.1, .01): covs = dict() for method in ('cd', 'lars'): cov_, _, costs = graph_lasso(emp_cov, alpha=.1, return_costs=True) covs[method] = cov_ costs, dual_gap = np.array(costs).T # Check that the costs always decrease assert_array_less(np.diff(costs), 0) # Check that the 2 approaches give similar results assert_array_almost_equal(covs['cd'], covs['lars']) # Smoke test the estimator model = GraphLasso(alpha=.1).fit(X) assert_array_almost_equal(model.covariance_, covs['cd']) def test_graph_lasso_cv(random_state=1): # Sample data from a sparse multivariate normal dim = 5 n_samples = 6 random_state = check_random_state(random_state) prec = make_sparse_spd_matrix(dim, alpha=.96, random_state=random_state) cov = linalg.inv(prec) X = random_state.multivariate_normal(np.zeros(dim), cov, size=n_samples) # Capture stdout, to smoke test the verbose mode orig_stdout = sys.stdout try: sys.stdout = StringIO() # We need verbose very high so that Parallel prints on stdout GraphLassoCV(verbose=100, alphas=3, tol=1e-1).fit(X) finally: sys.stdout = orig_stdout # Smoke test with specified alphas GraphLassoCV(alphas=[0.8, 0.5], tol=1e-1, n_jobs=1).fit(X)
bsd-3-clause
moutai/scikit-learn
sklearn/utils/random.py
37
10511
# Author: Hamzeh Alsalhi <[email protected]> # # License: BSD 3 clause from __future__ import division import numpy as np import scipy.sparse as sp import operator import array from sklearn.utils import check_random_state from sklearn.utils.fixes import astype from ._random import sample_without_replacement __all__ = ['sample_without_replacement', 'choice'] # This is a backport of np.random.choice from numpy 1.7 # The function can be removed when we bump the requirements to >=1.7 def choice(a, size=None, replace=True, p=None, random_state=None): """ choice(a, size=None, replace=True, p=None) Generates a random sample from a given 1-D array .. versionadded:: 1.7.0 Parameters ----------- a : 1-D array-like or int If an ndarray, a random sample is generated from its elements. If an int, the random sample is generated as if a was np.arange(n) size : int or tuple of ints, optional Output shape. Default is None, in which case a single value is returned. replace : boolean, optional Whether the sample is with or without replacement. p : 1-D array-like, optional The probabilities associated with each entry in a. If not given the sample assumes a uniform distribution over all entries in a. random_state : int, RandomState instance or None, optional (default=None) 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`. Returns -------- samples : 1-D ndarray, shape (size,) The generated random samples Raises ------- ValueError If a is an int and less than zero, if a or p are not 1-dimensional, if a is an array-like of size 0, if p is not a vector of probabilities, if a and p have different lengths, or if replace=False and the sample size is greater than the population size See Also --------- randint, shuffle, permutation Examples --------- Generate a uniform random sample from np.arange(5) of size 3: >>> np.random.choice(5, 3) # doctest: +SKIP array([0, 3, 4]) >>> #This is equivalent to np.random.randint(0,5,3) Generate a non-uniform random sample from np.arange(5) of size 3: >>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0]) # doctest: +SKIP array([3, 3, 0]) Generate a uniform random sample from np.arange(5) of size 3 without replacement: >>> np.random.choice(5, 3, replace=False) # doctest: +SKIP array([3,1,0]) >>> #This is equivalent to np.random.shuffle(np.arange(5))[:3] Generate a non-uniform random sample from np.arange(5) of size 3 without replacement: >>> np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0]) ... # doctest: +SKIP array([2, 3, 0]) Any of the above can be repeated with an arbitrary array-like instead of just integers. For instance: >>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher'] >>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3]) ... # doctest: +SKIP array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'], dtype='|S11') """ random_state = check_random_state(random_state) # Format and Verify input a = np.array(a, copy=False) if a.ndim == 0: try: # __index__ must return an integer by python rules. pop_size = operator.index(a.item()) except TypeError: raise ValueError("a must be 1-dimensional or an integer") if pop_size <= 0: raise ValueError("a must be greater than 0") elif a.ndim != 1: raise ValueError("a must be 1-dimensional") else: pop_size = a.shape[0] if pop_size is 0: raise ValueError("a must be non-empty") if None != p: p = np.array(p, dtype=np.double, ndmin=1, copy=False) if p.ndim != 1: raise ValueError("p must be 1-dimensional") if p.size != pop_size: raise ValueError("a and p must have same size") if np.any(p < 0): raise ValueError("probabilities are not non-negative") if not np.allclose(p.sum(), 1): raise ValueError("probabilities do not sum to 1") shape = size if shape is not None: size = np.prod(shape, dtype=np.intp) else: size = 1 # Actual sampling if replace: if None != p: cdf = p.cumsum() cdf /= cdf[-1] uniform_samples = random_state.random_sample(shape) idx = cdf.searchsorted(uniform_samples, side='right') # searchsorted returns a scalar idx = np.array(idx, copy=False) else: idx = random_state.randint(0, pop_size, size=shape) else: if size > pop_size: raise ValueError("Cannot take a larger sample than " "population when 'replace=False'") if None != p: if np.sum(p > 0) < size: raise ValueError("Fewer non-zero entries in p than size") n_uniq = 0 p = p.copy() found = np.zeros(shape, dtype=np.int) flat_found = found.ravel() while n_uniq < size: x = random_state.rand(size - n_uniq) if n_uniq > 0: p[flat_found[0:n_uniq]] = 0 cdf = np.cumsum(p) cdf /= cdf[-1] new = cdf.searchsorted(x, side='right') _, unique_indices = np.unique(new, return_index=True) unique_indices.sort() new = new.take(unique_indices) flat_found[n_uniq:n_uniq + new.size] = new n_uniq += new.size idx = found else: idx = random_state.permutation(pop_size)[:size] if shape is not None: idx.shape = shape if shape is None and isinstance(idx, np.ndarray): # In most cases a scalar will have been made an array idx = idx.item(0) # Use samples as indices for a if a is array-like if a.ndim == 0: return idx if shape is not None and idx.ndim == 0: # If size == () then the user requested a 0-d array as opposed to # a scalar object when size is None. However a[idx] is always a # scalar and not an array. So this makes sure the result is an # array, taking into account that np.array(item) may not work # for object arrays. res = np.empty((), dtype=a.dtype) res[()] = a[idx] return res return a[idx] def random_choice_csc(n_samples, classes, class_probability=None, random_state=None): """Generate a sparse random matrix given column class distributions Parameters ---------- n_samples : int, Number of samples to draw in each column. classes : list of size n_outputs of arrays of size (n_classes,) List of classes for each column. class_probability : list of size n_outputs of arrays of size (n_classes,) Optional (default=None). Class distribution of each column. If None the uniform distribution is assumed. random_state : int, RandomState instance or None, optional (default=None) 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`. Returns ------- random_matrix : sparse csc matrix of size (n_samples, n_outputs) """ data = array.array('i') indices = array.array('i') indptr = array.array('i', [0]) for j in range(len(classes)): classes[j] = np.asarray(classes[j]) if classes[j].dtype.kind != 'i': raise ValueError("class dtype %s is not supported" % classes[j].dtype) classes[j] = astype(classes[j], np.int64, copy=False) # use uniform distribution if no class_probability is given if class_probability is None: class_prob_j = np.empty(shape=classes[j].shape[0]) class_prob_j.fill(1 / classes[j].shape[0]) else: class_prob_j = np.asarray(class_probability[j]) if np.sum(class_prob_j) != 1.0: raise ValueError("Probability array at index {0} does not sum to " "one".format(j)) if class_prob_j.shape[0] != classes[j].shape[0]: raise ValueError("classes[{0}] (length {1}) and " "class_probability[{0}] (length {2}) have " "different length.".format(j, classes[j].shape[0], class_prob_j.shape[0])) # If 0 is not present in the classes insert it with a probability 0.0 if 0 not in classes[j]: classes[j] = np.insert(classes[j], 0, 0) class_prob_j = np.insert(class_prob_j, 0, 0.0) # If there are nonzero classes choose randomly using class_probability rng = check_random_state(random_state) if classes[j].shape[0] > 1: p_nonzero = 1 - class_prob_j[classes[j] == 0] nnz = int(n_samples * p_nonzero) ind_sample = sample_without_replacement(n_population=n_samples, n_samples=nnz, random_state=random_state) indices.extend(ind_sample) # Normalize probabilites for the nonzero elements classes_j_nonzero = classes[j] != 0 class_probability_nz = class_prob_j[classes_j_nonzero] class_probability_nz_norm = (class_probability_nz / np.sum(class_probability_nz)) classes_ind = np.searchsorted(class_probability_nz_norm.cumsum(), rng.rand(nnz)) data.extend(classes[j][classes_j_nonzero][classes_ind]) indptr.append(len(indices)) return sp.csc_matrix((data, indices, indptr), (n_samples, len(classes)), dtype=int)
bsd-3-clause
RobertABT/heightmap
build/matplotlib/examples/misc/ftface_props.py
9
3481
#!/usr/bin/env python from __future__ import print_function """ This is a demo script to show you how to use all the properties of an FT2Font object. These describe global font properties. For individual character metrices, use the Glyp object, as returned by load_char """ import matplotlib from matplotlib.ft2font import FT2Font #fname = '/usr/local/share/matplotlib/VeraIt.ttf' fname = matplotlib.get_data_path() + '/fonts/ttf/VeraIt.ttf' #fname = '/usr/local/share/matplotlib/cmr10.ttf' font = FT2Font(fname) # these constants are used to access the style_flags and face_flags FT_FACE_FLAG_SCALABLE = 1 << 0 FT_FACE_FLAG_FIXED_SIZES = 1 << 1 FT_FACE_FLAG_FIXED_WIDTH = 1 << 2 FT_FACE_FLAG_SFNT = 1 << 3 FT_FACE_FLAG_HORIZONTAL = 1 << 4 FT_FACE_FLAG_VERTICAL = 1 << 5 FT_FACE_FLAG_KERNING = 1 << 6 FT_FACE_FLAG_FAST_GLYPHS = 1 << 7 FT_FACE_FLAG_MULTIPLE_MASTERS = 1 << 8 FT_FACE_FLAG_GLYPH_NAMES = 1 << 9 FT_FACE_FLAG_EXTERNAL_STREAM = 1 << 10 FT_STYLE_FLAG_ITALIC = 1 << 0 FT_STYLE_FLAG_BOLD = 1 << 1 print('Num faces :', font.num_faces) # number of faces in file print('Num glyphs :', font.num_glyphs) # number of glyphs in the face print('Family name :', font.family_name) # face family name print('Syle name :', font.style_name) # face syle name print('PS name :', font.postscript_name) # the postscript name print('Num fixed :', font.num_fixed_sizes) # number of embedded bitmap in face # the following are only available if face.scalable if font.scalable: # the face global bounding box (xmin, ymin, xmax, ymax) print('Bbox :', font.bbox) # number of font units covered by the EM print('EM :', font.units_per_EM) # the ascender in 26.6 units print('Ascender :', font.ascender) # the descender in 26.6 units print('Descender :', font.descender) # the height in 26.6 units print('Height :', font.height) # maximum horizontal cursor advance print('Max adv width :', font.max_advance_width) # same for vertical layout print('Max adv height :', font.max_advance_height) # vertical position of the underline bar print('Underline pos :', font.underline_position) # vertical thickness of the underline print('Underline thickness :', font.underline_thickness) print('Italics :', font.style_flags & FT_STYLE_FLAG_ITALIC != 0) print('Bold :', font.style_flags & FT_STYLE_FLAG_BOLD != 0) print('Scalable :', font.style_flags & FT_FACE_FLAG_SCALABLE != 0) print('Fixed sizes :', font.style_flags & FT_FACE_FLAG_FIXED_SIZES != 0) print('Fixed width :', font.style_flags & FT_FACE_FLAG_FIXED_WIDTH != 0) print('SFNT :', font.style_flags & FT_FACE_FLAG_SFNT != 0) print('Horizontal :', font.style_flags & FT_FACE_FLAG_HORIZONTAL != 0) print('Vertical :', font.style_flags & FT_FACE_FLAG_VERTICAL != 0) print('Kerning :', font.style_flags & FT_FACE_FLAG_KERNING != 0) print('Fast glyphs :', font.style_flags & FT_FACE_FLAG_FAST_GLYPHS != 0) print('Mult. masters :', font.style_flags & FT_FACE_FLAG_MULTIPLE_MASTERS != 0) print('Glyph names :', font.style_flags & FT_FACE_FLAG_GLYPH_NAMES != 0) print(dir(font)) cmap = font.get_charmap() print(font.get_kerning)
mit
tactileentertainment/pandas-bigquery
pandas_bigquery/datasets.py
1
4080
from pandas_bigquery.exceptions import * from pandas_bigquery.gbqconnector import GbqConnector class Datasets(GbqConnector): def __init__(self, project_id, reauth=False, verbose=False, private_key=None): try: from googleapiclient.errors import HttpError except: from apiclient.errors import HttpError self.http_error = HttpError super(Datasets, self).__init__(project_id, reauth, verbose, private_key) def exists(self, dataset_id): """ Check if a dataset exists in Google BigQuery Parameters ---------- dataset_id : str Name of dataset to be verified Returns ------- boolean true if dataset exists, otherwise false """ try: self.service.datasets().get( projectId=self.project_id, datasetId=dataset_id).execute() return True except self.http_error as ex: if ex.resp.status == 404: return False else: self.process_http_error(ex) def list(self): """ Return a list of datasets in Google BigQuery Parameters ---------- Returns ------- list List of datasets under the specific project """ dataset_list = [] next_page_token = None first_query = True while first_query or next_page_token: first_query = False try: list_dataset_response = self.service.datasets().list( projectId=self.project_id, pageToken=next_page_token).execute() dataset_response = list_dataset_response.get('datasets') if dataset_response is None: dataset_response = [] next_page_token = list_dataset_response.get('nextPageToken') if dataset_response is None: dataset_response = [] for row_num, raw_row in enumerate(dataset_response): dataset_list.append( raw_row['datasetReference']['datasetId']) except self.http_error as ex: self.process_http_error(ex) return dataset_list def insert(self, dataset_id): """ Create a dataset in Google BigQuery Parameters ---------- dataset_id : str Name of dataset to be written """ if self.exists(dataset_id): raise DatasetCreationError("Dataset {0} already " "exists".format(dataset_id)) body = { 'datasetReference': { 'projectId': self.project_id, 'datasetId': dataset_id } } try: self.service.datasets().insert( projectId=self.project_id, body=body).execute() except self.http_error as ex: self.process_http_error(ex) def delete(self, dataset_id, delete_contents=False): """ Delete a dataset in Google BigQuery Parameters ---------- dataset_id : str Name of dataset to be deleted delete_contents : boolean If True, delete all the tables in the dataset. If False and the dataset contains tables, the request will fail. Default is False """ if not self.exists(dataset_id): raise NotFoundException( "Dataset {0} does not exist".format(dataset_id)) try: self.service.datasets().delete( datasetId=dataset_id, projectId=self.project_id, deleteContents=delete_contents).execute() except self.http_error as ex: # Ignore 404 error which may occur if dataset already deleted if ex.resp.status != 404: self.process_http_error(ex)
bsd-3-clause
glouppe/scikit-learn
sklearn/externals/joblib/__init__.py
23
4764
""" Joblib is a set of tools to provide **lightweight pipelining in Python**. In particular, joblib offers: 1. transparent disk-caching of the output values and lazy re-evaluation (memoize pattern) 2. easy simple parallel computing 3. logging and tracing of the execution Joblib is optimized to be **fast** and **robust** in particular on large data and has specific optimizations for `numpy` arrays. It is **BSD-licensed**. ============================== ============================================ **User documentation**: http://pythonhosted.org/joblib **Download packages**: http://pypi.python.org/pypi/joblib#downloads **Source code**: http://github.com/joblib/joblib **Report issues**: http://github.com/joblib/joblib/issues ============================== ============================================ Vision -------- The vision is to provide tools to easily achieve better performance and reproducibility when working with long running jobs. * **Avoid computing twice the same thing**: code is rerun over an over, for instance when prototyping computational-heavy jobs (as in scientific development), but hand-crafted solution to alleviate this issue is error-prone and often leads to unreproducible results * **Persist to disk transparently**: persisting in an efficient way arbitrary objects containing large data is hard. Using joblib's caching mechanism avoids hand-written persistence and implicitly links the file on disk to the execution context of the original Python object. As a result, joblib's persistence is good for resuming an application status or computational job, eg after a crash. Joblib strives to address these problems while **leaving your code and your flow control as unmodified as possible** (no framework, no new paradigms). Main features ------------------ 1) **Transparent and fast disk-caching of output value:** a memoize or make-like functionality for Python functions that works well for arbitrary Python objects, including very large numpy arrays. Separate persistence and flow-execution logic from domain logic or algorithmic code by writing the operations as a set of steps with well-defined inputs and outputs: Python functions. Joblib can save their computation to disk and rerun it only if necessary:: >>> from sklearn.externals.joblib import Memory >>> mem = Memory(cachedir='/tmp/joblib') >>> import numpy as np >>> a = np.vander(np.arange(3)).astype(np.float) >>> square = mem.cache(np.square) >>> b = square(a) # doctest: +ELLIPSIS ________________________________________________________________________________ [Memory] Calling square... square(array([[ 0., 0., 1.], [ 1., 1., 1.], [ 4., 2., 1.]])) ___________________________________________________________square - 0...s, 0.0min >>> c = square(a) >>> # The above call did not trigger an evaluation 2) **Embarrassingly parallel helper:** to make is easy to write readable parallel code and debug it quickly:: >>> from sklearn.externals.joblib import Parallel, delayed >>> from math import sqrt >>> Parallel(n_jobs=1)(delayed(sqrt)(i**2) for i in range(10)) [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] 3) **Logging/tracing:** The different functionalities will progressively acquire better logging mechanism to help track what has been ran, and capture I/O easily. In addition, Joblib will provide a few I/O primitives, to easily define define logging and display streams, and provide a way of compiling a report. We want to be able to quickly inspect what has been run. 4) **Fast compressed Persistence**: a replacement for pickle to work efficiently on Python objects containing large data ( *joblib.dump* & *joblib.load* ). .. >>> import shutil ; shutil.rmtree('/tmp/joblib/') """ # PEP0440 compatible formatted version, see: # https://www.python.org/dev/peps/pep-0440/ # # Generic release markers: # X.Y # X.Y.Z # For bugfix releases # # Admissible pre-release markers: # X.YaN # Alpha release # X.YbN # Beta release # X.YrcN # Release Candidate # X.Y # Final release # # Dev branch marker is: 'X.Y.dev' or 'X.Y.devN' where N is an integer. # 'X.Y.dev0' is the canonical version of 'X.Y.dev' # __version__ = '0.9.3' from .memory import Memory, MemorizedResult from .logger import PrintTime from .logger import Logger from .hashing import hash from .numpy_pickle import dump from .numpy_pickle import load from .parallel import Parallel from .parallel import delayed from .parallel import cpu_count
bsd-3-clause
zklaus/tomohowk
src/plot_reconstructions.py
2
7603
#!/usr/bin/python # -*- coding: utf-8 -*- import argparse import h5py from math import log10, ceil from matplotlib import cm, colors, pyplot from matplotlib.animation import FuncAnimation import numpy from tools import parse_range import warnings #This filters a bug in matplotlib. Will be fixed in version 1.5.0. warnings.filterwarnings('ignore', category=FutureWarning, message="elementwise comparison failed") def shifted_color_map(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'): ''' Function to offset the "center" of a colormap. Useful for data with a negative min and positive max and you want the middle of the colormap's dynamic range to be at zero Input ----- cmap : The matplotlib colormap to be altered start : Offset from lowest point in the colormap's range. Defaults to 0.0 (no lower ofset). Should be between 0.0 and `midpoint`. midpoint : The new center of the colormap. Defaults to 0.5 (no shift). Should be between 0.0 and 1.0. In general, this should be 1 - vmax/(vmax + abs(vmin)) For example if your data range from -15.0 to +5.0 and you want the center of the colormap at 0.0, `midpoint` should be set to 1 - 5/(5 + 15)) or 0.75 stop : Offset from highets point in the colormap's range. Defaults to 1.0 (no upper ofset). Should be between `midpoint` and 1.0. ''' cdict = { 'red': [], 'green': [], 'blue': [], 'alpha': [] } # regular index to compute the colors reg_index = numpy.linspace(start, stop, 257) # shifted index to match the data shift_index = numpy.hstack([ numpy.linspace(0.0, midpoint, 128, endpoint=False), numpy.linspace(midpoint, 1.0, 129, endpoint=True) ]) for ri, si in zip(reg_index, shift_index): r, g, b, a = cmap(ri) cdict['red'].append((si, r, r)) cdict['green'].append((si, g, g)) cdict['blue'].append((si, b, b)) cdict['alpha'].append((si, a, a)) newcmap = colors.LinearSegmentedColormap(name, cdict) pyplot.register_cmap(cmap=newcmap) return newcmap class QuadContainer(object): def __init__(self, quad): self.quad = quad self.quad.set_rasterized(True) def update_quad(self, quad): self.quad.remove() self.quad = quad self.quad.set_rasterized(True) def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("infilename", help="HDF5 file containing the reconstructions") parser.add_argument("-o", "--output", help="output basename for movie. The file will be <name>.mp4, " "along with <name>_thumb.pdf thumbnail of first frame.") parser.add_argument("-v", "--visualization", help="visualization style. The raw option shows precisely the data," "polished gives a more pleasant rendering. (default: %(default)s)", choices=["raw", "polished"], default="raw") parser.add_argument("-t", "--track", help="Plot track of central position in phase space. (default: %(default)s)", action="store_true", default=False) parser.add_argument("-s", "--scans", help="Select scans to treat. " "All data, including coordinates, will be averaged over all specified scans.", type=parse_range, required=True) parser.add_argument("--vmin", help="Sets minimal value for colorcode. " "Can be either an absolute value, or a percentage. " "If the latter, it specifies the percentile of occuring values to ignore. " "(default: %(default)s)", default=".1%") parser.add_argument("--vmax", help="Sets maximal value for colorcode. " "Can be either an absolute value, or a percentage. " "If the latter, it specifies the percentile of occuring values to ignore. " "(default: %(default)s)", default=".1%") args = parser.parse_args() return args def prepare_data(args): with h5py.File(args.infilename, "r") as h5: rg = h5["reconstructions"] no_scans = rg["Q"].shape[0] if args.scans=="all": scans = range(no_scans) else: scans = args.scans if len(scans)==1: q_mean = rg["q_mean"][scans[0]] p_mean = rg["p_mean"][scans[0]] Q_ds = rg["Q"][scans[0]] P_ds = rg["P"][scans[0]] W_ds = rg["W"][scans[0]] else: q_mean = numpy.average(rg["q_mean"][scans], axis=0) p_mean = numpy.average(rg["p_mean"][scans], axis=0) Q_ds = numpy.average(rg["Q"][scans], axis=0) P_ds = numpy.average(rg["P"][scans], axis=0) W_ds = numpy.average(rg["W"][scans], axis=0) return q_mean, p_mean, Q_ds, P_ds, W_ds def main(): args = parse_args() q_mean, p_mean, Q, P, W = prepare_data(args) no_steps = Q.shape[0] q_min = Q[:,0,0].min() q_max = Q[:,0,-1].max() p_min = P[:,0,0].min() p_max = P[:,-1,0].max() if args.vmin[-1]=="%": W_min = numpy.percentile(W[:], float(args.vmin[:-1])) else: W_min = float(args.vmin) if args.vmax[-1]=="%": W_max = numpy.percentile(W[:], 100.-float(args.vmax[:-1])) else: W_max = float(args.vmax) midpoint = 1 - W_max/(W_max + abs(W_min)) cmap = shifted_color_map(cm.coolwarm, midpoint=midpoint, name="shifted") fig = pyplot.figure() ax = fig.add_subplot(1,1,1) ax.set_xlim(q_min, q_max) ax.set_ylim(p_min, p_max) ax.set_xlabel("q") ax.set_ylabel("p") if args.visualization=="polished": shading="gouraud" else: shading="flat" quad = QuadContainer(ax.pcolormesh(Q[0], P[0], W[0], vmin=W_min, vmax=W_max, cmap=cmap, shading=shading)) ax.set_aspect("equal") if args.track: ax.set_color_cycle([cm.copper(1.*i/(no_steps-1)) for i in range(no_steps-1)]) for i in range(no_steps-1): ax.plot(q_mean[i:i+2],p_mean[i:i+2], alpha=.3) cb = fig.colorbar(quad.quad) cb.set_label("Quasiprobability Density") cb.solids.set_rasterized(True) if args.visualization=="polished": ax.set_axis_bgcolor(cb.to_rgba(0.)) no_digits = int(ceil(log10(no_steps))+1) title_string = "Wigner Function at step {:{width}}/{:{width}}" title = ax.set_title(title_string.format(0, no_steps, width=no_digits)) ax.grid(True) if args.output: fig.savefig(args.output+"_thumb.pdf") def animate(i): title.set_text(title_string.format(i, no_steps, width=no_digits)) quad.update_quad(ax.pcolormesh(Q[i], P[i], W[i], vmin=W_min, vmax=W_max, cmap=cmap, shading=shading)) ax.grid(True) return quad.quad, ani = FuncAnimation(fig, animate, no_steps, interval=100, repeat_delay=1000) if args.output: print("Saving movie to {}. This may take a couple of minutes.".format(args.output)) ani.save(args.output+".mp4", fps=10, extra_args=['-vcodec', 'libx264']) pyplot.show() if __name__ == "__main__": main()
mit
nelson-liu/scikit-learn
sklearn/utils/fixes.py
14
13240
"""Compatibility fixes for older version of python, numpy and scipy If you add content to this file, please give the version of the package at which the fixe is no longer needed. """ # Authors: Emmanuelle Gouillart <[email protected]> # Gael Varoquaux <[email protected]> # Fabian Pedregosa <[email protected]> # Lars Buitinck # # License: BSD 3 clause import warnings import sys import functools import os import errno import numpy as np import scipy.sparse as sp import scipy try: from inspect import signature except ImportError: from ..externals.funcsigs import signature def _parse_version(version_string): version = [] for x in version_string.split('.'): try: version.append(int(x)) except ValueError: # x may be of the form dev-1ea1592 version.append(x) return tuple(version) np_version = _parse_version(np.__version__) sp_version = _parse_version(scipy.__version__) try: from scipy.special import expit # SciPy >= 0.10 with np.errstate(invalid='ignore', over='ignore'): if np.isnan(expit(1000)): # SciPy < 0.14 raise ImportError("no stable expit in scipy.special") except ImportError: def expit(x, out=None): """Logistic sigmoid function, ``1 / (1 + exp(-x))``. See sklearn.utils.extmath.log_logistic for the log of this function. """ if out is None: out = np.empty(np.atleast_1d(x).shape, dtype=np.float64) out[:] = x # 1 / (1 + exp(-x)) = (1 + tanh(x / 2)) / 2 # This way of computing the logistic is both fast and stable. out *= .5 np.tanh(out, out) out += 1 out *= .5 return out.reshape(np.shape(x)) # little danse to see if np.copy has an 'order' keyword argument # Supported since numpy 1.7.0 if 'order' in signature(np.copy).parameters: def safe_copy(X): # Copy, but keep the order return np.copy(X, order='K') else: # Before an 'order' argument was introduced, numpy wouldn't muck with # the ordering safe_copy = np.copy try: if (not np.allclose(np.divide(.4, 1, casting="unsafe"), np.divide(.4, 1, casting="unsafe", dtype=np.float64)) or not np.allclose(np.divide(.4, 1), .4)): raise TypeError('Divide not working with dtype: ' 'https://github.com/numpy/numpy/issues/3484') divide = np.divide except TypeError: # Compat for old versions of np.divide that do not provide support for # the dtype args def divide(x1, x2, out=None, dtype=None): out_orig = out if out is None: out = np.asarray(x1, dtype=dtype) if out is x1: out = x1.copy() else: if out is not x1: out[:] = x1 if dtype is not None and out.dtype != dtype: out = out.astype(dtype) out /= x2 if out_orig is None and np.isscalar(x1): out = np.asscalar(out) return out try: np.array(5).astype(float, copy=False) except TypeError: # Compat where astype accepted no copy argument (numpy < 1.7.0) def astype(array, dtype, copy=True): if not copy and array.dtype == dtype: return array return array.astype(dtype) else: astype = np.ndarray.astype try: with warnings.catch_warnings(record=True): # Don't raise the numpy deprecation warnings that appear in # 1.9, but avoid Python bug due to simplefilter('ignore') warnings.simplefilter('always') sp.csr_matrix([1.0, 2.0, 3.0]).max(axis=0) except (TypeError, AttributeError): # in scipy < 14.0, sparse matrix min/max doesn't accept an `axis` argument # the following code is taken from the scipy 0.14 codebase def _minor_reduce(X, ufunc): major_index = np.flatnonzero(np.diff(X.indptr)) if X.data.size == 0 and major_index.size == 0: # Numpy < 1.8.0 don't handle empty arrays in reduceat value = np.zeros_like(X.data) else: value = ufunc.reduceat(X.data, X.indptr[major_index]) return major_index, value def _min_or_max_axis(X, axis, min_or_max): N = X.shape[axis] if N == 0: raise ValueError("zero-size array to reduction operation") M = X.shape[1 - axis] mat = X.tocsc() if axis == 0 else X.tocsr() mat.sum_duplicates() major_index, value = _minor_reduce(mat, min_or_max) not_full = np.diff(mat.indptr)[major_index] < N value[not_full] = min_or_max(value[not_full], 0) mask = value != 0 major_index = np.compress(mask, major_index) value = np.compress(mask, value) from scipy.sparse import coo_matrix if axis == 0: res = coo_matrix((value, (np.zeros(len(value)), major_index)), dtype=X.dtype, shape=(1, M)) else: res = coo_matrix((value, (major_index, np.zeros(len(value)))), dtype=X.dtype, shape=(M, 1)) return res.A.ravel() def _sparse_min_or_max(X, axis, min_or_max): if axis is None: if 0 in X.shape: raise ValueError("zero-size array to reduction operation") zero = X.dtype.type(0) if X.nnz == 0: return zero m = min_or_max.reduce(X.data.ravel()) if X.nnz != np.product(X.shape): m = min_or_max(zero, m) return m if axis < 0: axis += 2 if (axis == 0) or (axis == 1): return _min_or_max_axis(X, axis, min_or_max) else: raise ValueError("invalid axis, use 0 for rows, or 1 for columns") def sparse_min_max(X, axis): return (_sparse_min_or_max(X, axis, np.minimum), _sparse_min_or_max(X, axis, np.maximum)) else: def sparse_min_max(X, axis): return (X.min(axis=axis).toarray().ravel(), X.max(axis=axis).toarray().ravel()) try: from numpy import argpartition except ImportError: # numpy.argpartition was introduced in v 1.8.0 def argpartition(a, kth, axis=-1, kind='introselect', order=None): return np.argsort(a, axis=axis, order=order) try: from numpy import partition except ImportError: warnings.warn('Using `sort` instead of partition.' 'Upgrade numpy to 1.8 for better performace on large number' 'of clusters') def partition(a, kth, axis=-1, kind='introselect', order=None): return np.sort(a, axis=axis, order=order) if np_version < (1, 7): # Prior to 1.7.0, np.frombuffer wouldn't work for empty first arg. def frombuffer_empty(buf, dtype): if len(buf) == 0: return np.empty(0, dtype=dtype) else: return np.frombuffer(buf, dtype=dtype) else: frombuffer_empty = np.frombuffer if np_version < (1, 8): def in1d(ar1, ar2, assume_unique=False, invert=False): # Backport of numpy function in1d 1.8.1 to support numpy 1.6.2 # Ravel both arrays, behavior for the first array could be different ar1 = np.asarray(ar1).ravel() ar2 = np.asarray(ar2).ravel() # This code is significantly faster when the condition is satisfied. if len(ar2) < 10 * len(ar1) ** 0.145: if invert: mask = np.ones(len(ar1), dtype=np.bool) for a in ar2: mask &= (ar1 != a) else: mask = np.zeros(len(ar1), dtype=np.bool) for a in ar2: mask |= (ar1 == a) return mask # Otherwise use sorting if not assume_unique: ar1, rev_idx = np.unique(ar1, return_inverse=True) ar2 = np.unique(ar2) ar = np.concatenate((ar1, ar2)) # We need this to be a stable sort, so always use 'mergesort' # here. The values from the first array should always come before # the values from the second array. order = ar.argsort(kind='mergesort') sar = ar[order] if invert: bool_ar = (sar[1:] != sar[:-1]) else: bool_ar = (sar[1:] == sar[:-1]) flag = np.concatenate((bool_ar, [invert])) indx = order.argsort(kind='mergesort')[:len(ar1)] if assume_unique: return flag[indx] else: return flag[indx][rev_idx] else: from numpy import in1d if sp_version < (0, 15): # Backport fix for scikit-learn/scikit-learn#2986 / scipy/scipy#4142 from ._scipy_sparse_lsqr_backport import lsqr as sparse_lsqr else: from scipy.sparse.linalg import lsqr as sparse_lsqr def parallel_helper(obj, methodname, *args, **kwargs): """Helper to workaround Python 2 limitations of pickling instance methods""" return getattr(obj, methodname)(*args, **kwargs) if np_version < (1, 6, 2): # Allow bincount to accept empty arrays # https://github.com/numpy/numpy/commit/40f0844846a9d7665616b142407a3d74cb65a040 def bincount(x, weights=None, minlength=None): if len(x) > 0: return np.bincount(x, weights, minlength) else: if minlength is None: minlength = 0 minlength = np.asscalar(np.asarray(minlength, dtype=np.intp)) return np.zeros(minlength, dtype=np.intp) else: from numpy import bincount if 'exist_ok' in signature(os.makedirs).parameters: makedirs = os.makedirs else: def makedirs(name, mode=0o777, exist_ok=False): """makedirs(name [, mode=0o777][, exist_ok=False]) Super-mkdir; create a leaf directory and all intermediate ones. Works like mkdir, except that any intermediate path segment (not just the rightmost) will be created if it does not exist. If the target directory already exists, raise an OSError if exist_ok is False. Otherwise no exception is raised. This is recursive. """ try: os.makedirs(name, mode=mode) except OSError as e: if (not exist_ok or e.errno != errno.EEXIST or not os.path.isdir(name)): raise if np_version < (1, 8, 1): def array_equal(a1, a2): # copy-paste from numpy 1.8.1 try: a1, a2 = np.asarray(a1), np.asarray(a2) except: return False if a1.shape != a2.shape: return False return bool(np.asarray(a1 == a2).all()) else: from numpy import array_equal if sp_version < (0, 13, 0): def rankdata(a, method='average'): if method not in ('average', 'min', 'max', 'dense', 'ordinal'): raise ValueError('unknown method "{0}"'.format(method)) arr = np.ravel(np.asarray(a)) algo = 'mergesort' if method == 'ordinal' else 'quicksort' sorter = np.argsort(arr, kind=algo) inv = np.empty(sorter.size, dtype=np.intp) inv[sorter] = np.arange(sorter.size, dtype=np.intp) if method == 'ordinal': return inv + 1 arr = arr[sorter] obs = np.r_[True, arr[1:] != arr[:-1]] dense = obs.cumsum()[inv] if method == 'dense': return dense # cumulative counts of each unique value count = np.r_[np.nonzero(obs)[0], len(obs)] if method == 'max': return count[dense] if method == 'min': return count[dense - 1] + 1 # average method return .5 * (count[dense] + count[dense - 1] + 1) else: from scipy.stats import rankdata if np_version < (1, 12): class MaskedArray(np.ma.MaskedArray): # Before numpy 1.12, np.ma.MaskedArray object is not picklable # This fix is needed to make our model_selection.GridSearchCV # picklable as the ``cv_results_`` param uses MaskedArray def __getstate__(self): """Return the internal state of the masked array, for pickling purposes. """ cf = 'CF'[self.flags.fnc] data_state = super(np.ma.MaskedArray, self).__reduce__()[2] return data_state + (np.ma.getmaskarray(self).tostring(cf), self._fill_value) else: from numpy.ma import MaskedArray # noqa if 'axis' not in signature(np.linalg.norm).parameters: def norm(X, ord=None, axis=None): """ Handles the axis parameter for the norm function in old versions of numpy (useless for numpy >= 1.8). """ if axis is None or X.ndim == 1: result = np.linalg.norm(X, ord=ord) return result if axis not in (0, 1): raise NotImplementedError(""" The fix that adds axis parameter to the old numpy norm only works for 1D or 2D arrays. """) if axis == 0: X = X.T result = np.zeros(X.shape[0]) for i in range(len(result)): result[i] = np.linalg.norm(X[i], ord=ord) return result else: norm = np.linalg.norm
bsd-3-clause
0x0all/scikit-learn
sklearn/manifold/tests/test_spectral_embedding.py
26
7703
from nose.tools import assert_true from nose.tools import assert_equal from scipy.sparse import csr_matrix from scipy.sparse import csc_matrix import numpy as np from numpy.testing import assert_array_almost_equal from nose.tools import assert_raises from nose.plugins.skip import SkipTest from sklearn.manifold.spectral_embedding_ import SpectralEmbedding from sklearn.manifold.spectral_embedding_ import _graph_is_connected from sklearn.metrics.pairwise import rbf_kernel from sklearn.metrics import normalized_mutual_info_score from sklearn.cluster import KMeans from sklearn.datasets.samples_generator import make_blobs # non centered, sparse centers to check the centers = np.array([ [0.0, 5.0, 0.0, 0.0, 0.0], [0.0, 0.0, 4.0, 0.0, 0.0], [1.0, 0.0, 0.0, 5.0, 1.0], ]) n_samples = 1000 n_clusters, n_features = centers.shape S, true_labels = make_blobs(n_samples=n_samples, centers=centers, cluster_std=1., random_state=42) def _check_with_col_sign_flipping(A, B, tol=0.0): """ Check array A and B are equal with possible sign flipping on each columns""" sign = True for column_idx in range(A.shape[1]): sign = sign and ((((A[:, column_idx] - B[:, column_idx]) ** 2).mean() <= tol ** 2) or (((A[:, column_idx] + B[:, column_idx]) ** 2).mean() <= tol ** 2)) if not sign: return False return True def test_spectral_embedding_two_components(seed=36): """Test spectral embedding with two components""" random_state = np.random.RandomState(seed) n_sample = 100 affinity = np.zeros(shape=[n_sample * 2, n_sample * 2]) # first component affinity[0:n_sample, 0:n_sample] = np.abs(random_state.randn(n_sample, n_sample)) + 2 # second component affinity[n_sample::, n_sample::] = np.abs(random_state.randn(n_sample, n_sample)) + 2 # connection affinity[0, n_sample + 1] = 1 affinity[n_sample + 1, 0] = 1 affinity.flat[::2 * n_sample + 1] = 0 affinity = 0.5 * (affinity + affinity.T) true_label = np.zeros(shape=2 * n_sample) true_label[0:n_sample] = 1 se_precomp = SpectralEmbedding(n_components=1, affinity="precomputed", random_state=np.random.RandomState(seed)) embedded_coordinate = se_precomp.fit_transform(affinity) # Some numpy versions are touchy with types embedded_coordinate = \ se_precomp.fit_transform(affinity.astype(np.float32)) # thresholding on the first components using 0. label_ = np.array(embedded_coordinate.ravel() < 0, dtype="float") assert_equal(normalized_mutual_info_score(true_label, label_), 1.0) def test_spectral_embedding_precomputed_affinity(seed=36): """Test spectral embedding with precomputed kernel""" gamma = 1.0 se_precomp = SpectralEmbedding(n_components=2, affinity="precomputed", random_state=np.random.RandomState(seed)) se_rbf = SpectralEmbedding(n_components=2, affinity="rbf", gamma=gamma, random_state=np.random.RandomState(seed)) embed_precomp = se_precomp.fit_transform(rbf_kernel(S, gamma=gamma)) embed_rbf = se_rbf.fit_transform(S) assert_array_almost_equal( se_precomp.affinity_matrix_, se_rbf.affinity_matrix_) assert_true(_check_with_col_sign_flipping(embed_precomp, embed_rbf, 0.05)) def test_spectral_embedding_callable_affinity(seed=36): """Test spectral embedding with callable affinity""" gamma = 0.9 kern = rbf_kernel(S, gamma=gamma) se_callable = SpectralEmbedding(n_components=2, affinity=( lambda x: rbf_kernel(x, gamma=gamma)), gamma=gamma, random_state=np.random.RandomState(seed)) se_rbf = SpectralEmbedding(n_components=2, affinity="rbf", gamma=gamma, random_state=np.random.RandomState(seed)) embed_rbf = se_rbf.fit_transform(S) embed_callable = se_callable.fit_transform(S) assert_array_almost_equal( se_callable.affinity_matrix_, se_rbf.affinity_matrix_) assert_array_almost_equal(kern, se_rbf.affinity_matrix_) assert_true( _check_with_col_sign_flipping(embed_rbf, embed_callable, 0.05)) def test_spectral_embedding_amg_solver(seed=36): """Test spectral embedding with amg solver""" try: from pyamg import smoothed_aggregation_solver except ImportError: raise SkipTest("pyagm not available.") se_amg = SpectralEmbedding(n_components=2, affinity="nearest_neighbors", eigen_solver="amg", n_neighbors=5, random_state=np.random.RandomState(seed)) se_arpack = SpectralEmbedding(n_components=2, affinity="nearest_neighbors", eigen_solver="arpack", n_neighbors=5, random_state=np.random.RandomState(seed)) embed_amg = se_amg.fit_transform(S) embed_arpack = se_arpack.fit_transform(S) assert_true(_check_with_col_sign_flipping(embed_amg, embed_arpack, 0.05)) def test_pipeline_spectral_clustering(seed=36): """Test using pipeline to do spectral clustering""" random_state = np.random.RandomState(seed) se_rbf = SpectralEmbedding(n_components=n_clusters, affinity="rbf", random_state=random_state) se_knn = SpectralEmbedding(n_components=n_clusters, affinity="nearest_neighbors", n_neighbors=5, random_state=random_state) for se in [se_rbf, se_knn]: km = KMeans(n_clusters=n_clusters, random_state=random_state) km.fit(se.fit_transform(S)) assert_array_almost_equal( normalized_mutual_info_score( km.labels_, true_labels), 1.0, 2) def test_spectral_embedding_unknown_eigensolver(seed=36): """Test that SpectralClustering fails with an unknown eigensolver""" se = SpectralEmbedding(n_components=1, affinity="precomputed", random_state=np.random.RandomState(seed), eigen_solver="<unknown>") assert_raises(ValueError, se.fit, S) def test_spectral_embedding_unknown_affinity(seed=36): """Test that SpectralClustering fails with an unknown affinity type""" se = SpectralEmbedding(n_components=1, affinity="<unknown>", random_state=np.random.RandomState(seed)) assert_raises(ValueError, se.fit, S) def test_connectivity(seed=36): """Test that graph connectivity test works as expected""" graph = np.array([[1, 0, 0, 0, 0], [0, 1, 1, 0, 0], [0, 1, 1, 1, 0], [0, 0, 1, 1, 1], [0, 0, 0, 1, 1]]) assert_equal(_graph_is_connected(graph), False) assert_equal(_graph_is_connected(csr_matrix(graph)), False) assert_equal(_graph_is_connected(csc_matrix(graph)), False) graph = np.array([[1, 1, 0, 0, 0], [1, 1, 1, 0, 0], [0, 1, 1, 1, 0], [0, 0, 1, 1, 1], [0, 0, 0, 1, 1]]) assert_equal(_graph_is_connected(graph), True) assert_equal(_graph_is_connected(csr_matrix(graph)), True) assert_equal(_graph_is_connected(csc_matrix(graph)), True)
bsd-3-clause
ephes/scikit-learn
examples/datasets/plot_iris_dataset.py
283
1928
#!/usr/bin/python # -*- coding: utf-8 -*- """ ========================================================= The Iris Dataset ========================================================= This data sets consists of 3 different types of irises' (Setosa, Versicolour, and Virginica) petal and sepal length, stored in a 150x4 numpy.ndarray The rows being the samples and the columns being: Sepal Length, Sepal Width, Petal Length and Petal Width. The below plot uses the first two features. See `here <http://en.wikipedia.org/wiki/Iris_flower_data_set>`_ for more information on this dataset. """ print(__doc__) # Code source: Gaël Varoquaux # Modified for documentation by Jaques Grobler # License: BSD 3 clause import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn import datasets from sklearn.decomposition import PCA # import some data to play with iris = datasets.load_iris() X = iris.data[:, :2] # we only take the first two features. Y = iris.target x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 plt.figure(2, figsize=(8, 6)) plt.clf() # Plot the training points plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.xlim(x_min, x_max) plt.ylim(y_min, y_max) plt.xticks(()) plt.yticks(()) # To getter a better understanding of interaction of the dimensions # plot the first three PCA dimensions fig = plt.figure(1, figsize=(8, 6)) ax = Axes3D(fig, elev=-150, azim=110) X_reduced = PCA(n_components=3).fit_transform(iris.data) ax.scatter(X_reduced[:, 0], X_reduced[:, 1], X_reduced[:, 2], c=Y, cmap=plt.cm.Paired) ax.set_title("First three PCA directions") ax.set_xlabel("1st eigenvector") ax.w_xaxis.set_ticklabels([]) ax.set_ylabel("2nd eigenvector") ax.w_yaxis.set_ticklabels([]) ax.set_zlabel("3rd eigenvector") ax.w_zaxis.set_ticklabels([]) plt.show()
bsd-3-clause
boada/desCluster
analysis/legacy/conditional_prob.py
2
3969
import pylab as pyl from matplotlib.ticker import NullFormatter import h5py as hdf from sklearn.cross_validation import train_test_split # load the data f = hdf.File('./result_FullKnowledge.hdf5', 'r') dset = f[f.keys()[0]] truth = dset.value f.close() f = hdf.File('./result_targetedIdeal.hdf5', 'r') dset = f[f.keys()[0]] target = dset.value f.close() f = hdf.File('./surveyComplete.hdf5', 'r') dset = f[f.keys()[0]] survey = dset.value # only use the results we actually have results for mask = target['NGAL'] >=5 maskedTruth = truth[mask] maskedTarget = target[mask] maskedSurvey = survey[mask] Ngrid = 41 gridy = pyl.linspace(2.3, 3.1, Ngrid + 1) gridx = pyl.linspace(13, 15.5, Ngrid + 1) x = pyl.log10(maskedTarget['M200c']) y = pyl.log10(maskedTarget['LOSVD']) mask = (2.3 < y) & (y <3.1) y = y[mask] x = x[mask] X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2) x, y = X_train, y_train H, xbins, ybins = pyl.histogram2d(X_train, y_train, bins=[gridx, gridy]) H = H.T H /= pyl.sum(H) #------------------------------------------------------------ # plot the result fig = pyl.figure() # define axes ax_Pxy = pyl.axes((0.2, 0.34, 0.27, 0.52)) ax_Px = pyl.axes((0.2, 0.14, 0.27, 0.2)) ax_Py = pyl.axes((0.1, 0.34, 0.1, 0.52)) ax_cb = pyl.axes((0.48, 0.34, 0.01, 0.52)) ax_Px_y = [pyl.axes((0.65, 0.62, 0.32, 0.23)), pyl.axes((0.65, 0.38, 0.32, 0.23)), pyl.axes((0.65, 0.14, 0.32, 0.23))] # set axis label formatters ax_Px_y[0].xaxis.set_major_formatter(NullFormatter()) ax_Px_y[1].xaxis.set_major_formatter(NullFormatter()) ax_Pxy.xaxis.set_major_formatter(NullFormatter()) ax_Pxy.yaxis.set_major_formatter(NullFormatter()) ax_Px.yaxis.set_major_formatter(NullFormatter()) ax_Py.xaxis.set_major_formatter(NullFormatter()) # draw the joint probability pyl.axes(ax_Pxy) H *= 1000 pyl.imshow(H, interpolation='nearest', origin='lower', aspect='auto', extent=[xbins.min(), xbins.max(), ybins.min(), ybins.max()], cmap=pyl.cm.binary) cb = pyl.colorbar(cax=ax_cb) cb.set_label('$p(M_{True}, \sigma)$') pyl.text(0, 1.02, r'$\times 10^{-3}$', transform=ax_cb.transAxes) # draw p(x) distribution ax_Px.plot(xbins[1:], H.sum(0), '-k', drawstyle='steps') # draw p(y) distribution ax_Py.plot(H.sum(1), ybins[1:], '-k', drawstyle='steps') # tweak axis labels ax_Px.set_xticks([12,13,14,15,16]) #ax_Py.set_yticks([2.5,13,14,15,16]) # define axis limits ax_Pxy.set_xlim(13, 15.5) ax_Pxy.set_ylim(2.3, 3.1 ) ax_Px.set_xlim(13, 15.5) ax_Py.set_ylim(2.3, 3.1) # label axes ax_Pxy.set_xlabel('$M_{True}$') ax_Pxy.set_ylabel('$\sigma$') ax_Px.set_xlabel('$M_{True}$') ax_Px.set_ylabel('$p(M_{True})$') ax_Px.yaxis.set_label_position('right') ax_Py.set_ylabel('$\sigma$') ax_Py.set_xlabel('$p(\sigma)$') ax_Py.xaxis.set_label_position('top') # draw marginal probabilities iy = pyl.digitize(X_test[:3], xbins) colors = 'rgc' axis = ax_Pxy.axis() for i in range(len(iy)): # overplot range on joint probability ax_Pxy.axhspan(ybins[iy[i]], ybins[iy[i]+1], alpha=0.25, fc=colors[i]) Px_y = H[iy[i]] / H[iy[i]].sum() ax_Px_y[i].plot(xbins[1:], Px_y, drawstyle='steps', c=colors[i]) ind = pyl.argsort(Px_y) ax_Px_y[i].axvline(xbins[ind[-1]], label='predicted') ax_Px_y[i].axvline(X_test[i], c='r', label='true') ax_Px_y[i].yaxis.set_major_formatter(NullFormatter()) ax_Px_y[i].set_ylabel('$p(M_{True} | %.2f)$' % ybins[iy[i]]) ax_Pxy.axis(axis) pred = [] iy = pyl.digitize(y_test, ybins) for i in iy: if i > H.shape[0]: pass else: Px_y = H[i] / H[i].sum() centers = (xbins[:-1] + xbins[1:])/2. norm = pyl.sum(Px_y * pyl.diff(xbins)) mean = pyl.sum(centers * Px_y * pyl.diff(xbins))/norm pred.append(mean) ax_Px_y[2].set_xlabel('$M_{True}$') #ax_Px_y[2].set_xticks([12,13,14,15,16]) ax_Px_y[2].legend() ax_Pxy.set_title('Joint Probability') ax_Px_y[0].set_title('Conditional Probability') pyl.show()
mit
nvoron23/statsmodels
docs/sphinxext/numpy_ext/docscrape_sphinx.py
62
7703
import re, inspect, textwrap, pydoc import sphinx from docscrape import NumpyDocString, FunctionDoc, ClassDoc class SphinxDocString(NumpyDocString): def __init__(self, docstring, config={}): self.use_plots = config.get('use_plots', False) NumpyDocString.__init__(self, docstring, config=config) # string conversion routines def _str_header(self, name, symbol='`'): return ['.. rubric:: ' + name, ''] def _str_field_list(self, name): return [':' + name + ':'] def _str_indent(self, doc, indent=4): out = [] for line in doc: out += [' '*indent + line] return out def _str_signature(self): return [''] if self['Signature']: return ['``%s``' % self['Signature']] + [''] else: return [''] def _str_summary(self): return self['Summary'] + [''] def _str_extended_summary(self): return self['Extended Summary'] + [''] def _str_param_list(self, name): out = [] if self[name]: out += self._str_field_list(name) out += [''] for param,param_type,desc in self[name]: out += self._str_indent(['**%s** : %s' % (param.strip(), param_type)]) out += [''] out += self._str_indent(desc,8) out += [''] return out @property def _obj(self): if hasattr(self, '_cls'): return self._cls elif hasattr(self, '_f'): return self._f return None def _str_member_list(self, name): """ Generate a member listing, autosummary:: table where possible, and a table where not. """ out = [] if self[name]: out += ['.. rubric:: %s' % name, ''] prefix = getattr(self, '_name', '') if prefix: prefix = '~%s.' % prefix autosum = [] others = [] for param, param_type, desc in self[name]: param = param.strip() if not self._obj or hasattr(self._obj, param): autosum += [" %s%s" % (prefix, param)] else: others.append((param, param_type, desc)) if autosum: out += ['.. autosummary::', ' :toctree:', ''] out += autosum if others: maxlen_0 = max([len(x[0]) for x in others]) maxlen_1 = max([len(x[1]) for x in others]) hdr = "="*maxlen_0 + " " + "="*maxlen_1 + " " + "="*10 fmt = '%%%ds %%%ds ' % (maxlen_0, maxlen_1) n_indent = maxlen_0 + maxlen_1 + 4 out += [hdr] for param, param_type, desc in others: out += [fmt % (param.strip(), param_type)] out += self._str_indent(desc, n_indent) out += [hdr] out += [''] return out def _str_section(self, name): out = [] if self[name]: out += self._str_header(name) out += [''] content = textwrap.dedent("\n".join(self[name])).split("\n") out += content out += [''] return out def _str_see_also(self, func_role): out = [] if self['See Also']: see_also = super(SphinxDocString, self)._str_see_also(func_role) out = ['.. seealso::', ''] out += self._str_indent(see_also[2:]) return out def _str_warnings(self): out = [] if self['Warnings']: out = ['.. warning::', ''] out += self._str_indent(self['Warnings']) return out def _str_index(self): idx = self['index'] out = [] if len(idx) == 0: return out out += ['.. index:: %s' % idx.get('default','')] for section, references in idx.iteritems(): if section == 'default': continue elif section == 'refguide': out += [' single: %s' % (', '.join(references))] else: out += [' %s: %s' % (section, ','.join(references))] return out def _str_references(self): out = [] if self['References']: out += self._str_header('References') if isinstance(self['References'], str): self['References'] = [self['References']] out.extend(self['References']) out += [''] # Latex collects all references to a separate bibliography, # so we need to insert links to it if sphinx.__version__ >= "0.6": out += ['.. only:: latex',''] else: out += ['.. latexonly::',''] items = [] for line in self['References']: m = re.match(r'.. \[([a-z0-9._-]+)\]', line, re.I) if m: items.append(m.group(1)) out += [' ' + ", ".join(["[%s]_" % item for item in items]), ''] return out def _str_examples(self): examples_str = "\n".join(self['Examples']) if (self.use_plots and 'import matplotlib' in examples_str and 'plot::' not in examples_str): out = [] out += self._str_header('Examples') out += ['.. plot::', ''] out += self._str_indent(self['Examples']) out += [''] return out else: return self._str_section('Examples') def __str__(self, indent=0, func_role="obj"): out = [] out += self._str_signature() out += self._str_index() + [''] out += self._str_summary() out += self._str_extended_summary() for param_list in ('Parameters', 'Returns', 'Raises'): out += self._str_param_list(param_list) out += self._str_warnings() out += self._str_see_also(func_role) out += self._str_section('Notes') out += self._str_references() out += self._str_examples() for param_list in ('Attributes', 'Methods'): out += self._str_member_list(param_list) out = self._str_indent(out,indent) return '\n'.join(out) class SphinxFunctionDoc(SphinxDocString, FunctionDoc): def __init__(self, obj, doc=None, config={}): self.use_plots = config.get('use_plots', False) FunctionDoc.__init__(self, obj, doc=doc, config=config) class SphinxClassDoc(SphinxDocString, ClassDoc): def __init__(self, obj, doc=None, func_doc=None, config={}): self.use_plots = config.get('use_plots', False) ClassDoc.__init__(self, obj, doc=doc, func_doc=None, config=config) class SphinxObjDoc(SphinxDocString): def __init__(self, obj, doc=None, config={}): self._f = obj SphinxDocString.__init__(self, doc, config=config) def get_doc_object(obj, what=None, doc=None, config={}): if what is None: if inspect.isclass(obj): what = 'class' elif inspect.ismodule(obj): what = 'module' elif callable(obj): what = 'function' else: what = 'object' if what == 'class': return SphinxClassDoc(obj, func_doc=SphinxFunctionDoc, doc=doc, config=config) elif what in ('function', 'method'): return SphinxFunctionDoc(obj, doc=doc, config=config) else: if doc is None: doc = pydoc.getdoc(obj) return SphinxObjDoc(obj, doc, config=config)
bsd-3-clause
sgibbes/zonal_stats_app
utilities/post_processing.py
1
1991
import pandas as pd def biomass_to_mtc02(layer): layer.emissions.SUM = layer.emissions.SUM.astype(float) layer.emissions['emissions_mtc02'] = layer.emissions.SUM * 3.67 * .5 / 1000000 del layer.emissions['emissions'] return layer.emissions def value_to_tcd_year(value): remap_dict = { 1: [{'tcd': '1-10 %', 'sub': 40}], 2: [{'tcd': '11-15 %', 'sub': 80}], 3: [{'tcd': '16-20 %', 'sub': 120}], 4: [{'tcd': '21-25 %', 'sub': 160}], 5: [{'tcd': '26-30 %', 'sub': 200}], 6: [{'tcd': '31-50 %', 'sub': 240}], 7: [{'tcd': '51-75 %', 'sub': 280}], 8: [{'tcd': '76-100 %', 'sub': 320}] } # divide the coded value by interval. if its 1.175, use int to get 1 div = int(value / 40) # look up that value to get TCD tcd = remap_dict[div][0]['tcd'] # find this value which is subtraced from the coded value. 47-40 = 7. Gets the year sub = remap_dict[div][0]['sub'] year = 2000 + (value - sub) if year == 2000: year = "no loss" return tcd, year def generate_list_columns(intersect, intersect_col): columns_to_add = [] if len(intersect_col) > 0: columns_to_add.append(intersect_col) intersect_filename = intersect.split('\\')[-1] admin_dict = [{'adm0': {1: "ISO"}, 'adm1': {2: "ID_1"}, 'adm2': {3: "ID_2"}, 'adm3': {4: "ID_3"}, 'adm4': {5: "ID_4"}, 'adm5': {6: "ID_5"}}] mydict = admin_dict[0] try: # incrementally add all admin levels for whatever admin level is intersected. # example: adm2 will ad id_2, id_1, iso for key, value in mydict[intersect_filename].items(): id_num = key for key, value in mydict.items(): for i in range(0, id_num + 1): try: columns_to_add.append(mydict[key][i]) except KeyError: pass except KeyError: pass return columns_to_add
apache-2.0
gviejo/ThalamusPhysio
python/main_make_MAP_ALLEN.py
1
7282
#!/usr/bin/env python ''' File name: main_make_map.py Author: Guillaume Viejo Date created: 28/09/2017 Python Version: 3.5.2 TRying to make the mapping from the allen atlas ''' import numpy as np import pandas as pd # from matplotlib.pyplot import plot,show,draw import scipy.io from functions import * from pylab import * from sklearn.decomposition import PCA import _pickle as cPickle import sys from scipy.ndimage import gaussian_filter import os ############################################################################################################### # PARAMETERS ############################################################################################################### mouses = ['Mouse12', 'Mouse17', 'Mouse20', 'Mouse32'] nbins = 200 binsize = 5 times = np.arange(0, binsize*(nbins+1), binsize) - (nbins*binsize)/2 times2 = times space = 0.01 interval_to_cut = { 'Mouse12':[88,120], 'Mouse17':[84,123]} # 'Mouse20':[92,131], # 'Mouse32':[80,125]} ############################################################################################################### # LOADING DATA ############################################################################################################### for m in mouses: # for m in ['Mouse20']: data = cPickle.load(open("../data/maps/"+m+".pickle", 'rb')) headdir = data['headdir'] x = data['x'] y = data['y'] total = data['total'] swr = data['movies']['swr'] theta = data['movies']['theta'] theta_dens = data['theta_dens'] ############################################################################################################### # INTERPOLATE DATA ############################################################################################################### # total neuron total = total / total.max() xnew, ynew, xytotal = interpolate(total.copy(), x, y, space) filtotal = gaussian_filter(xytotal, (10, 10)) newtotal = softmax(filtotal, 10.0, 0.1) # head direction xnew, ynew, newheaddir = interpolate(headdir.copy(), x, y, space) newheaddir[newheaddir < np.percentile(newheaddir, 80)] = 0.0 # theta dens xnew, ynew, newthetadens = interpolate(theta_dens.copy(), x, y, space) # swr newswr = [] for t in range(len(times)): xnew, ynew, frame = interpolate(swr[:,:,t].copy(), x, y, space) # frame = gaussian_filter(frame, (10, 10)) newswr.append(frame) newswr = np.array(newswr) newswr = gaussian_filter(newswr, (10,10,10)) newswr = newswr - newswr.min() newswr = newswr / newswr.max() # theta phase = np.linspace(0, 2*np.pi, theta.shape[-1]) newtheta = [] for i in range(len(phase)): xnew, ynew, frame = interpolate(theta[:,:,i].copy(), x, y, space) newtheta.append(frame) newtheta = np.array(newtheta) newtheta = gaussian_filter(newtheta, (0, 0.2, 0.2)) newtheta = newtheta - newtheta.min() newtheta = newtheta / newtheta.max() thl_lines = None # # thalamus lines and shanks position to creat the mapping session nucleus if m+"_thalamus_lines.png" in os.listdir("../figures/mapping_to_align"): thl_lines = scipy.ndimage.imread("../figures/mapping_to_align/"+m+"_thalamus_lines.png").sum(2) xlines, ylines, thl_lines = interpolate(thl_lines, np.linspace(x.min(), x.max(), thl_lines.shape[1]), np.linspace(y.min(), y.max(), thl_lines.shape[0]), space*0.1) thl_lines -= thl_lines.min() thl_lines /= thl_lines.max() thl_lines[thl_lines<0.6] = np.NaN figure() imshow(thl_lines, extent = (xlines[0], xlines[-1], ylines[-1], ylines[0])) xx, yy = np.meshgrid(x, y) scatter(xx.flatten(), yy.flatten()) xticks(x, np.arange(len(x))[::-1]) yticks(y, np.arange(len(y))) savefig("../figures/mapping_to_align/"+m+"_shanks_postion.pdf") mse = np.abs(np.median(newswr, 0) - newswr).sum(1).sum(1) idx_frames = np.arange(0, len(newswr), 10)#[np.argmax(mse)-15:np.argmax(mse)+15] figure(figsize=(20,100)) col = 4 row = int(np.ceil(len(idx_frames)/col)) for i, fr in enumerate(idx_frames): subplot(row, col, i+1) frame = newswr[fr] rgbframe = get_rgb(frame.copy(), np.ones_like(newtotal), newtotal.copy(), 0.65) imshow(rgbframe, aspect = 'equal', extent = (xnew[0], xnew[-1], ynew[-1], ynew[0])) # imshow(frame, aspect = 'equal', vmin = newswr.min(), vmax = newswr.max(), extent = (xnew[0], xnew[-1], ynew[-1], ynew[0]), cmap = 'jet') if thl_lines is not None: imshow(thl_lines, aspect = 'equal', extent = (xnew[0], xnew[-1], ynew[-1], ynew[0])) contour(newheaddir, extent = (xnew[0], xnew[-1], ynew[0], ynew[-1]), cmap = 'winter') gca().set_aspect('equal') gca().set_xticks(np.arange(xnew[0], xnew[-1], 0.2)) gca().set_yticks(np.arange(ynew[0], ynew[-1], 0.2)) title("T = "+str(int(times[fr]))+" ms") savefig("../figures/mapping_to_align/"+m+"_swr_frames.pdf") idx_frames = np.arange(len(newtheta)) figure(figsize = (20,100)) col = 4 row = int(np.ceil(len(idx_frames)/col)) for i, fr in enumerate(idx_frames): subplot(row, col, i+1) frame = newtheta[fr] rgbframe = get_rgb(frame.copy(), np.ones_like(newtotal), newtotal.copy(), 0.65) imshow(rgbframe, aspect = 'equal', extent = (xnew[0], xnew[-1], ynew[-1], ynew[0])) contour(newheaddir, extent = (xnew[0], xnew[-1], ynew[0], ynew[-1]), cmap = 'winter') if thl_lines is not None: imshow(thl_lines, aspect = 'equal', extent = (xnew[0], xnew[-1], ynew[-1], ynew[0])) gca().set_aspect('equal') gca().set_xticks(np.arange(xnew[0], xnew[-1], 0.2)) gca().set_yticks(np.arange(ynew[0], ynew[-1], 0.2)) title("phi = "+str(int(phase[fr]))) savefig("../figures/mapping_to_align/"+m+"_theta_frames.pdf") figure() imshow(newthetadens, extent = (xnew[0], xnew[-1], ynew[-1], ynew[0]), cmap = 'jet') contour(newheaddir, extent = (xnew[0], xnew[-1], ynew[-1], ynew[0]), origin = 'upper', cmap = 'winter') if thl_lines is not None: imshow(thl_lines, aspect = 'equal', extent = (xnew[0], xnew[-1], ynew[-1], ynew[0])) gca().set_aspect('equal') savefig("../figures/mapping_to_align/"+m+"_hd_density.pdf") from matplotlib import animation, rc from IPython.display import HTML, Image rc('animation', html='html5') fig, axes = plt.subplots(1,1) start = 0 frame = newswr[start] rgbframe = get_rgb(frame.copy(), np.ones_like(newtotal), newtotal.copy(), 0.65) images = [axes.imshow(get_rgb(newswr[0].copy(), np.ones_like(newtotal), newtotal.copy(), 0.65), vmin = newswr.min(), vmax = newswr.max(), aspect = 'equal', origin = 'upper', extent = (xnew[0], xnew[-1], ynew[-1], ynew[0]))] if thl_lines is not None: axes.imshow(thl_lines, aspect = 'equal', origin = 'upper', extent = (xlines[0], xlines[-1], ylines[-1], ylines[0])) def init(): images[0].set_data(get_rgb(frame.copy(), np.ones_like(newtotal), newtotal.copy(), 0.65)) return images def animate(t): frame = newswr[t] rgbframe = get_rgb(frame.copy(), np.ones_like(newtotal), newtotal.copy(), 0.65) images[0].set_data(rgbframe) images[0].axes.set_title("time = "+str(times[t])) return images anim = animation.FuncAnimation(fig, animate, init_func=init, frames=range(start,len(newswr)), interval=10, blit=False, repeat_delay = 1000) anim.save('../figures/mapping_to_align/swr_mod_'+m+'.gif', writer='imagemagick', fps=15)
gpl-3.0
widdowquinn/SI_Holmes_etal_2017
multiplexing/multiplex_data.py
1
6579
#!/usr/bin/env python3.5 # # multiplex_data.py # # Script to take input datasets for the Holmes et al. paper, and split them # into several test and training sets for cross-validation, writing the # datasets to several subdirectories. # # (C) The James Hutton Institute 2016 # Author: Leighton Pritchard """ multiplex_data.py A script to multiplex input data for Stan models into several training and test sets. """ import logging import logging.handlers import os import random import sys import time from argparse import ArgumentParser import pandas as pd class MultiplexException(Exception): """Exception raised when script fails""" def __init__(self, message): super().__init__(message) # Parse command-line def parse_cmdline(): """ Parse command-line arguments """ parser = ArgumentParser(prog=__file__) parser.add_argument("-o", "--outdir", dest="outdirname", action="store", default='multiplexed_data', type=str, help="Parent directory for output subfolders") parser.add_argument("-k", dest="kfold", action="store", default=10, type=int, help="Number of test/training datasets to create") parser.add_argument("-d", "--data", dest="datafile", action="store", default=None, type=str, help="Path to input data in tab-separated format") parser.add_argument("-l", "--logfile", dest="logfile", action="store", default=None, type=str, help="Logfile location") parser.add_argument("-v", "--verbose", dest="verbose", action="store_true", help="Give verbose output") parser.add_argument("--seed", dest="seedval", action="store", default=None, type=int, help="Seed random values for testing") return parser.parse_args() # Set up logger def logger_setup(logfilename=None, verbose=False): """Return logger for script""" logger = logging.getLogger(__file__) logger.setLevel(logging.DEBUG) # Add handler for STDERR err_handler = logging.StreamHandler(sys.stderr) logger.addHandler(err_handler) err_formatter = logging.Formatter('%(levelname)s: %(message)s') err_handler.setFormatter(err_formatter) # Add logfile handler if logfilename: try: logstream = open(logfilename, 'w') err_handler_file = logging.StreamHandler(logstream) err_handler_file.setFormatter(err_formatter) err_handler_file.setLevel(logging.INFO) logger.addHandler(err_handler_file) except: msg = "Could not open {0} for logging".format(logfilename) logger.error(msg) raise MultiplexException(msg) # Set loglevel if verbose: err_handler.setLevel(logging.INFO) else: err_handler.setLevel(logging.WARNING) return logger def load_data(filename): """Return input data and unique locus tags. Assumes that data is tab-separated. """ data = pd.read_csv(filename, sep="\t") return (data, data['locus_tag'].unique()) def chunks(iterable, chunksize): """Return the passed iterable in chunks of given size""" for idx in range(0, len(iterable), chunksize): yield iterable[idx:idx + chunksize] def split_and_write_data(dataset, kfold, outdir, seedval): """Write k-fold CV datasets to subdirectories We insist that the parent directory is created anew, to avoid problems with overwriting some, but not all, previous k-fold CV datasets. """ os.makedirs(outdir, exist_ok=False) # seed the PRNG? if seedval: random.seed(seedval) # Shuffle dataset indices and calculate k-fold step size indices = list(dataset.index) random.shuffle(indices) step = int(len(dataset)/kfold) # Shuffled index chunks of size step are the holdout sets. holdouts = chunks(indices, step) # for idx, test_indices in enumerate(holdouts): mplexdir = os.path.join(outdir, "multiplex{:05d}".format(idx)) os.makedirs(mplexdir, exist_ok=False) dataset.iloc[test_indices].to_csv(os.path.join(mplexdir, "test.tab"), sep="\t", index=False) dataset.drop(test_indices).to_csv(os.path.join(mplexdir, "train.tab"), sep="\t", index=False) # Main method for script def main(): """Main function for script.""" args = parse_cmdline() # Set up logger logger = logger_setup(args.logfile, args.verbose) logger.info('# %s logfile', __file__) logger.info('# %s', time.asctime()) logger.info(args) # Load input data try: logger.info("Loading data file %s", args.datafile) data, tag_ids = load_data(args.datafile) ntags = len(tag_ids) logger.info("Loaded data from %s", args.datafile) logger.info("Data shape: %d x %d", *data.shape) logger.info("Data contains %d unique locus tags", ntags) logger.info("Data headers: %s", list(data.columns)) except: msg = "Could not load data file {0}".format(args.datafile) logger.error(msg) raise MultiplexException(msg) # Split data into k subsets, writing each to its own subdirectory if args.kfold < 2 or args.kfold > data.shape[0]: msg = "Value of k not valid (got %d, should be in range [2,%d])" logger.error(msg, args.kfold, data.shape[0]) raise MultiplexException(msg % (args.kfold, data.shape[0])) try: logger.info("Writing %d k-fold CV datasets to subdirectories", args.kfold) logger.info("Main subdirectory: %s", args.outdirname) split_and_write_data(data, args.kfold, args.outdirname, args.seedval) logger.info("New CV data subdirectories:") logger.info("%s", args.outdirname) for dirname in os.listdir(args.outdirname): logger.info("\t|-%s", dirname) for fname in os.listdir(os.path.join(args.outdirname, dirname)): logger.info("\t|\t|-%s", fname) logger.info("\t|") except: msg = "Writing CV datasets failed (exiting)" logger.error(msg) raise MultiplexException(msg) logger.info("Exiting cleanly %s", time.asctime()) # SCRIPT if __name__ == '__main__': main()
mit
wright-group/WrightTools
examples/join.py
1
1385
""" Join ===== Some examples of how joining works. """ import numpy as np from matplotlib import pyplot as plt import WrightTools as wt a = wt.data.Data(name="a") b = wt.data.Data(name="b") a.create_variable("x", np.linspace(0, 10, 51)[:, None]) b.create_variable("x", np.linspace(5, 15, 51)[:, None]) a.create_variable("y", np.linspace(0, 10, 51)[None, :]) b.create_variable("y", np.linspace(0, 10, 51)[None, :]) a.create_channel("z", np.sin(a.x[:]) * np.cos(a.y[:]) + 1) b.create_channel("z", 5 * np.exp(-((b.x[:] - 10) ** 2)) * np.exp(-((b.y[:] - 5) ** 2)) + 1) a.transform("x", "y") b.transform("x", "y") first = wt.data.join([a, b], name="first") last = wt.data.join([a, b], method="last", name="last") min = wt.data.join([a, b], method="min", name="min") max = wt.data.join([a, b], method="max", name="max") sum = wt.data.join([a, b], method="sum", name="sum") mean = wt.data.join([a, b], method="mean", name="mean") # Plot the splits in columns fig, gs = wt.artists.create_figure(nrows=4, cols=[1, 1]) for i, da in enumerate([a, b, first, last, min, max, sum, mean]): ax = plt.subplot(gs[i]) ax.pcolor(da, vmin=0, vmax=6) wt.artists.corner_text(da.natural_name, ax=ax) ax.set_xlim(first.axes[0].min(), first.axes[0].max()) ax.set_ylim(first.axes[1].min(), first.axes[1].max()) wt.artists.set_fig_labels(xlabel=a.axes[0].label, ylabel=a.axes[1].label)
mit
sanguinariojoe/aquagpusph
examples/2D/spheric_testcase10_waveimpact/cMake/plot_t.py
14
5704
#****************************************************************************** # * # * ** * * * * * # * * * * * * * * * * # ***** * * * * ***** ** *** * * ** *** *** * # * * * * * * * * * * * * * * * * * * * * # * * * * * * * * * * * * * * * * * * * * # * * ** * ** * * *** *** *** ** *** * * * # * * * * # ** * * * # * #****************************************************************************** # * # This file is part of AQUAgpusph, a free CFD program based on SPH. * # Copyright (C) 2012 Jose Luis Cercos Pita <[email protected]> * # * # AQUAgpusph is free software: you can redistribute it and/or modify * # it under the terms of the GNU General Public License as published by * # the Free Software Foundation, either version 3 of the License, or * # (at your option) any later version. * # * # AQUAgpusph 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 AQUAgpusph. If not, see <http://www.gnu.org/licenses/>. * # * #****************************************************************************** import math import os from os import path import matplotlib.pyplot as plt import matplotlib.animation as animation def readFile(filepath): """ Read and extract data from a file :param filepath File ot read """ abspath = filepath if not path.isabs(filepath): abspath = path.join(path.dirname(path.abspath(__file__)), filepath) # Read the file by lines f = open(abspath, "r") lines = f.readlines() f.close() data = [] for l in lines[1:-1]: # Skip the last line, which may be unready l = l.strip() while l.find(' ') != -1: l = l.replace(' ', ' ') fields = l.split(' ') try: data.append(map(float, fields)) except: continue # Transpose the data return [list(d) for d in zip(*data)] fig = plt.figure() ax = fig.add_subplot(111) t = [0.0] e = [0.0] fove = ax.fill_between(t, 0, e, facecolor='red', linewidth=0.0) fave = ax.fill_between(t, 0, e, facecolor='blue', linestyle="-", linewidth=0.0) love, = ax.plot(t, e, color='#990000', linestyle="-", linewidth=2.0, label='Average overhead') lave, = ax.plot(t, e, color='#000099', linestyle="-", linewidth=2.0, label='Average elapsed') line, = ax.plot(t, e, color="black", linestyle="-", linewidth=1.0, alpha=0.5, label='Elapsed') def update(frame_index): plt.tight_layout() data = readFile('Performance.dat') t = data[0] e = data[1] e_ela = data[2] e_ove = data[5] # Clear nan values for i in range(len(e_ela)): if math.isnan(e_ela[i]): e_ela[i] = 0.0 if math.isnan(e_ove[i]): e_ove[i] = 0.0 e_ave = [e_ela[i] - e_ove[i] for i in range(len(e_ela))] # clear the fills for coll in (ax.collections): ax.collections.remove(coll) fove = ax.fill_between(t, 0, e_ela, facecolor='red', linestyle="-", linewidth=2.0) fave = ax.fill_between(t, 0, e_ave, facecolor='blue', linestyle="-", linewidth=2.0) love.set_data(t, e_ela) lave.set_data(t, e_ave) line.set_data(t, e) ax.set_xlim(0, t[-1]) ax.set_ylim(0, 1.5 * e_ela[-1]) # Set some options ax.grid() ax.set_xlim(0, 0.1) ax.set_ylim(-0.1, 0.1) ax.set_autoscale_on(False) ax.set_xlabel(r"$t \, [\mathrm{s}]$", fontsize=21) ax.set_ylabel(r"$t_{CPU} \, [\mathrm{s}]$", fontsize=21) ax.legend(handles=[lave, love, line], loc='upper right') ani = animation.FuncAnimation(fig, update, interval=5000) plt.show()
gpl-3.0
EtiCui/Msc-UdeS
dataAnalysis/dihedral_histogram.py
1
5762
#!/usr/bin/python """ These function will read LAMMPS output (dihedral.#step.out) of the dihedral angles (column1:#, column2:angle value), to plot an histogram of the angle's frequencies. Works in parallel with mpi4py, altough it's very fast without parallelisation. Usage: #change first and last desired step in the script python dihedral_histogram.py Requirement: python2.7 numpy matplotlib mpi4py pandas TODO Read a trajectory from a single file """ import numpy as np import matplotlib.pyplot as plt from mpi4py import MPI from glob import glob import pandas as pd rank = MPI.COMM_WORLD.Get_rank() nprocs = MPI.COMM_WORLD.Get_size() #first desired step first=-50 #last desired step last=-1 def open_dihedral_file(fname): """Function to load a dihedral output from lammps (name: dihedral.STEP.out). Args: ---- fname(string): filename of the output (ex:dihedral.timestep.out) The output must countains the second column as the dihedral angle Returns: ---- dihedral_data(array): an array of all the dihedral angle """ f = open(fname, "r") get_atoms = False dihedral_data = [] for line in f: if line.startswith("ITEM: ENTRIES"): get_atoms = True line = next(f) # get the index and dihedral if get_atoms == True: number, dihedral_angle = (int(line.split()[0]), float(line.split()[1])) dihedral_data.append(dihedral_angle) #only returns the angle return dihedral_data def get_histogram_dihedral(fname=None,dihedral_data=None,histogram_bins=np.arange(-180,181)): """ This function creates a numpy array with the frequencies of occurence for each angle Args: ---- fname(string): filename (optional) dihedral_data(array): array of all the dihedral angles (optional if fname is given) histogram_bins(array): bins for the histogram(default -180 to 180 with increment of 1) Returns: ---- histogram_bins(array):bins used for the histogram_bins dihedral_histogram(array): Occurence of each angle """ if dihedral_data == None: dihedral_data = open_dihedral_file(fname) #create a histogram for the dihedral angle dihedral_histogram,bins = np.histogram(dihedral_data,histogram_bins) return histogram_bins[:-1],dihedral_histogram def open_multiple_dihedral_file(): """ This function will open a trajecteory in parallel to create a global histogram Returns: ---- For rank 0 only (None for other ranks) dihedral_df(dataframe): a dataframe with the bins as index and the angle frequencies as the column trans_ratio(float) : trans dihedral ratio gauche_ratio(float): gauche dihedral ratio gauche_minus_ratio(float): gauche minus ratio output_dihedral.out(file): The first column is the bins and the second the frequencies """ rank = MPI.COMM_WORLD.Get_rank() nprocs = MPI.COMM_WORLD.Get_size() # create a list of all the dihedrals filename complete_dihedral = glob("dihedral*") # sort the list complete_dihedral.sort(key=lambda f: int(filter(str.isdigit, f))) # consider only the desired file last5ns_dihedral = complete_dihedral[first:last] fragment_dihedral = np.array_split(last5ns_dihedral, nprocs) for dihedral_files in np.nditer(fragment_dihedral[rank][:], flags=['external_loop']): dihedral_histogram_rank = np.zeros(shape=(1),dtype=np.int) intrachain_histogram_rank = np.zeros(shape=(1),dtype=np.int) for dihedral_file in dihedral_files: histogram_bins,dihedral_histogram = get_histogram_dihedral(dihedral_file) #reshape the array to have the same size if len(dihedral_histogram_rank) < len(dihedral_histogram): dihedral_histogram_rank.resize(dihedral_histogram.shape) dihedral_histogram_rank = dihedral_histogram_rank + dihedral_histogram #the first processor will gather all the arays MPI.COMM_WORLD.barrier() intrachain_histogram_total = np.zeros(intrachain_histogram_rank.shape,dtype=np.int) dihedral_histogram_total = np.zeros(dihedral_histogram_rank.shape,dtype=np.int) MPI.COMM_WORLD.Reduce(intrachain_histogram_rank,intrachain_histogram_total,op = MPI.SUM,root = 0) MPI.COMM_WORLD.Reduce(dihedral_histogram_rank,dihedral_histogram_total,op = MPI.SUM,root = 0) #The first rank calculate the ratios and the output if rank == 0: dihedral_df = pd.DataFrame({"bins":histogram_bins,"dihedral_angle":dihedral_histogram_total}) dihedral_df = dihedral_df.set_index(["bins"]) #file dihedral_df.to_csv("output_dihedral.out",sep = " ") #ratio of the dihedral configuration trans_ratio = float((dihedral_df.loc[:-120].sum()+dihedral_df.loc[120:].sum())/dihedral_df.sum()) gauche_minus_ratio = float(dihedral_df.loc[-120:0].sum()/dihedral_df.sum()) gauche_ratio = float(dihedral_df.loc[0:120].sum()/dihedral_df.sum()) print("Ratio of trans,gauche+ and gauche-: ",trans_ratio ,gauche_ratio,gauche_minus_ratio) return dihedral_df, trans_ratio,gauche_ratio,gauche_minus_ratio else: return None,None,None,None def visualize(dihedral_df): """Function to visualize the histogram Args: dihedral_df(dataframe): dataframe with the bins and frequencies Returns: a matplotlib histogram of the dihedral angles """ plt.bar(dihedral_df.index,dihedral_df.dihedral_angle) plt.xlabel(r"$\phi(^o)$") plt.ylabel(r"Nombre d'angles de torsion") plt.show() dihedral_df, trans_ratio,gauche_ratio,gauche_minus_ratio = open_multiple_dihedral_file() if rank == 0: visualize(dihedral_df)
mit
grlee77/pywt
demo/dwt2_dwtn_image.py
3
1776
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt import pywt import pywt.data # Load image original = pywt.data.camera() # Wavelet transform of image, and plot approximation and details titles = ['Approximation', ' Horizontal detail', 'Vertical detail', 'Diagonal detail'] coeffs2 = pywt.dwt2(original, 'bior1.3') LL, (LH, HL, HH) = coeffs2 fig = plt.figure() for i, a in enumerate([LL, LH, HL, HH]): ax = fig.add_subplot(2, 2, i + 1) ax.imshow(a, interpolation="nearest", cmap=plt.cm.gray) ax.set_title(titles[i], fontsize=12) ax.set_xticks([]) ax.set_yticks([]) fig.suptitle("dwt2 coefficients", fontsize=14) # Now reconstruct and plot the original image reconstructed = pywt.idwt2(coeffs2, 'bior1.3') fig = plt.figure() plt.imshow(reconstructed, interpolation="nearest", cmap=plt.cm.gray) # Check that reconstructed image is close to the original np.testing.assert_allclose(original, reconstructed, atol=1e-13, rtol=1e-13) # Now do the same with dwtn/idwtn, to show the difference in their signatures coeffsn = pywt.dwtn(original, 'bior1.3') fig = plt.figure() for i, key in enumerate(['aa', 'ad', 'da', 'dd']): ax = fig.add_subplot(2, 2, i + 1) ax.imshow(coeffsn[key], interpolation="nearest", cmap=plt.cm.gray) ax.set_title(titles[i], fontsize=12) ax.set_xticks([]) ax.set_yticks([]) fig.suptitle("dwtn coefficients", fontsize=14) # Now reconstruct and plot the original image reconstructed = pywt.idwtn(coeffsn, 'bior1.3') fig = plt.figure() plt.imshow(reconstructed, interpolation="nearest", cmap=plt.cm.gray) # Check that reconstructed image is close to the original np.testing.assert_allclose(original, reconstructed, atol=1e-13, rtol=1e-13) plt.show()
mit
djpine/pyman
Book/apdx1/Supporting Materials/PyInstallTest.py
3
1524
#!/bin/sh # This code tests that your Python installation worked. # It generates a png image file that you should e-mail # to the address shown on the plot import scipy import numpy import matplotlib import matplotlib.pyplot as plt import platform import socket # If you are a student, please fill in your first and last # names inside the quotes in the two lines below. Do not # modify anything else in this file your_first_name = 'Dana' your_last_name = 'Smith' # If you are an instructor, modify the next 3 lines. # You do not need to modify anything else in this file. classname = 'Intro Exp Phys I' term = 'Fall_2012' # must contain no spaces email = '[email protected]' plt.plot([0,1], 'r', [1,0], 'b') plt.text( 0.5, 0.9, '{0:s} {1:s}\n{2:s}\n{3:s}' .format(your_first_name, your_last_name, classname, term), horizontalalignment='center', verticalalignment='top', size = 'x-large', bbox=dict(facecolor='purple', alpha=0.4)) plt.text( 0.5, 0.1, 'scipy {0:s}\nnumpy {1:s}\nmatplotlib {2:s}\non {3:s}\n{4:s}' .format(scipy.__version__, numpy.__version__, matplotlib.__version__, platform.platform(), socket.gethostname() ) , horizontalalignment='center', verticalalignment='bottom') filename = your_last_name + '_' + your_first_name + '_' + \ term + '.png' plt.title('{0:s} "{1:s}"\n E-mail this file to "{2:s}"' .format('This plot has been saved on your computer as', filename, email), fontsize=12) plt.savefig(filename) plt.show()
cc0-1.0
akionakamura/scikit-learn
sklearn/preprocessing/tests/test_data.py
113
38432
import warnings import numpy as np import numpy.linalg as la from scipy import sparse from distutils.version import LooseVersion from sklearn.utils.testing import assert_almost_equal, clean_warning_registry from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_greater_equal from sklearn.utils.testing import assert_less_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_false from sklearn.utils.testing import assert_warns_message from sklearn.utils.testing import assert_no_warnings from sklearn.utils.sparsefuncs import mean_variance_axis from sklearn.preprocessing.data import _transform_selected from sklearn.preprocessing.data import Binarizer from sklearn.preprocessing.data import KernelCenterer from sklearn.preprocessing.data import Normalizer from sklearn.preprocessing.data import normalize from sklearn.preprocessing.data import OneHotEncoder from sklearn.preprocessing.data import StandardScaler from sklearn.preprocessing.data import scale from sklearn.preprocessing.data import MinMaxScaler from sklearn.preprocessing.data import minmax_scale from sklearn.preprocessing.data import MaxAbsScaler from sklearn.preprocessing.data import maxabs_scale from sklearn.preprocessing.data import RobustScaler from sklearn.preprocessing.data import robust_scale from sklearn.preprocessing.data import add_dummy_feature from sklearn.preprocessing.data import PolynomialFeatures from sklearn.utils.validation import DataConversionWarning from sklearn import datasets iris = datasets.load_iris() def toarray(a): if hasattr(a, "toarray"): a = a.toarray() return a def test_polynomial_features(): # Test Polynomial Features X1 = np.arange(6)[:, np.newaxis] P1 = np.hstack([np.ones_like(X1), X1, X1 ** 2, X1 ** 3]) deg1 = 3 X2 = np.arange(6).reshape((3, 2)) x1 = X2[:, :1] x2 = X2[:, 1:] P2 = np.hstack([x1 ** 0 * x2 ** 0, x1 ** 1 * x2 ** 0, x1 ** 0 * x2 ** 1, x1 ** 2 * x2 ** 0, x1 ** 1 * x2 ** 1, x1 ** 0 * x2 ** 2]) deg2 = 2 for (deg, X, P) in [(deg1, X1, P1), (deg2, X2, P2)]: P_test = PolynomialFeatures(deg, include_bias=True).fit_transform(X) assert_array_almost_equal(P_test, P) P_test = PolynomialFeatures(deg, include_bias=False).fit_transform(X) assert_array_almost_equal(P_test, P[:, 1:]) interact = PolynomialFeatures(2, interaction_only=True, include_bias=True) X_poly = interact.fit_transform(X) assert_array_almost_equal(X_poly, P2[:, [0, 1, 2, 4]]) def test_scaler_1d(): # Test scaling of dataset along single axis rng = np.random.RandomState(0) X = rng.randn(5) X_orig_copy = X.copy() scaler = StandardScaler() X_scaled = scaler.fit(X).transform(X, copy=False) assert_array_almost_equal(X_scaled.mean(axis=0), 0.0) assert_array_almost_equal(X_scaled.std(axis=0), 1.0) # check inverse transform X_scaled_back = scaler.inverse_transform(X_scaled) assert_array_almost_equal(X_scaled_back, X_orig_copy) # Test with 1D list X = [0., 1., 2, 0.4, 1.] scaler = StandardScaler() X_scaled = scaler.fit(X).transform(X, copy=False) assert_array_almost_equal(X_scaled.mean(axis=0), 0.0) assert_array_almost_equal(X_scaled.std(axis=0), 1.0) X_scaled = scale(X) assert_array_almost_equal(X_scaled.mean(axis=0), 0.0) assert_array_almost_equal(X_scaled.std(axis=0), 1.0) X = np.ones(5) assert_array_equal(scale(X, with_mean=False), X) def test_standard_scaler_numerical_stability(): """Test numerical stability of scaling""" # np.log(1e-5) is taken because of its floating point representation # was empirically found to cause numerical problems with np.mean & np.std. x = np.zeros(8, dtype=np.float64) + np.log(1e-5, dtype=np.float64) if LooseVersion(np.__version__) >= LooseVersion('1.9'): # This does not raise a warning as the number of samples is too low # to trigger the problem in recent numpy x_scaled = assert_no_warnings(scale, x) assert_array_almost_equal(scale(x), np.zeros(8)) else: w = "standard deviation of the data is probably very close to 0" x_scaled = assert_warns_message(UserWarning, w, scale, x) assert_array_almost_equal(x_scaled, np.zeros(8)) # with 2 more samples, the std computation run into numerical issues: x = np.zeros(10, dtype=np.float64) + np.log(1e-5, dtype=np.float64) w = "standard deviation of the data is probably very close to 0" x_scaled = assert_warns_message(UserWarning, w, scale, x) assert_array_almost_equal(x_scaled, np.zeros(10)) x = np.ones(10, dtype=np.float64) * 1e-100 x_small_scaled = assert_no_warnings(scale, x) assert_array_almost_equal(x_small_scaled, np.zeros(10)) # Large values can cause (often recoverable) numerical stability issues: x_big = np.ones(10, dtype=np.float64) * 1e100 w = "Dataset may contain too large values" x_big_scaled = assert_warns_message(UserWarning, w, scale, x_big) assert_array_almost_equal(x_big_scaled, np.zeros(10)) assert_array_almost_equal(x_big_scaled, x_small_scaled) x_big_centered = assert_warns_message(UserWarning, w, scale, x_big, with_std=False) assert_array_almost_equal(x_big_centered, np.zeros(10)) assert_array_almost_equal(x_big_centered, x_small_scaled) def test_scaler_2d_arrays(): # Test scaling of 2d array along first axis rng = np.random.RandomState(0) X = rng.randn(4, 5) X[:, 0] = 0.0 # first feature is always of zero scaler = StandardScaler() X_scaled = scaler.fit(X).transform(X, copy=True) assert_false(np.any(np.isnan(X_scaled))) assert_array_almost_equal(X_scaled.mean(axis=0), 5 * [0.0]) assert_array_almost_equal(X_scaled.std(axis=0), [0., 1., 1., 1., 1.]) # Check that X has been copied assert_true(X_scaled is not X) # check inverse transform X_scaled_back = scaler.inverse_transform(X_scaled) assert_true(X_scaled_back is not X) assert_true(X_scaled_back is not X_scaled) assert_array_almost_equal(X_scaled_back, X) X_scaled = scale(X, axis=1, with_std=False) assert_false(np.any(np.isnan(X_scaled))) assert_array_almost_equal(X_scaled.mean(axis=1), 4 * [0.0]) X_scaled = scale(X, axis=1, with_std=True) assert_false(np.any(np.isnan(X_scaled))) assert_array_almost_equal(X_scaled.mean(axis=1), 4 * [0.0]) assert_array_almost_equal(X_scaled.std(axis=1), 4 * [1.0]) # Check that the data hasn't been modified assert_true(X_scaled is not X) X_scaled = scaler.fit(X).transform(X, copy=False) assert_false(np.any(np.isnan(X_scaled))) assert_array_almost_equal(X_scaled.mean(axis=0), 5 * [0.0]) assert_array_almost_equal(X_scaled.std(axis=0), [0., 1., 1., 1., 1.]) # Check that X has not been copied assert_true(X_scaled is X) X = rng.randn(4, 5) X[:, 0] = 1.0 # first feature is a constant, non zero feature scaler = StandardScaler() X_scaled = scaler.fit(X).transform(X, copy=True) assert_false(np.any(np.isnan(X_scaled))) assert_array_almost_equal(X_scaled.mean(axis=0), 5 * [0.0]) assert_array_almost_equal(X_scaled.std(axis=0), [0., 1., 1., 1., 1.]) # Check that X has not been copied assert_true(X_scaled is not X) def test_min_max_scaler_iris(): X = iris.data scaler = MinMaxScaler() # default params X_trans = scaler.fit_transform(X) assert_array_almost_equal(X_trans.min(axis=0), 0) assert_array_almost_equal(X_trans.min(axis=0), 0) assert_array_almost_equal(X_trans.max(axis=0), 1) X_trans_inv = scaler.inverse_transform(X_trans) assert_array_almost_equal(X, X_trans_inv) # not default params: min=1, max=2 scaler = MinMaxScaler(feature_range=(1, 2)) X_trans = scaler.fit_transform(X) assert_array_almost_equal(X_trans.min(axis=0), 1) assert_array_almost_equal(X_trans.max(axis=0), 2) X_trans_inv = scaler.inverse_transform(X_trans) assert_array_almost_equal(X, X_trans_inv) # min=-.5, max=.6 scaler = MinMaxScaler(feature_range=(-.5, .6)) X_trans = scaler.fit_transform(X) assert_array_almost_equal(X_trans.min(axis=0), -.5) assert_array_almost_equal(X_trans.max(axis=0), .6) X_trans_inv = scaler.inverse_transform(X_trans) assert_array_almost_equal(X, X_trans_inv) # raises on invalid range scaler = MinMaxScaler(feature_range=(2, 1)) assert_raises(ValueError, scaler.fit, X) def test_min_max_scaler_zero_variance_features(): # Check min max scaler on toy data with zero variance features X = [[0., 1., +0.5], [0., 1., -0.1], [0., 1., +1.1]] X_new = [[+0., 2., 0.5], [-1., 1., 0.0], [+0., 1., 1.5]] # default params scaler = MinMaxScaler() X_trans = scaler.fit_transform(X) X_expected_0_1 = [[0., 0., 0.5], [0., 0., 0.0], [0., 0., 1.0]] assert_array_almost_equal(X_trans, X_expected_0_1) X_trans_inv = scaler.inverse_transform(X_trans) assert_array_almost_equal(X, X_trans_inv) X_trans_new = scaler.transform(X_new) X_expected_0_1_new = [[+0., 1., 0.500], [-1., 0., 0.083], [+0., 0., 1.333]] assert_array_almost_equal(X_trans_new, X_expected_0_1_new, decimal=2) # not default params scaler = MinMaxScaler(feature_range=(1, 2)) X_trans = scaler.fit_transform(X) X_expected_1_2 = [[1., 1., 1.5], [1., 1., 1.0], [1., 1., 2.0]] assert_array_almost_equal(X_trans, X_expected_1_2) # function interface X_trans = minmax_scale(X) assert_array_almost_equal(X_trans, X_expected_0_1) X_trans = minmax_scale(X, feature_range=(1, 2)) assert_array_almost_equal(X_trans, X_expected_1_2) def test_minmax_scale_axis1(): X = iris.data X_trans = minmax_scale(X, axis=1) assert_array_almost_equal(np.min(X_trans, axis=1), 0) assert_array_almost_equal(np.max(X_trans, axis=1), 1) def test_min_max_scaler_1d(): # Test scaling of dataset along single axis rng = np.random.RandomState(0) X = rng.randn(5) X_orig_copy = X.copy() scaler = MinMaxScaler() X_scaled = scaler.fit(X).transform(X) assert_array_almost_equal(X_scaled.min(axis=0), 0.0) assert_array_almost_equal(X_scaled.max(axis=0), 1.0) # check inverse transform X_scaled_back = scaler.inverse_transform(X_scaled) assert_array_almost_equal(X_scaled_back, X_orig_copy) # Test with 1D list X = [0., 1., 2, 0.4, 1.] scaler = MinMaxScaler() X_scaled = scaler.fit(X).transform(X) assert_array_almost_equal(X_scaled.min(axis=0), 0.0) assert_array_almost_equal(X_scaled.max(axis=0), 1.0) # Constant feature. X = np.zeros(5) scaler = MinMaxScaler() X_scaled = scaler.fit(X).transform(X) assert_greater_equal(X_scaled.min(), 0.) assert_less_equal(X_scaled.max(), 1.) def test_scaler_without_centering(): rng = np.random.RandomState(42) X = rng.randn(4, 5) X[:, 0] = 0.0 # first feature is always of zero X_csr = sparse.csr_matrix(X) X_csc = sparse.csc_matrix(X) assert_raises(ValueError, StandardScaler().fit, X_csr) null_transform = StandardScaler(with_mean=False, with_std=False, copy=True) X_null = null_transform.fit_transform(X_csr) assert_array_equal(X_null.data, X_csr.data) X_orig = null_transform.inverse_transform(X_null) assert_array_equal(X_orig.data, X_csr.data) scaler = StandardScaler(with_mean=False).fit(X) X_scaled = scaler.transform(X, copy=True) assert_false(np.any(np.isnan(X_scaled))) scaler_csr = StandardScaler(with_mean=False).fit(X_csr) X_csr_scaled = scaler_csr.transform(X_csr, copy=True) assert_false(np.any(np.isnan(X_csr_scaled.data))) scaler_csc = StandardScaler(with_mean=False).fit(X_csc) X_csc_scaled = scaler_csr.transform(X_csc, copy=True) assert_false(np.any(np.isnan(X_csc_scaled.data))) assert_equal(scaler.mean_, scaler_csr.mean_) assert_array_almost_equal(scaler.std_, scaler_csr.std_) assert_equal(scaler.mean_, scaler_csc.mean_) assert_array_almost_equal(scaler.std_, scaler_csc.std_) assert_array_almost_equal( X_scaled.mean(axis=0), [0., -0.01, 2.24, -0.35, -0.78], 2) assert_array_almost_equal(X_scaled.std(axis=0), [0., 1., 1., 1., 1.]) X_csr_scaled_mean, X_csr_scaled_std = mean_variance_axis(X_csr_scaled, 0) assert_array_almost_equal(X_csr_scaled_mean, X_scaled.mean(axis=0)) assert_array_almost_equal(X_csr_scaled_std, X_scaled.std(axis=0)) # Check that X has not been modified (copy) assert_true(X_scaled is not X) assert_true(X_csr_scaled is not X_csr) X_scaled_back = scaler.inverse_transform(X_scaled) assert_true(X_scaled_back is not X) assert_true(X_scaled_back is not X_scaled) assert_array_almost_equal(X_scaled_back, X) X_csr_scaled_back = scaler_csr.inverse_transform(X_csr_scaled) assert_true(X_csr_scaled_back is not X_csr) assert_true(X_csr_scaled_back is not X_csr_scaled) assert_array_almost_equal(X_csr_scaled_back.toarray(), X) X_csc_scaled_back = scaler_csr.inverse_transform(X_csc_scaled.tocsc()) assert_true(X_csc_scaled_back is not X_csc) assert_true(X_csc_scaled_back is not X_csc_scaled) assert_array_almost_equal(X_csc_scaled_back.toarray(), X) def test_scaler_int(): # test that scaler converts integer input to floating # for both sparse and dense matrices rng = np.random.RandomState(42) X = rng.randint(20, size=(4, 5)) X[:, 0] = 0 # first feature is always of zero X_csr = sparse.csr_matrix(X) X_csc = sparse.csc_matrix(X) null_transform = StandardScaler(with_mean=False, with_std=False, copy=True) clean_warning_registry() with warnings.catch_warnings(record=True): X_null = null_transform.fit_transform(X_csr) assert_array_equal(X_null.data, X_csr.data) X_orig = null_transform.inverse_transform(X_null) assert_array_equal(X_orig.data, X_csr.data) clean_warning_registry() with warnings.catch_warnings(record=True): scaler = StandardScaler(with_mean=False).fit(X) X_scaled = scaler.transform(X, copy=True) assert_false(np.any(np.isnan(X_scaled))) clean_warning_registry() with warnings.catch_warnings(record=True): scaler_csr = StandardScaler(with_mean=False).fit(X_csr) X_csr_scaled = scaler_csr.transform(X_csr, copy=True) assert_false(np.any(np.isnan(X_csr_scaled.data))) clean_warning_registry() with warnings.catch_warnings(record=True): scaler_csc = StandardScaler(with_mean=False).fit(X_csc) X_csc_scaled = scaler_csr.transform(X_csc, copy=True) assert_false(np.any(np.isnan(X_csc_scaled.data))) assert_equal(scaler.mean_, scaler_csr.mean_) assert_array_almost_equal(scaler.std_, scaler_csr.std_) assert_equal(scaler.mean_, scaler_csc.mean_) assert_array_almost_equal(scaler.std_, scaler_csc.std_) assert_array_almost_equal( X_scaled.mean(axis=0), [0., 1.109, 1.856, 21., 1.559], 2) assert_array_almost_equal(X_scaled.std(axis=0), [0., 1., 1., 1., 1.]) X_csr_scaled_mean, X_csr_scaled_std = mean_variance_axis( X_csr_scaled.astype(np.float), 0) assert_array_almost_equal(X_csr_scaled_mean, X_scaled.mean(axis=0)) assert_array_almost_equal(X_csr_scaled_std, X_scaled.std(axis=0)) # Check that X has not been modified (copy) assert_true(X_scaled is not X) assert_true(X_csr_scaled is not X_csr) X_scaled_back = scaler.inverse_transform(X_scaled) assert_true(X_scaled_back is not X) assert_true(X_scaled_back is not X_scaled) assert_array_almost_equal(X_scaled_back, X) X_csr_scaled_back = scaler_csr.inverse_transform(X_csr_scaled) assert_true(X_csr_scaled_back is not X_csr) assert_true(X_csr_scaled_back is not X_csr_scaled) assert_array_almost_equal(X_csr_scaled_back.toarray(), X) X_csc_scaled_back = scaler_csr.inverse_transform(X_csc_scaled.tocsc()) assert_true(X_csc_scaled_back is not X_csc) assert_true(X_csc_scaled_back is not X_csc_scaled) assert_array_almost_equal(X_csc_scaled_back.toarray(), X) def test_scaler_without_copy(): # Check that StandardScaler.fit does not change input rng = np.random.RandomState(42) X = rng.randn(4, 5) X[:, 0] = 0.0 # first feature is always of zero X_csr = sparse.csr_matrix(X) X_copy = X.copy() StandardScaler(copy=False).fit(X) assert_array_equal(X, X_copy) X_csr_copy = X_csr.copy() StandardScaler(with_mean=False, copy=False).fit(X_csr) assert_array_equal(X_csr.toarray(), X_csr_copy.toarray()) def test_scale_sparse_with_mean_raise_exception(): rng = np.random.RandomState(42) X = rng.randn(4, 5) X_csr = sparse.csr_matrix(X) # check scaling and fit with direct calls on sparse data assert_raises(ValueError, scale, X_csr, with_mean=True) assert_raises(ValueError, StandardScaler(with_mean=True).fit, X_csr) # check transform and inverse_transform after a fit on a dense array scaler = StandardScaler(with_mean=True).fit(X) assert_raises(ValueError, scaler.transform, X_csr) X_transformed_csr = sparse.csr_matrix(scaler.transform(X)) assert_raises(ValueError, scaler.inverse_transform, X_transformed_csr) def test_scale_input_finiteness_validation(): # Check if non finite inputs raise ValueError X = [np.nan, 5, 6, 7, 8] assert_raises_regex(ValueError, "Input contains NaN, infinity or a value too large", scale, X) X = [np.inf, 5, 6, 7, 8] assert_raises_regex(ValueError, "Input contains NaN, infinity or a value too large", scale, X) def test_scale_function_without_centering(): rng = np.random.RandomState(42) X = rng.randn(4, 5) X[:, 0] = 0.0 # first feature is always of zero X_csr = sparse.csr_matrix(X) X_scaled = scale(X, with_mean=False) assert_false(np.any(np.isnan(X_scaled))) X_csr_scaled = scale(X_csr, with_mean=False) assert_false(np.any(np.isnan(X_csr_scaled.data))) # test csc has same outcome X_csc_scaled = scale(X_csr.tocsc(), with_mean=False) assert_array_almost_equal(X_scaled, X_csc_scaled.toarray()) # raises value error on axis != 0 assert_raises(ValueError, scale, X_csr, with_mean=False, axis=1) assert_array_almost_equal(X_scaled.mean(axis=0), [0., -0.01, 2.24, -0.35, -0.78], 2) assert_array_almost_equal(X_scaled.std(axis=0), [0., 1., 1., 1., 1.]) # Check that X has not been copied assert_true(X_scaled is not X) X_csr_scaled_mean, X_csr_scaled_std = mean_variance_axis(X_csr_scaled, 0) assert_array_almost_equal(X_csr_scaled_mean, X_scaled.mean(axis=0)) assert_array_almost_equal(X_csr_scaled_std, X_scaled.std(axis=0)) def test_robust_scaler_2d_arrays(): """Test robust scaling of 2d array along first axis""" rng = np.random.RandomState(0) X = rng.randn(4, 5) X[:, 0] = 0.0 # first feature is always of zero scaler = RobustScaler() X_scaled = scaler.fit(X).transform(X) assert_array_almost_equal(np.median(X_scaled, axis=0), 5 * [0.0]) assert_array_almost_equal(X_scaled.std(axis=0)[0], 0) def test_robust_scaler_iris(): X = iris.data scaler = RobustScaler() X_trans = scaler.fit_transform(X) assert_array_almost_equal(np.median(X_trans, axis=0), 0) X_trans_inv = scaler.inverse_transform(X_trans) assert_array_almost_equal(X, X_trans_inv) q = np.percentile(X_trans, q=(25, 75), axis=0) iqr = q[1] - q[0] assert_array_almost_equal(iqr, 1) def test_robust_scale_axis1(): X = iris.data X_trans = robust_scale(X, axis=1) assert_array_almost_equal(np.median(X_trans, axis=1), 0) q = np.percentile(X_trans, q=(25, 75), axis=1) iqr = q[1] - q[0] assert_array_almost_equal(iqr, 1) def test_robust_scaler_zero_variance_features(): """Check RobustScaler on toy data with zero variance features""" X = [[0., 1., +0.5], [0., 1., -0.1], [0., 1., +1.1]] scaler = RobustScaler() X_trans = scaler.fit_transform(X) # NOTE: for such a small sample size, what we expect in the third column # depends HEAVILY on the method used to calculate quantiles. The values # here were calculated to fit the quantiles produces by np.percentile # using numpy 1.9 Calculating quantiles with # scipy.stats.mstats.scoreatquantile or scipy.stats.mstats.mquantiles # would yield very different results! X_expected = [[0., 0., +0.0], [0., 0., -1.0], [0., 0., +1.0]] assert_array_almost_equal(X_trans, X_expected) X_trans_inv = scaler.inverse_transform(X_trans) assert_array_almost_equal(X, X_trans_inv) # make sure new data gets transformed correctly X_new = [[+0., 2., 0.5], [-1., 1., 0.0], [+0., 1., 1.5]] X_trans_new = scaler.transform(X_new) X_expected_new = [[+0., 1., +0.], [-1., 0., -0.83333], [+0., 0., +1.66667]] assert_array_almost_equal(X_trans_new, X_expected_new, decimal=3) def test_maxabs_scaler_zero_variance_features(): """Check MaxAbsScaler on toy data with zero variance features""" X = [[0., 1., +0.5], [0., 1., -0.3], [0., 1., +1.5], [0., 0., +0.0]] scaler = MaxAbsScaler() X_trans = scaler.fit_transform(X) X_expected = [[0., 1., 1.0 / 3.0], [0., 1., -0.2], [0., 1., 1.0], [0., 0., 0.0]] assert_array_almost_equal(X_trans, X_expected) X_trans_inv = scaler.inverse_transform(X_trans) assert_array_almost_equal(X, X_trans_inv) # make sure new data gets transformed correctly X_new = [[+0., 2., 0.5], [-1., 1., 0.0], [+0., 1., 1.5]] X_trans_new = scaler.transform(X_new) X_expected_new = [[+0., 2.0, 1.0 / 3.0], [-1., 1.0, 0.0], [+0., 1.0, 1.0]] assert_array_almost_equal(X_trans_new, X_expected_new, decimal=2) # sparse data X_csr = sparse.csr_matrix(X) X_trans = scaler.fit_transform(X_csr) X_expected = [[0., 1., 1.0 / 3.0], [0., 1., -0.2], [0., 1., 1.0], [0., 0., 0.0]] assert_array_almost_equal(X_trans.A, X_expected) X_trans_inv = scaler.inverse_transform(X_trans) assert_array_almost_equal(X, X_trans_inv.A) def test_maxabs_scaler_large_negative_value(): """Check MaxAbsScaler on toy data with a large negative value""" X = [[0., 1., +0.5, -1.0], [0., 1., -0.3, -0.5], [0., 1., -100.0, 0.0], [0., 0., +0.0, -2.0]] scaler = MaxAbsScaler() X_trans = scaler.fit_transform(X) X_expected = [[0., 1., 0.005, -0.5], [0., 1., -0.003, -0.25], [0., 1., -1.0, 0.0], [0., 0., 0.0, -1.0]] assert_array_almost_equal(X_trans, X_expected) def test_warning_scaling_integers(): # Check warning when scaling integer data X = np.array([[1, 2, 0], [0, 0, 0]], dtype=np.uint8) w = "Data with input dtype uint8 was converted to float64" clean_warning_registry() assert_warns_message(DataConversionWarning, w, scale, X) assert_warns_message(DataConversionWarning, w, StandardScaler().fit, X) assert_warns_message(DataConversionWarning, w, MinMaxScaler().fit, X) def test_normalizer_l1(): rng = np.random.RandomState(0) X_dense = rng.randn(4, 5) X_sparse_unpruned = sparse.csr_matrix(X_dense) # set the row number 3 to zero X_dense[3, :] = 0.0 # set the row number 3 to zero without pruning (can happen in real life) indptr_3 = X_sparse_unpruned.indptr[3] indptr_4 = X_sparse_unpruned.indptr[4] X_sparse_unpruned.data[indptr_3:indptr_4] = 0.0 # build the pruned variant using the regular constructor X_sparse_pruned = sparse.csr_matrix(X_dense) # check inputs that support the no-copy optim for X in (X_dense, X_sparse_pruned, X_sparse_unpruned): normalizer = Normalizer(norm='l1', copy=True) X_norm = normalizer.transform(X) assert_true(X_norm is not X) X_norm1 = toarray(X_norm) normalizer = Normalizer(norm='l1', copy=False) X_norm = normalizer.transform(X) assert_true(X_norm is X) X_norm2 = toarray(X_norm) for X_norm in (X_norm1, X_norm2): row_sums = np.abs(X_norm).sum(axis=1) for i in range(3): assert_almost_equal(row_sums[i], 1.0) assert_almost_equal(row_sums[3], 0.0) # check input for which copy=False won't prevent a copy for init in (sparse.coo_matrix, sparse.csc_matrix, sparse.lil_matrix): X = init(X_dense) X_norm = normalizer = Normalizer(norm='l2', copy=False).transform(X) assert_true(X_norm is not X) assert_true(isinstance(X_norm, sparse.csr_matrix)) X_norm = toarray(X_norm) for i in range(3): assert_almost_equal(row_sums[i], 1.0) assert_almost_equal(la.norm(X_norm[3]), 0.0) def test_normalizer_l2(): rng = np.random.RandomState(0) X_dense = rng.randn(4, 5) X_sparse_unpruned = sparse.csr_matrix(X_dense) # set the row number 3 to zero X_dense[3, :] = 0.0 # set the row number 3 to zero without pruning (can happen in real life) indptr_3 = X_sparse_unpruned.indptr[3] indptr_4 = X_sparse_unpruned.indptr[4] X_sparse_unpruned.data[indptr_3:indptr_4] = 0.0 # build the pruned variant using the regular constructor X_sparse_pruned = sparse.csr_matrix(X_dense) # check inputs that support the no-copy optim for X in (X_dense, X_sparse_pruned, X_sparse_unpruned): normalizer = Normalizer(norm='l2', copy=True) X_norm1 = normalizer.transform(X) assert_true(X_norm1 is not X) X_norm1 = toarray(X_norm1) normalizer = Normalizer(norm='l2', copy=False) X_norm2 = normalizer.transform(X) assert_true(X_norm2 is X) X_norm2 = toarray(X_norm2) for X_norm in (X_norm1, X_norm2): for i in range(3): assert_almost_equal(la.norm(X_norm[i]), 1.0) assert_almost_equal(la.norm(X_norm[3]), 0.0) # check input for which copy=False won't prevent a copy for init in (sparse.coo_matrix, sparse.csc_matrix, sparse.lil_matrix): X = init(X_dense) X_norm = normalizer = Normalizer(norm='l2', copy=False).transform(X) assert_true(X_norm is not X) assert_true(isinstance(X_norm, sparse.csr_matrix)) X_norm = toarray(X_norm) for i in range(3): assert_almost_equal(la.norm(X_norm[i]), 1.0) assert_almost_equal(la.norm(X_norm[3]), 0.0) def test_normalizer_max(): rng = np.random.RandomState(0) X_dense = rng.randn(4, 5) X_sparse_unpruned = sparse.csr_matrix(X_dense) # set the row number 3 to zero X_dense[3, :] = 0.0 # set the row number 3 to zero without pruning (can happen in real life) indptr_3 = X_sparse_unpruned.indptr[3] indptr_4 = X_sparse_unpruned.indptr[4] X_sparse_unpruned.data[indptr_3:indptr_4] = 0.0 # build the pruned variant using the regular constructor X_sparse_pruned = sparse.csr_matrix(X_dense) # check inputs that support the no-copy optim for X in (X_dense, X_sparse_pruned, X_sparse_unpruned): normalizer = Normalizer(norm='max', copy=True) X_norm1 = normalizer.transform(X) assert_true(X_norm1 is not X) X_norm1 = toarray(X_norm1) normalizer = Normalizer(norm='max', copy=False) X_norm2 = normalizer.transform(X) assert_true(X_norm2 is X) X_norm2 = toarray(X_norm2) for X_norm in (X_norm1, X_norm2): row_maxs = X_norm.max(axis=1) for i in range(3): assert_almost_equal(row_maxs[i], 1.0) assert_almost_equal(row_maxs[3], 0.0) # check input for which copy=False won't prevent a copy for init in (sparse.coo_matrix, sparse.csc_matrix, sparse.lil_matrix): X = init(X_dense) X_norm = normalizer = Normalizer(norm='l2', copy=False).transform(X) assert_true(X_norm is not X) assert_true(isinstance(X_norm, sparse.csr_matrix)) X_norm = toarray(X_norm) for i in range(3): assert_almost_equal(row_maxs[i], 1.0) assert_almost_equal(la.norm(X_norm[3]), 0.0) def test_normalize(): # Test normalize function # Only tests functionality not used by the tests for Normalizer. X = np.random.RandomState(37).randn(3, 2) assert_array_equal(normalize(X, copy=False), normalize(X.T, axis=0, copy=False).T) assert_raises(ValueError, normalize, [[0]], axis=2) assert_raises(ValueError, normalize, [[0]], norm='l3') def test_binarizer(): X_ = np.array([[1, 0, 5], [2, 3, -1]]) for init in (np.array, list, sparse.csr_matrix, sparse.csc_matrix): X = init(X_.copy()) binarizer = Binarizer(threshold=2.0, copy=True) X_bin = toarray(binarizer.transform(X)) assert_equal(np.sum(X_bin == 0), 4) assert_equal(np.sum(X_bin == 1), 2) X_bin = binarizer.transform(X) assert_equal(sparse.issparse(X), sparse.issparse(X_bin)) binarizer = Binarizer(copy=True).fit(X) X_bin = toarray(binarizer.transform(X)) assert_true(X_bin is not X) assert_equal(np.sum(X_bin == 0), 2) assert_equal(np.sum(X_bin == 1), 4) binarizer = Binarizer(copy=True) X_bin = binarizer.transform(X) assert_true(X_bin is not X) X_bin = toarray(X_bin) assert_equal(np.sum(X_bin == 0), 2) assert_equal(np.sum(X_bin == 1), 4) binarizer = Binarizer(copy=False) X_bin = binarizer.transform(X) if init is not list: assert_true(X_bin is X) X_bin = toarray(X_bin) assert_equal(np.sum(X_bin == 0), 2) assert_equal(np.sum(X_bin == 1), 4) binarizer = Binarizer(threshold=-0.5, copy=True) for init in (np.array, list): X = init(X_.copy()) X_bin = toarray(binarizer.transform(X)) assert_equal(np.sum(X_bin == 0), 1) assert_equal(np.sum(X_bin == 1), 5) X_bin = binarizer.transform(X) # Cannot use threshold < 0 for sparse assert_raises(ValueError, binarizer.transform, sparse.csc_matrix(X)) def test_center_kernel(): # Test that KernelCenterer is equivalent to StandardScaler # in feature space rng = np.random.RandomState(0) X_fit = rng.random_sample((5, 4)) scaler = StandardScaler(with_std=False) scaler.fit(X_fit) X_fit_centered = scaler.transform(X_fit) K_fit = np.dot(X_fit, X_fit.T) # center fit time matrix centerer = KernelCenterer() K_fit_centered = np.dot(X_fit_centered, X_fit_centered.T) K_fit_centered2 = centerer.fit_transform(K_fit) assert_array_almost_equal(K_fit_centered, K_fit_centered2) # center predict time matrix X_pred = rng.random_sample((2, 4)) K_pred = np.dot(X_pred, X_fit.T) X_pred_centered = scaler.transform(X_pred) K_pred_centered = np.dot(X_pred_centered, X_fit_centered.T) K_pred_centered2 = centerer.transform(K_pred) assert_array_almost_equal(K_pred_centered, K_pred_centered2) def test_fit_transform(): rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) for obj in ((StandardScaler(), Normalizer(), Binarizer())): X_transformed = obj.fit(X).transform(X) X_transformed2 = obj.fit_transform(X) assert_array_equal(X_transformed, X_transformed2) def test_add_dummy_feature(): X = [[1, 0], [0, 1], [0, 1]] X = add_dummy_feature(X) assert_array_equal(X, [[1, 1, 0], [1, 0, 1], [1, 0, 1]]) def test_add_dummy_feature_coo(): X = sparse.coo_matrix([[1, 0], [0, 1], [0, 1]]) X = add_dummy_feature(X) assert_true(sparse.isspmatrix_coo(X), X) assert_array_equal(X.toarray(), [[1, 1, 0], [1, 0, 1], [1, 0, 1]]) def test_add_dummy_feature_csc(): X = sparse.csc_matrix([[1, 0], [0, 1], [0, 1]]) X = add_dummy_feature(X) assert_true(sparse.isspmatrix_csc(X), X) assert_array_equal(X.toarray(), [[1, 1, 0], [1, 0, 1], [1, 0, 1]]) def test_add_dummy_feature_csr(): X = sparse.csr_matrix([[1, 0], [0, 1], [0, 1]]) X = add_dummy_feature(X) assert_true(sparse.isspmatrix_csr(X), X) assert_array_equal(X.toarray(), [[1, 1, 0], [1, 0, 1], [1, 0, 1]]) def test_one_hot_encoder_sparse(): # Test OneHotEncoder's fit and transform. X = [[3, 2, 1], [0, 1, 1]] enc = OneHotEncoder() # discover max values automatically X_trans = enc.fit_transform(X).toarray() assert_equal(X_trans.shape, (2, 5)) assert_array_equal(enc.active_features_, np.where([1, 0, 0, 1, 0, 1, 1, 0, 1])[0]) assert_array_equal(enc.feature_indices_, [0, 4, 7, 9]) # check outcome assert_array_equal(X_trans, [[0., 1., 0., 1., 1.], [1., 0., 1., 0., 1.]]) # max value given as 3 enc = OneHotEncoder(n_values=4) X_trans = enc.fit_transform(X) assert_equal(X_trans.shape, (2, 4 * 3)) assert_array_equal(enc.feature_indices_, [0, 4, 8, 12]) # max value given per feature enc = OneHotEncoder(n_values=[3, 2, 2]) X = [[1, 0, 1], [0, 1, 1]] X_trans = enc.fit_transform(X) assert_equal(X_trans.shape, (2, 3 + 2 + 2)) assert_array_equal(enc.n_values_, [3, 2, 2]) # check that testing with larger feature works: X = np.array([[2, 0, 1], [0, 1, 1]]) enc.transform(X) # test that an error is raised when out of bounds: X_too_large = [[0, 2, 1], [0, 1, 1]] assert_raises(ValueError, enc.transform, X_too_large) assert_raises(ValueError, OneHotEncoder(n_values=2).fit_transform, X) # test that error is raised when wrong number of features assert_raises(ValueError, enc.transform, X[:, :-1]) # test that error is raised when wrong number of features in fit # with prespecified n_values assert_raises(ValueError, enc.fit, X[:, :-1]) # test exception on wrong init param assert_raises(TypeError, OneHotEncoder(n_values=np.int).fit, X) enc = OneHotEncoder() # test negative input to fit assert_raises(ValueError, enc.fit, [[0], [-1]]) # test negative input to transform enc.fit([[0], [1]]) assert_raises(ValueError, enc.transform, [[0], [-1]]) def test_one_hot_encoder_dense(): # check for sparse=False X = [[3, 2, 1], [0, 1, 1]] enc = OneHotEncoder(sparse=False) # discover max values automatically X_trans = enc.fit_transform(X) assert_equal(X_trans.shape, (2, 5)) assert_array_equal(enc.active_features_, np.where([1, 0, 0, 1, 0, 1, 1, 0, 1])[0]) assert_array_equal(enc.feature_indices_, [0, 4, 7, 9]) # check outcome assert_array_equal(X_trans, np.array([[0., 1., 0., 1., 1.], [1., 0., 1., 0., 1.]])) def _check_transform_selected(X, X_expected, sel): for M in (X, sparse.csr_matrix(X)): Xtr = _transform_selected(M, Binarizer().transform, sel) assert_array_equal(toarray(Xtr), X_expected) def test_transform_selected(): X = [[3, 2, 1], [0, 1, 1]] X_expected = [[1, 2, 1], [0, 1, 1]] _check_transform_selected(X, X_expected, [0]) _check_transform_selected(X, X_expected, [True, False, False]) X_expected = [[1, 1, 1], [0, 1, 1]] _check_transform_selected(X, X_expected, [0, 1, 2]) _check_transform_selected(X, X_expected, [True, True, True]) _check_transform_selected(X, X_expected, "all") _check_transform_selected(X, X, []) _check_transform_selected(X, X, [False, False, False]) def _run_one_hot(X, X2, cat): enc = OneHotEncoder(categorical_features=cat) Xtr = enc.fit_transform(X) X2tr = enc.transform(X2) return Xtr, X2tr def _check_one_hot(X, X2, cat, n_features): ind = np.where(cat)[0] # With mask A, B = _run_one_hot(X, X2, cat) # With indices C, D = _run_one_hot(X, X2, ind) # Check shape assert_equal(A.shape, (2, n_features)) assert_equal(B.shape, (1, n_features)) assert_equal(C.shape, (2, n_features)) assert_equal(D.shape, (1, n_features)) # Check that mask and indices give the same results assert_array_equal(toarray(A), toarray(C)) assert_array_equal(toarray(B), toarray(D)) def test_one_hot_encoder_categorical_features(): X = np.array([[3, 2, 1], [0, 1, 1]]) X2 = np.array([[1, 1, 1]]) cat = [True, False, False] _check_one_hot(X, X2, cat, 4) # Edge case: all non-categorical cat = [False, False, False] _check_one_hot(X, X2, cat, 3) # Edge case: all categorical cat = [True, True, True] _check_one_hot(X, X2, cat, 5) def test_one_hot_encoder_unknown_transform(): X = np.array([[0, 2, 1], [1, 0, 3], [1, 0, 2]]) y = np.array([[4, 1, 1]]) # Test that one hot encoder raises error for unknown features # present during transform. oh = OneHotEncoder(handle_unknown='error') oh.fit(X) assert_raises(ValueError, oh.transform, y) # Test the ignore option, ignores unknown features. oh = OneHotEncoder(handle_unknown='ignore') oh.fit(X) assert_array_equal( oh.transform(y).toarray(), np.array([[0., 0., 0., 0., 1., 0., 0.]]) ) # Raise error if handle_unknown is neither ignore or error. oh = OneHotEncoder(handle_unknown='42') oh.fit(X) assert_raises(ValueError, oh.transform, y)
bsd-3-clause
AnasGhrab/scikit-learn
sklearn/metrics/tests/test_ranking.py
127
40813
from __future__ import division, print_function import numpy as np from itertools import product import warnings from scipy.sparse import csr_matrix from sklearn import datasets from sklearn import svm from sklearn import ensemble from sklearn.datasets import make_multilabel_classification from sklearn.random_projection import sparse_random_matrix from sklearn.utils.validation import check_array, check_consistent_length from sklearn.utils.validation import check_random_state from sklearn.utils.testing import assert_raises, clean_warning_registry from sklearn.utils.testing import assert_raise_message from sklearn.utils.testing import assert_equal 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_warns from sklearn.metrics import auc from sklearn.metrics import average_precision_score from sklearn.metrics import coverage_error from sklearn.metrics import label_ranking_average_precision_score from sklearn.metrics import precision_recall_curve from sklearn.metrics import label_ranking_loss from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_curve from sklearn.metrics.base import UndefinedMetricWarning ############################################################################### # Utilities for testing def make_prediction(dataset=None, binary=False): """Make some classification predictions on a toy dataset using a SVC If binary is True restrict to a binary classification problem instead of a multiclass classification problem """ if dataset is None: # import some data to play with dataset = datasets.load_iris() X = dataset.data y = dataset.target if binary: # restrict to a binary classification task X, y = X[y < 2], y[y < 2] n_samples, n_features = X.shape p = np.arange(n_samples) rng = check_random_state(37) rng.shuffle(p) X, y = X[p], y[p] half = int(n_samples / 2) # add noisy features to make the problem harder and avoid perfect results rng = np.random.RandomState(0) X = np.c_[X, rng.randn(n_samples, 200 * n_features)] # run classifier, get class probabilities and label predictions clf = svm.SVC(kernel='linear', probability=True, random_state=0) probas_pred = clf.fit(X[:half], y[:half]).predict_proba(X[half:]) if binary: # only interested in probabilities of the positive case # XXX: do we really want a special API for the binary case? probas_pred = probas_pred[:, 1] y_pred = clf.predict(X[half:]) y_true = y[half:] return y_true, y_pred, probas_pred ############################################################################### # Tests def _auc(y_true, y_score): """Alternative implementation to check for correctness of `roc_auc_score`.""" pos_label = np.unique(y_true)[1] # Count the number of times positive samples are correctly ranked above # negative samples. pos = y_score[y_true == pos_label] neg = y_score[y_true != pos_label] diff_matrix = pos.reshape(1, -1) - neg.reshape(-1, 1) n_correct = np.sum(diff_matrix > 0) return n_correct / float(len(pos) * len(neg)) def _average_precision(y_true, y_score): """Alternative implementation to check for correctness of `average_precision_score`.""" pos_label = np.unique(y_true)[1] n_pos = np.sum(y_true == pos_label) order = np.argsort(y_score)[::-1] y_score = y_score[order] y_true = y_true[order] score = 0 for i in range(len(y_score)): if y_true[i] == pos_label: # Compute precision up to document i # i.e, percentage of relevant documents up to document i. prec = 0 for j in range(0, i + 1): if y_true[j] == pos_label: prec += 1.0 prec /= (i + 1.0) score += prec return score / n_pos def test_roc_curve(): # Test Area under Receiver Operating Characteristic (ROC) curve y_true, _, probas_pred = make_prediction(binary=True) fpr, tpr, thresholds = roc_curve(y_true, probas_pred) roc_auc = auc(fpr, tpr) expected_auc = _auc(y_true, probas_pred) assert_array_almost_equal(roc_auc, expected_auc, decimal=2) assert_almost_equal(roc_auc, roc_auc_score(y_true, probas_pred)) assert_equal(fpr.shape, tpr.shape) assert_equal(fpr.shape, thresholds.shape) def test_roc_curve_end_points(): # Make sure that roc_curve returns a curve start at 0 and ending and # 1 even in corner cases rng = np.random.RandomState(0) y_true = np.array([0] * 50 + [1] * 50) y_pred = rng.randint(3, size=100) fpr, tpr, thr = roc_curve(y_true, y_pred) assert_equal(fpr[0], 0) assert_equal(fpr[-1], 1) assert_equal(fpr.shape, tpr.shape) assert_equal(fpr.shape, thr.shape) def test_roc_returns_consistency(): # Test whether the returned threshold matches up with tpr # make small toy dataset y_true, _, probas_pred = make_prediction(binary=True) fpr, tpr, thresholds = roc_curve(y_true, probas_pred) # use the given thresholds to determine the tpr tpr_correct = [] for t in thresholds: tp = np.sum((probas_pred >= t) & y_true) p = np.sum(y_true) tpr_correct.append(1.0 * tp / p) # compare tpr and tpr_correct to see if the thresholds' order was correct assert_array_almost_equal(tpr, tpr_correct, decimal=2) assert_equal(fpr.shape, tpr.shape) assert_equal(fpr.shape, thresholds.shape) def test_roc_nonrepeating_thresholds(): # Test to ensure that we don't return spurious repeating thresholds. # Duplicated thresholds can arise due to machine precision issues. dataset = datasets.load_digits() X = dataset['data'] y = dataset['target'] # This random forest classifier can only return probabilities # significant to two decimal places clf = ensemble.RandomForestClassifier(n_estimators=100, random_state=0) # How well can the classifier predict whether a digit is less than 5? # This task contributes floating point roundoff errors to the probabilities train, test = slice(None, None, 2), slice(1, None, 2) probas_pred = clf.fit(X[train], y[train]).predict_proba(X[test]) y_score = probas_pred[:, :5].sum(axis=1) # roundoff errors begin here y_true = [yy < 5 for yy in y[test]] # Check for repeating values in the thresholds fpr, tpr, thresholds = roc_curve(y_true, y_score) assert_equal(thresholds.size, np.unique(np.round(thresholds, 2)).size) def test_roc_curve_multi(): # roc_curve not applicable for multi-class problems y_true, _, probas_pred = make_prediction(binary=False) assert_raises(ValueError, roc_curve, y_true, probas_pred) def test_roc_curve_confidence(): # roc_curve for confidence scores y_true, _, probas_pred = make_prediction(binary=True) fpr, tpr, thresholds = roc_curve(y_true, probas_pred - 0.5) roc_auc = auc(fpr, tpr) assert_array_almost_equal(roc_auc, 0.90, decimal=2) assert_equal(fpr.shape, tpr.shape) assert_equal(fpr.shape, thresholds.shape) def test_roc_curve_hard(): # roc_curve for hard decisions y_true, pred, probas_pred = make_prediction(binary=True) # always predict one trivial_pred = np.ones(y_true.shape) fpr, tpr, thresholds = roc_curve(y_true, trivial_pred) roc_auc = auc(fpr, tpr) assert_array_almost_equal(roc_auc, 0.50, decimal=2) assert_equal(fpr.shape, tpr.shape) assert_equal(fpr.shape, thresholds.shape) # always predict zero trivial_pred = np.zeros(y_true.shape) fpr, tpr, thresholds = roc_curve(y_true, trivial_pred) roc_auc = auc(fpr, tpr) assert_array_almost_equal(roc_auc, 0.50, decimal=2) assert_equal(fpr.shape, tpr.shape) assert_equal(fpr.shape, thresholds.shape) # hard decisions fpr, tpr, thresholds = roc_curve(y_true, pred) roc_auc = auc(fpr, tpr) assert_array_almost_equal(roc_auc, 0.78, decimal=2) assert_equal(fpr.shape, tpr.shape) assert_equal(fpr.shape, thresholds.shape) def test_roc_curve_one_label(): y_true = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] y_pred = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1] # assert there are warnings w = UndefinedMetricWarning fpr, tpr, thresholds = assert_warns(w, roc_curve, y_true, y_pred) # all true labels, all fpr should be nan assert_array_equal(fpr, np.nan * np.ones(len(thresholds))) assert_equal(fpr.shape, tpr.shape) assert_equal(fpr.shape, thresholds.shape) # assert there are warnings fpr, tpr, thresholds = assert_warns(w, roc_curve, [1 - x for x in y_true], y_pred) # all negative labels, all tpr should be nan assert_array_equal(tpr, np.nan * np.ones(len(thresholds))) assert_equal(fpr.shape, tpr.shape) assert_equal(fpr.shape, thresholds.shape) def test_roc_curve_toydata(): # Binary classification y_true = [0, 1] y_score = [0, 1] tpr, fpr, _ = roc_curve(y_true, y_score) roc_auc = roc_auc_score(y_true, y_score) assert_array_almost_equal(tpr, [0, 1]) assert_array_almost_equal(fpr, [1, 1]) assert_almost_equal(roc_auc, 1.) y_true = [0, 1] y_score = [1, 0] tpr, fpr, _ = roc_curve(y_true, y_score) roc_auc = roc_auc_score(y_true, y_score) assert_array_almost_equal(tpr, [0, 1, 1]) assert_array_almost_equal(fpr, [0, 0, 1]) assert_almost_equal(roc_auc, 0.) y_true = [1, 0] y_score = [1, 1] tpr, fpr, _ = roc_curve(y_true, y_score) roc_auc = roc_auc_score(y_true, y_score) assert_array_almost_equal(tpr, [0, 1]) assert_array_almost_equal(fpr, [0, 1]) assert_almost_equal(roc_auc, 0.5) y_true = [1, 0] y_score = [1, 0] tpr, fpr, _ = roc_curve(y_true, y_score) roc_auc = roc_auc_score(y_true, y_score) assert_array_almost_equal(tpr, [0, 1]) assert_array_almost_equal(fpr, [1, 1]) assert_almost_equal(roc_auc, 1.) y_true = [1, 0] y_score = [0.5, 0.5] tpr, fpr, _ = roc_curve(y_true, y_score) roc_auc = roc_auc_score(y_true, y_score) assert_array_almost_equal(tpr, [0, 1]) assert_array_almost_equal(fpr, [0, 1]) assert_almost_equal(roc_auc, .5) y_true = [0, 0] y_score = [0.25, 0.75] tpr, fpr, _ = roc_curve(y_true, y_score) assert_raises(ValueError, roc_auc_score, y_true, y_score) assert_array_almost_equal(tpr, [0., 0.5, 1.]) assert_array_almost_equal(fpr, [np.nan, np.nan, np.nan]) y_true = [1, 1] y_score = [0.25, 0.75] tpr, fpr, _ = roc_curve(y_true, y_score) assert_raises(ValueError, roc_auc_score, y_true, y_score) assert_array_almost_equal(tpr, [np.nan, np.nan]) assert_array_almost_equal(fpr, [0.5, 1.]) # Multi-label classification task y_true = np.array([[0, 1], [0, 1]]) y_score = np.array([[0, 1], [0, 1]]) assert_raises(ValueError, roc_auc_score, y_true, y_score, average="macro") assert_raises(ValueError, roc_auc_score, y_true, y_score, average="weighted") assert_almost_equal(roc_auc_score(y_true, y_score, average="samples"), 1.) assert_almost_equal(roc_auc_score(y_true, y_score, average="micro"), 1.) y_true = np.array([[0, 1], [0, 1]]) y_score = np.array([[0, 1], [1, 0]]) assert_raises(ValueError, roc_auc_score, y_true, y_score, average="macro") assert_raises(ValueError, roc_auc_score, y_true, y_score, average="weighted") assert_almost_equal(roc_auc_score(y_true, y_score, average="samples"), 0.5) assert_almost_equal(roc_auc_score(y_true, y_score, average="micro"), 0.5) y_true = np.array([[1, 0], [0, 1]]) y_score = np.array([[0, 1], [1, 0]]) assert_almost_equal(roc_auc_score(y_true, y_score, average="macro"), 0) assert_almost_equal(roc_auc_score(y_true, y_score, average="weighted"), 0) assert_almost_equal(roc_auc_score(y_true, y_score, average="samples"), 0) assert_almost_equal(roc_auc_score(y_true, y_score, average="micro"), 0) y_true = np.array([[1, 0], [0, 1]]) y_score = np.array([[0.5, 0.5], [0.5, 0.5]]) assert_almost_equal(roc_auc_score(y_true, y_score, average="macro"), .5) assert_almost_equal(roc_auc_score(y_true, y_score, average="weighted"), .5) assert_almost_equal(roc_auc_score(y_true, y_score, average="samples"), .5) assert_almost_equal(roc_auc_score(y_true, y_score, average="micro"), .5) def test_auc(): # Test Area Under Curve (AUC) computation x = [0, 1] y = [0, 1] assert_array_almost_equal(auc(x, y), 0.5) x = [1, 0] y = [0, 1] assert_array_almost_equal(auc(x, y), 0.5) x = [1, 0, 0] y = [0, 1, 1] assert_array_almost_equal(auc(x, y), 0.5) x = [0, 1] y = [1, 1] assert_array_almost_equal(auc(x, y), 1) x = [0, 0.5, 1] y = [0, 0.5, 1] assert_array_almost_equal(auc(x, y), 0.5) def test_auc_duplicate_values(): # Test Area Under Curve (AUC) computation with duplicate values # auc() was previously sorting the x and y arrays according to the indices # from numpy.argsort(x), which was reordering the tied 0's in this example # and resulting in an incorrect area computation. This test detects the # error. x = [-2.0, 0.0, 0.0, 0.0, 1.0] y1 = [2.0, 0.0, 0.5, 1.0, 1.0] y2 = [2.0, 1.0, 0.0, 0.5, 1.0] y3 = [2.0, 1.0, 0.5, 0.0, 1.0] for y in (y1, y2, y3): assert_array_almost_equal(auc(x, y, reorder=True), 3.0) def test_auc_errors(): # Incompatible shapes assert_raises(ValueError, auc, [0.0, 0.5, 1.0], [0.1, 0.2]) # Too few x values assert_raises(ValueError, auc, [0.0], [0.1]) # x is not in order assert_raises(ValueError, auc, [1.0, 0.0, 0.5], [0.0, 0.0, 0.0]) def test_auc_score_non_binary_class(): # Test that roc_auc_score function returns an error when trying # to compute AUC for non-binary class values. rng = check_random_state(404) y_pred = rng.rand(10) # y_true contains only one class value y_true = np.zeros(10, dtype="int") assert_raise_message(ValueError, "ROC AUC score is not defined", roc_auc_score, y_true, y_pred) y_true = np.ones(10, dtype="int") assert_raise_message(ValueError, "ROC AUC score is not defined", roc_auc_score, y_true, y_pred) y_true = -np.ones(10, dtype="int") assert_raise_message(ValueError, "ROC AUC score is not defined", roc_auc_score, y_true, y_pred) # y_true contains three different class values y_true = rng.randint(0, 3, size=10) assert_raise_message(ValueError, "multiclass format is not supported", roc_auc_score, y_true, y_pred) clean_warning_registry() with warnings.catch_warnings(record=True): rng = check_random_state(404) y_pred = rng.rand(10) # y_true contains only one class value y_true = np.zeros(10, dtype="int") assert_raise_message(ValueError, "ROC AUC score is not defined", roc_auc_score, y_true, y_pred) y_true = np.ones(10, dtype="int") assert_raise_message(ValueError, "ROC AUC score is not defined", roc_auc_score, y_true, y_pred) y_true = -np.ones(10, dtype="int") assert_raise_message(ValueError, "ROC AUC score is not defined", roc_auc_score, y_true, y_pred) # y_true contains three different class values y_true = rng.randint(0, 3, size=10) assert_raise_message(ValueError, "multiclass format is not supported", roc_auc_score, y_true, y_pred) def test_precision_recall_curve(): y_true, _, probas_pred = make_prediction(binary=True) _test_precision_recall_curve(y_true, probas_pred) # Use {-1, 1} for labels; make sure original labels aren't modified y_true[np.where(y_true == 0)] = -1 y_true_copy = y_true.copy() _test_precision_recall_curve(y_true, probas_pred) assert_array_equal(y_true_copy, y_true) labels = [1, 0, 0, 1] predict_probas = [1, 2, 3, 4] p, r, t = precision_recall_curve(labels, predict_probas) assert_array_almost_equal(p, np.array([0.5, 0.33333333, 0.5, 1., 1.])) assert_array_almost_equal(r, np.array([1., 0.5, 0.5, 0.5, 0.])) assert_array_almost_equal(t, np.array([1, 2, 3, 4])) assert_equal(p.size, r.size) assert_equal(p.size, t.size + 1) def test_precision_recall_curve_pos_label(): y_true, _, probas_pred = make_prediction(binary=False) pos_label = 2 p, r, thresholds = precision_recall_curve(y_true, probas_pred[:, pos_label], pos_label=pos_label) p2, r2, thresholds2 = precision_recall_curve(y_true == pos_label, probas_pred[:, pos_label]) assert_array_almost_equal(p, p2) assert_array_almost_equal(r, r2) assert_array_almost_equal(thresholds, thresholds2) assert_equal(p.size, r.size) assert_equal(p.size, thresholds.size + 1) def _test_precision_recall_curve(y_true, probas_pred): # Test Precision-Recall and aread under PR curve p, r, thresholds = precision_recall_curve(y_true, probas_pred) precision_recall_auc = auc(r, p) assert_array_almost_equal(precision_recall_auc, 0.85, 2) assert_array_almost_equal(precision_recall_auc, average_precision_score(y_true, probas_pred)) assert_almost_equal(_average_precision(y_true, probas_pred), precision_recall_auc, 1) assert_equal(p.size, r.size) assert_equal(p.size, thresholds.size + 1) # Smoke test in the case of proba having only one value p, r, thresholds = precision_recall_curve(y_true, np.zeros_like(probas_pred)) precision_recall_auc = auc(r, p) assert_array_almost_equal(precision_recall_auc, 0.75, 3) assert_equal(p.size, r.size) assert_equal(p.size, thresholds.size + 1) def test_precision_recall_curve_errors(): # Contains non-binary labels assert_raises(ValueError, precision_recall_curve, [0, 1, 2], [[0.0], [1.0], [1.0]]) def test_precision_recall_curve_toydata(): with np.errstate(all="raise"): # Binary classification y_true = [0, 1] y_score = [0, 1] p, r, _ = precision_recall_curve(y_true, y_score) auc_prc = average_precision_score(y_true, y_score) assert_array_almost_equal(p, [1, 1]) assert_array_almost_equal(r, [1, 0]) assert_almost_equal(auc_prc, 1.) y_true = [0, 1] y_score = [1, 0] p, r, _ = precision_recall_curve(y_true, y_score) auc_prc = average_precision_score(y_true, y_score) assert_array_almost_equal(p, [0.5, 0., 1.]) assert_array_almost_equal(r, [1., 0., 0.]) assert_almost_equal(auc_prc, 0.25) y_true = [1, 0] y_score = [1, 1] p, r, _ = precision_recall_curve(y_true, y_score) auc_prc = average_precision_score(y_true, y_score) assert_array_almost_equal(p, [0.5, 1]) assert_array_almost_equal(r, [1., 0]) assert_almost_equal(auc_prc, .75) y_true = [1, 0] y_score = [1, 0] p, r, _ = precision_recall_curve(y_true, y_score) auc_prc = average_precision_score(y_true, y_score) assert_array_almost_equal(p, [1, 1]) assert_array_almost_equal(r, [1, 0]) assert_almost_equal(auc_prc, 1.) y_true = [1, 0] y_score = [0.5, 0.5] p, r, _ = precision_recall_curve(y_true, y_score) auc_prc = average_precision_score(y_true, y_score) assert_array_almost_equal(p, [0.5, 1]) assert_array_almost_equal(r, [1, 0.]) assert_almost_equal(auc_prc, .75) y_true = [0, 0] y_score = [0.25, 0.75] assert_raises(Exception, precision_recall_curve, y_true, y_score) assert_raises(Exception, average_precision_score, y_true, y_score) y_true = [1, 1] y_score = [0.25, 0.75] p, r, _ = precision_recall_curve(y_true, y_score) assert_almost_equal(average_precision_score(y_true, y_score), 1.) assert_array_almost_equal(p, [1., 1., 1.]) assert_array_almost_equal(r, [1, 0.5, 0.]) # Multi-label classification task y_true = np.array([[0, 1], [0, 1]]) y_score = np.array([[0, 1], [0, 1]]) assert_raises(Exception, average_precision_score, y_true, y_score, average="macro") assert_raises(Exception, average_precision_score, y_true, y_score, average="weighted") assert_almost_equal(average_precision_score(y_true, y_score, average="samples"), 1.) assert_almost_equal(average_precision_score(y_true, y_score, average="micro"), 1.) y_true = np.array([[0, 1], [0, 1]]) y_score = np.array([[0, 1], [1, 0]]) assert_raises(Exception, average_precision_score, y_true, y_score, average="macro") assert_raises(Exception, average_precision_score, y_true, y_score, average="weighted") assert_almost_equal(average_precision_score(y_true, y_score, average="samples"), 0.625) assert_almost_equal(average_precision_score(y_true, y_score, average="micro"), 0.625) y_true = np.array([[1, 0], [0, 1]]) y_score = np.array([[0, 1], [1, 0]]) assert_almost_equal(average_precision_score(y_true, y_score, average="macro"), 0.25) assert_almost_equal(average_precision_score(y_true, y_score, average="weighted"), 0.25) assert_almost_equal(average_precision_score(y_true, y_score, average="samples"), 0.25) assert_almost_equal(average_precision_score(y_true, y_score, average="micro"), 0.25) y_true = np.array([[1, 0], [0, 1]]) y_score = np.array([[0.5, 0.5], [0.5, 0.5]]) assert_almost_equal(average_precision_score(y_true, y_score, average="macro"), 0.75) assert_almost_equal(average_precision_score(y_true, y_score, average="weighted"), 0.75) assert_almost_equal(average_precision_score(y_true, y_score, average="samples"), 0.75) assert_almost_equal(average_precision_score(y_true, y_score, average="micro"), 0.75) def test_score_scale_invariance(): # Test that average_precision_score and roc_auc_score are invariant by # the scaling or shifting of probabilities y_true, _, probas_pred = make_prediction(binary=True) roc_auc = roc_auc_score(y_true, probas_pred) roc_auc_scaled = roc_auc_score(y_true, 100 * probas_pred) roc_auc_shifted = roc_auc_score(y_true, probas_pred - 10) assert_equal(roc_auc, roc_auc_scaled) assert_equal(roc_auc, roc_auc_shifted) pr_auc = average_precision_score(y_true, probas_pred) pr_auc_scaled = average_precision_score(y_true, 100 * probas_pred) pr_auc_shifted = average_precision_score(y_true, probas_pred - 10) assert_equal(pr_auc, pr_auc_scaled) assert_equal(pr_auc, pr_auc_shifted) def check_lrap_toy(lrap_score): # Check on several small example that it works assert_almost_equal(lrap_score([[0, 1]], [[0.25, 0.75]]), 1) assert_almost_equal(lrap_score([[0, 1]], [[0.75, 0.25]]), 1 / 2) assert_almost_equal(lrap_score([[1, 1]], [[0.75, 0.25]]), 1) assert_almost_equal(lrap_score([[0, 0, 1]], [[0.25, 0.5, 0.75]]), 1) assert_almost_equal(lrap_score([[0, 1, 0]], [[0.25, 0.5, 0.75]]), 1 / 2) assert_almost_equal(lrap_score([[0, 1, 1]], [[0.25, 0.5, 0.75]]), 1) assert_almost_equal(lrap_score([[1, 0, 0]], [[0.25, 0.5, 0.75]]), 1 / 3) assert_almost_equal(lrap_score([[1, 0, 1]], [[0.25, 0.5, 0.75]]), (2 / 3 + 1 / 1) / 2) assert_almost_equal(lrap_score([[1, 1, 0]], [[0.25, 0.5, 0.75]]), (2 / 3 + 1 / 2) / 2) assert_almost_equal(lrap_score([[0, 0, 1]], [[0.75, 0.5, 0.25]]), 1 / 3) assert_almost_equal(lrap_score([[0, 1, 0]], [[0.75, 0.5, 0.25]]), 1 / 2) assert_almost_equal(lrap_score([[0, 1, 1]], [[0.75, 0.5, 0.25]]), (1 / 2 + 2 / 3) / 2) assert_almost_equal(lrap_score([[1, 0, 0]], [[0.75, 0.5, 0.25]]), 1) assert_almost_equal(lrap_score([[1, 0, 1]], [[0.75, 0.5, 0.25]]), (1 + 2 / 3) / 2) assert_almost_equal(lrap_score([[1, 1, 0]], [[0.75, 0.5, 0.25]]), 1) assert_almost_equal(lrap_score([[1, 1, 1]], [[0.75, 0.5, 0.25]]), 1) assert_almost_equal(lrap_score([[0, 0, 1]], [[0.5, 0.75, 0.25]]), 1 / 3) assert_almost_equal(lrap_score([[0, 1, 0]], [[0.5, 0.75, 0.25]]), 1) assert_almost_equal(lrap_score([[0, 1, 1]], [[0.5, 0.75, 0.25]]), (1 + 2 / 3) / 2) assert_almost_equal(lrap_score([[1, 0, 0]], [[0.5, 0.75, 0.25]]), 1 / 2) assert_almost_equal(lrap_score([[1, 0, 1]], [[0.5, 0.75, 0.25]]), (1 / 2 + 2 / 3) / 2) assert_almost_equal(lrap_score([[1, 1, 0]], [[0.5, 0.75, 0.25]]), 1) assert_almost_equal(lrap_score([[1, 1, 1]], [[0.5, 0.75, 0.25]]), 1) # Tie handling assert_almost_equal(lrap_score([[1, 0]], [[0.5, 0.5]]), 0.5) assert_almost_equal(lrap_score([[0, 1]], [[0.5, 0.5]]), 0.5) assert_almost_equal(lrap_score([[1, 1]], [[0.5, 0.5]]), 1) assert_almost_equal(lrap_score([[0, 0, 1]], [[0.25, 0.5, 0.5]]), 0.5) assert_almost_equal(lrap_score([[0, 1, 0]], [[0.25, 0.5, 0.5]]), 0.5) assert_almost_equal(lrap_score([[0, 1, 1]], [[0.25, 0.5, 0.5]]), 1) assert_almost_equal(lrap_score([[1, 0, 0]], [[0.25, 0.5, 0.5]]), 1 / 3) assert_almost_equal(lrap_score([[1, 0, 1]], [[0.25, 0.5, 0.5]]), (2 / 3 + 1 / 2) / 2) assert_almost_equal(lrap_score([[1, 1, 0]], [[0.25, 0.5, 0.5]]), (2 / 3 + 1 / 2) / 2) assert_almost_equal(lrap_score([[1, 1, 1]], [[0.25, 0.5, 0.5]]), 1) assert_almost_equal(lrap_score([[1, 1, 0]], [[0.5, 0.5, 0.5]]), 2 / 3) assert_almost_equal(lrap_score([[1, 1, 1, 0]], [[0.5, 0.5, 0.5, 0.5]]), 3 / 4) def check_zero_or_all_relevant_labels(lrap_score): random_state = check_random_state(0) for n_labels in range(2, 5): y_score = random_state.uniform(size=(1, n_labels)) y_score_ties = np.zeros_like(y_score) # No relevant labels y_true = np.zeros((1, n_labels)) assert_equal(lrap_score(y_true, y_score), 1.) assert_equal(lrap_score(y_true, y_score_ties), 1.) # Only relevant labels y_true = np.ones((1, n_labels)) assert_equal(lrap_score(y_true, y_score), 1.) assert_equal(lrap_score(y_true, y_score_ties), 1.) # Degenerate case: only one label assert_almost_equal(lrap_score([[1], [0], [1], [0]], [[0.5], [0.5], [0.5], [0.5]]), 1.) def check_lrap_error_raised(lrap_score): # Raise value error if not appropriate format assert_raises(ValueError, lrap_score, [0, 1, 0], [0.25, 0.3, 0.2]) assert_raises(ValueError, lrap_score, [0, 1, 2], [[0.25, 0.75, 0.0], [0.7, 0.3, 0.0], [0.8, 0.2, 0.0]]) assert_raises(ValueError, lrap_score, [(0), (1), (2)], [[0.25, 0.75, 0.0], [0.7, 0.3, 0.0], [0.8, 0.2, 0.0]]) # Check that that y_true.shape != y_score.shape raise the proper exception assert_raises(ValueError, lrap_score, [[0, 1], [0, 1]], [0, 1]) assert_raises(ValueError, lrap_score, [[0, 1], [0, 1]], [[0, 1]]) assert_raises(ValueError, lrap_score, [[0, 1], [0, 1]], [[0], [1]]) assert_raises(ValueError, lrap_score, [[0, 1]], [[0, 1], [0, 1]]) assert_raises(ValueError, lrap_score, [[0], [1]], [[0, 1], [0, 1]]) assert_raises(ValueError, lrap_score, [[0, 1], [0, 1]], [[0], [1]]) def check_lrap_only_ties(lrap_score): # Check tie handling in score # Basic check with only ties and increasing label space for n_labels in range(2, 10): y_score = np.ones((1, n_labels)) # Check for growing number of consecutive relevant for n_relevant in range(1, n_labels): # Check for a bunch of positions for pos in range(n_labels - n_relevant): y_true = np.zeros((1, n_labels)) y_true[0, pos:pos + n_relevant] = 1 assert_almost_equal(lrap_score(y_true, y_score), n_relevant / n_labels) def check_lrap_without_tie_and_increasing_score(lrap_score): # Check that Label ranking average precision works for various # Basic check with increasing label space size and decreasing score for n_labels in range(2, 10): y_score = n_labels - (np.arange(n_labels).reshape((1, n_labels)) + 1) # First and last y_true = np.zeros((1, n_labels)) y_true[0, 0] = 1 y_true[0, -1] = 1 assert_almost_equal(lrap_score(y_true, y_score), (2 / n_labels + 1) / 2) # Check for growing number of consecutive relevant label for n_relevant in range(1, n_labels): # Check for a bunch of position for pos in range(n_labels - n_relevant): y_true = np.zeros((1, n_labels)) y_true[0, pos:pos + n_relevant] = 1 assert_almost_equal(lrap_score(y_true, y_score), sum((r + 1) / ((pos + r + 1) * n_relevant) for r in range(n_relevant))) def _my_lrap(y_true, y_score): """Simple implementation of label ranking average precision""" check_consistent_length(y_true, y_score) y_true = check_array(y_true) y_score = check_array(y_score) n_samples, n_labels = y_true.shape score = np.empty((n_samples, )) for i in range(n_samples): # The best rank correspond to 1. Rank higher than 1 are worse. # The best inverse ranking correspond to n_labels. unique_rank, inv_rank = np.unique(y_score[i], return_inverse=True) n_ranks = unique_rank.size rank = n_ranks - inv_rank # Rank need to be corrected to take into account ties # ex: rank 1 ex aequo means that both label are rank 2. corr_rank = np.bincount(rank, minlength=n_ranks + 1).cumsum() rank = corr_rank[rank] relevant = y_true[i].nonzero()[0] if relevant.size == 0 or relevant.size == n_labels: score[i] = 1 continue score[i] = 0. for label in relevant: # Let's count the number of relevant label with better rank # (smaller rank). n_ranked_above = sum(rank[r] <= rank[label] for r in relevant) # Weight by the rank of the actual label score[i] += n_ranked_above / rank[label] score[i] /= relevant.size return score.mean() def check_alternative_lrap_implementation(lrap_score, n_classes=5, n_samples=20, random_state=0): _, y_true = make_multilabel_classification(n_features=1, allow_unlabeled=False, random_state=random_state, n_classes=n_classes, n_samples=n_samples) # Score with ties y_score = sparse_random_matrix(n_components=y_true.shape[0], n_features=y_true.shape[1], random_state=random_state) if hasattr(y_score, "toarray"): y_score = y_score.toarray() score_lrap = label_ranking_average_precision_score(y_true, y_score) score_my_lrap = _my_lrap(y_true, y_score) assert_almost_equal(score_lrap, score_my_lrap) # Uniform score random_state = check_random_state(random_state) y_score = random_state.uniform(size=(n_samples, n_classes)) score_lrap = label_ranking_average_precision_score(y_true, y_score) score_my_lrap = _my_lrap(y_true, y_score) assert_almost_equal(score_lrap, score_my_lrap) def test_label_ranking_avp(): for fn in [label_ranking_average_precision_score, _my_lrap]: yield check_lrap_toy, fn yield check_lrap_without_tie_and_increasing_score, fn yield check_lrap_only_ties, fn yield check_zero_or_all_relevant_labels, fn yield check_lrap_error_raised, label_ranking_average_precision_score for n_samples, n_classes, random_state in product((1, 2, 8, 20), (2, 5, 10), range(1)): yield (check_alternative_lrap_implementation, label_ranking_average_precision_score, n_classes, n_samples, random_state) def test_coverage_error(): # Toy case assert_almost_equal(coverage_error([[0, 1]], [[0.25, 0.75]]), 1) assert_almost_equal(coverage_error([[0, 1]], [[0.75, 0.25]]), 2) assert_almost_equal(coverage_error([[1, 1]], [[0.75, 0.25]]), 2) assert_almost_equal(coverage_error([[0, 0]], [[0.75, 0.25]]), 0) assert_almost_equal(coverage_error([[0, 0, 0]], [[0.25, 0.5, 0.75]]), 0) assert_almost_equal(coverage_error([[0, 0, 1]], [[0.25, 0.5, 0.75]]), 1) assert_almost_equal(coverage_error([[0, 1, 0]], [[0.25, 0.5, 0.75]]), 2) assert_almost_equal(coverage_error([[0, 1, 1]], [[0.25, 0.5, 0.75]]), 2) assert_almost_equal(coverage_error([[1, 0, 0]], [[0.25, 0.5, 0.75]]), 3) assert_almost_equal(coverage_error([[1, 0, 1]], [[0.25, 0.5, 0.75]]), 3) assert_almost_equal(coverage_error([[1, 1, 0]], [[0.25, 0.5, 0.75]]), 3) assert_almost_equal(coverage_error([[1, 1, 1]], [[0.25, 0.5, 0.75]]), 3) assert_almost_equal(coverage_error([[0, 0, 0]], [[0.75, 0.5, 0.25]]), 0) assert_almost_equal(coverage_error([[0, 0, 1]], [[0.75, 0.5, 0.25]]), 3) assert_almost_equal(coverage_error([[0, 1, 0]], [[0.75, 0.5, 0.25]]), 2) assert_almost_equal(coverage_error([[0, 1, 1]], [[0.75, 0.5, 0.25]]), 3) assert_almost_equal(coverage_error([[1, 0, 0]], [[0.75, 0.5, 0.25]]), 1) assert_almost_equal(coverage_error([[1, 0, 1]], [[0.75, 0.5, 0.25]]), 3) assert_almost_equal(coverage_error([[1, 1, 0]], [[0.75, 0.5, 0.25]]), 2) assert_almost_equal(coverage_error([[1, 1, 1]], [[0.75, 0.5, 0.25]]), 3) assert_almost_equal(coverage_error([[0, 0, 0]], [[0.5, 0.75, 0.25]]), 0) assert_almost_equal(coverage_error([[0, 0, 1]], [[0.5, 0.75, 0.25]]), 3) assert_almost_equal(coverage_error([[0, 1, 0]], [[0.5, 0.75, 0.25]]), 1) assert_almost_equal(coverage_error([[0, 1, 1]], [[0.5, 0.75, 0.25]]), 3) assert_almost_equal(coverage_error([[1, 0, 0]], [[0.5, 0.75, 0.25]]), 2) assert_almost_equal(coverage_error([[1, 0, 1]], [[0.5, 0.75, 0.25]]), 3) assert_almost_equal(coverage_error([[1, 1, 0]], [[0.5, 0.75, 0.25]]), 2) assert_almost_equal(coverage_error([[1, 1, 1]], [[0.5, 0.75, 0.25]]), 3) # Non trival case assert_almost_equal(coverage_error([[0, 1, 0], [1, 1, 0]], [[0.1, 10., -3], [0, 1, 3]]), (1 + 3) / 2.) assert_almost_equal(coverage_error([[0, 1, 0], [1, 1, 0], [0, 1, 1]], [[0.1, 10, -3], [0, 1, 3], [0, 2, 0]]), (1 + 3 + 3) / 3.) assert_almost_equal(coverage_error([[0, 1, 0], [1, 1, 0], [0, 1, 1]], [[0.1, 10, -3], [3, 1, 3], [0, 2, 0]]), (1 + 3 + 3) / 3.) def test_coverage_tie_handling(): assert_almost_equal(coverage_error([[0, 0]], [[0.5, 0.5]]), 0) assert_almost_equal(coverage_error([[1, 0]], [[0.5, 0.5]]), 2) assert_almost_equal(coverage_error([[0, 1]], [[0.5, 0.5]]), 2) assert_almost_equal(coverage_error([[1, 1]], [[0.5, 0.5]]), 2) assert_almost_equal(coverage_error([[0, 0, 0]], [[0.25, 0.5, 0.5]]), 0) assert_almost_equal(coverage_error([[0, 0, 1]], [[0.25, 0.5, 0.5]]), 2) assert_almost_equal(coverage_error([[0, 1, 0]], [[0.25, 0.5, 0.5]]), 2) assert_almost_equal(coverage_error([[0, 1, 1]], [[0.25, 0.5, 0.5]]), 2) assert_almost_equal(coverage_error([[1, 0, 0]], [[0.25, 0.5, 0.5]]), 3) assert_almost_equal(coverage_error([[1, 0, 1]], [[0.25, 0.5, 0.5]]), 3) assert_almost_equal(coverage_error([[1, 1, 0]], [[0.25, 0.5, 0.5]]), 3) assert_almost_equal(coverage_error([[1, 1, 1]], [[0.25, 0.5, 0.5]]), 3) def test_label_ranking_loss(): assert_almost_equal(label_ranking_loss([[0, 1]], [[0.25, 0.75]]), 0) assert_almost_equal(label_ranking_loss([[0, 1]], [[0.75, 0.25]]), 1) assert_almost_equal(label_ranking_loss([[0, 0, 1]], [[0.25, 0.5, 0.75]]), 0) assert_almost_equal(label_ranking_loss([[0, 1, 0]], [[0.25, 0.5, 0.75]]), 1 / 2) assert_almost_equal(label_ranking_loss([[0, 1, 1]], [[0.25, 0.5, 0.75]]), 0) assert_almost_equal(label_ranking_loss([[1, 0, 0]], [[0.25, 0.5, 0.75]]), 2 / 2) assert_almost_equal(label_ranking_loss([[1, 0, 1]], [[0.25, 0.5, 0.75]]), 1 / 2) assert_almost_equal(label_ranking_loss([[1, 1, 0]], [[0.25, 0.5, 0.75]]), 2 / 2) # Undefined metrics - the ranking doesn't matter assert_almost_equal(label_ranking_loss([[0, 0]], [[0.75, 0.25]]), 0) assert_almost_equal(label_ranking_loss([[1, 1]], [[0.75, 0.25]]), 0) assert_almost_equal(label_ranking_loss([[0, 0]], [[0.5, 0.5]]), 0) assert_almost_equal(label_ranking_loss([[1, 1]], [[0.5, 0.5]]), 0) assert_almost_equal(label_ranking_loss([[0, 0, 0]], [[0.5, 0.75, 0.25]]), 0) assert_almost_equal(label_ranking_loss([[1, 1, 1]], [[0.5, 0.75, 0.25]]), 0) assert_almost_equal(label_ranking_loss([[0, 0, 0]], [[0.25, 0.5, 0.5]]), 0) assert_almost_equal(label_ranking_loss([[1, 1, 1]], [[0.25, 0.5, 0.5]]), 0) # Non trival case assert_almost_equal(label_ranking_loss([[0, 1, 0], [1, 1, 0]], [[0.1, 10., -3], [0, 1, 3]]), (0 + 2 / 2) / 2.) assert_almost_equal(label_ranking_loss( [[0, 1, 0], [1, 1, 0], [0, 1, 1]], [[0.1, 10, -3], [0, 1, 3], [0, 2, 0]]), (0 + 2 / 2 + 1 / 2) / 3.) assert_almost_equal(label_ranking_loss( [[0, 1, 0], [1, 1, 0], [0, 1, 1]], [[0.1, 10, -3], [3, 1, 3], [0, 2, 0]]), (0 + 2 / 2 + 1 / 2) / 3.) # Sparse csr matrices assert_almost_equal(label_ranking_loss( csr_matrix(np.array([[0, 1, 0], [1, 1, 0]])), [[0.1, 10, -3], [3, 1, 3]]), (0 + 2 / 2) / 2.) def test_ranking_appropriate_input_shape(): # Check that that y_true.shape != y_score.shape raise the proper exception assert_raises(ValueError, label_ranking_loss, [[0, 1], [0, 1]], [0, 1]) assert_raises(ValueError, label_ranking_loss, [[0, 1], [0, 1]], [[0, 1]]) assert_raises(ValueError, label_ranking_loss, [[0, 1], [0, 1]], [[0], [1]]) assert_raises(ValueError, label_ranking_loss, [[0, 1]], [[0, 1], [0, 1]]) assert_raises(ValueError, label_ranking_loss, [[0], [1]], [[0, 1], [0, 1]]) assert_raises(ValueError, label_ranking_loss, [[0, 1], [0, 1]], [[0], [1]]) def test_ranking_loss_ties_handling(): # Tie handling assert_almost_equal(label_ranking_loss([[1, 0]], [[0.5, 0.5]]), 1) assert_almost_equal(label_ranking_loss([[0, 1]], [[0.5, 0.5]]), 1) assert_almost_equal(label_ranking_loss([[0, 0, 1]], [[0.25, 0.5, 0.5]]), 1 / 2) assert_almost_equal(label_ranking_loss([[0, 1, 0]], [[0.25, 0.5, 0.5]]), 1 / 2) assert_almost_equal(label_ranking_loss([[0, 1, 1]], [[0.25, 0.5, 0.5]]), 0) assert_almost_equal(label_ranking_loss([[1, 0, 0]], [[0.25, 0.5, 0.5]]), 1) assert_almost_equal(label_ranking_loss([[1, 0, 1]], [[0.25, 0.5, 0.5]]), 1) assert_almost_equal(label_ranking_loss([[1, 1, 0]], [[0.25, 0.5, 0.5]]), 1)
bsd-3-clause
cybernet14/scikit-learn
examples/svm/plot_oneclass.py
249
2302
""" ========================================== One-class SVM with non-linear kernel (RBF) ========================================== An example using a one-class SVM for novelty detection. :ref:`One-class SVM <svm_outlier_detection>` is an unsupervised algorithm that learns a decision function for novelty detection: classifying new data as similar or different to the training set. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt import matplotlib.font_manager from sklearn import svm xx, yy = np.meshgrid(np.linspace(-5, 5, 500), np.linspace(-5, 5, 500)) # Generate train data X = 0.3 * np.random.randn(100, 2) X_train = np.r_[X + 2, X - 2] # Generate some regular novel observations X = 0.3 * np.random.randn(20, 2) X_test = np.r_[X + 2, X - 2] # Generate some abnormal novel observations X_outliers = np.random.uniform(low=-4, high=4, size=(20, 2)) # fit the model clf = svm.OneClassSVM(nu=0.1, kernel="rbf", gamma=0.1) clf.fit(X_train) y_pred_train = clf.predict(X_train) y_pred_test = clf.predict(X_test) y_pred_outliers = clf.predict(X_outliers) n_error_train = y_pred_train[y_pred_train == -1].size n_error_test = y_pred_test[y_pred_test == -1].size n_error_outliers = y_pred_outliers[y_pred_outliers == 1].size # plot the line, the points, and the nearest vectors to the plane Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) plt.title("Novelty Detection") plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), 0, 7), cmap=plt.cm.Blues_r) a = plt.contour(xx, yy, Z, levels=[0], linewidths=2, colors='red') plt.contourf(xx, yy, Z, levels=[0, Z.max()], colors='orange') b1 = plt.scatter(X_train[:, 0], X_train[:, 1], c='white') b2 = plt.scatter(X_test[:, 0], X_test[:, 1], c='green') c = plt.scatter(X_outliers[:, 0], X_outliers[:, 1], c='red') plt.axis('tight') plt.xlim((-5, 5)) plt.ylim((-5, 5)) plt.legend([a.collections[0], b1, b2, c], ["learned frontier", "training observations", "new regular observations", "new abnormal observations"], loc="upper left", prop=matplotlib.font_manager.FontProperties(size=11)) plt.xlabel( "error train: %d/200 ; errors novel regular: %d/40 ; " "errors novel abnormal: %d/40" % (n_error_train, n_error_test, n_error_outliers)) plt.show()
bsd-3-clause
DhiruPranav/data-science-from-scratch
code/gradient_descent.py
53
5895
from __future__ import division from collections import Counter from linear_algebra import distance, vector_subtract, scalar_multiply import math, random def sum_of_squares(v): """computes the sum of squared elements in v""" return sum(v_i ** 2 for v_i in v) def difference_quotient(f, x, h): return (f(x + h) - f(x)) / h def plot_estimated_derivative(): def square(x): return x * x def derivative(x): return 2 * x derivative_estimate = lambda x: difference_quotient(square, x, h=0.00001) # plot to show they're basically the same import matplotlib.pyplot as plt x = range(-10,10) plt.plot(x, map(derivative, x), 'rx') # red x plt.plot(x, map(derivative_estimate, x), 'b+') # blue + plt.show() # purple *, hopefully def partial_difference_quotient(f, v, i, h): # add h to just the i-th element of v w = [v_j + (h if j == i else 0) for j, v_j in enumerate(v)] return (f(w) - f(v)) / h def estimate_gradient(f, v, h=0.00001): return [partial_difference_quotient(f, v, i, h) for i, _ in enumerate(v)] def step(v, direction, step_size): """move step_size in the direction from v""" return [v_i + step_size * direction_i for v_i, direction_i in zip(v, direction)] def sum_of_squares_gradient(v): return [2 * v_i for v_i in v] def safe(f): """define a new function that wraps f and return it""" def safe_f(*args, **kwargs): try: return f(*args, **kwargs) except: return float('inf') # this means "infinity" in Python return safe_f # # # minimize / maximize batch # # def minimize_batch(target_fn, gradient_fn, theta_0, tolerance=0.000001): """use gradient descent to find theta that minimizes target function""" step_sizes = [100, 10, 1, 0.1, 0.01, 0.001, 0.0001, 0.00001] theta = theta_0 # set theta to initial value target_fn = safe(target_fn) # safe version of target_fn value = target_fn(theta) # value we're minimizing while True: gradient = gradient_fn(theta) next_thetas = [step(theta, gradient, -step_size) for step_size in step_sizes] # choose the one that minimizes the error function next_theta = min(next_thetas, key=target_fn) next_value = target_fn(next_theta) # stop if we're "converging" if abs(value - next_value) < tolerance: return theta else: theta, value = next_theta, next_value def negate(f): """return a function that for any input x returns -f(x)""" return lambda *args, **kwargs: -f(*args, **kwargs) def negate_all(f): """the same when f returns a list of numbers""" return lambda *args, **kwargs: [-y for y in f(*args, **kwargs)] def maximize_batch(target_fn, gradient_fn, theta_0, tolerance=0.000001): return minimize_batch(negate(target_fn), negate_all(gradient_fn), theta_0, tolerance) # # minimize / maximize stochastic # def in_random_order(data): """generator that returns the elements of data in random order""" indexes = [i for i, _ in enumerate(data)] # create a list of indexes random.shuffle(indexes) # shuffle them for i in indexes: # return the data in that order yield data[i] def minimize_stochastic(target_fn, gradient_fn, x, y, theta_0, alpha_0=0.01): data = zip(x, y) theta = theta_0 # initial guess alpha = alpha_0 # initial step size min_theta, min_value = None, float("inf") # the minimum so far iterations_with_no_improvement = 0 # if we ever go 100 iterations with no improvement, stop while iterations_with_no_improvement < 100: value = sum( target_fn(x_i, y_i, theta) for x_i, y_i in data ) if value < min_value: # if we've found a new minimum, remember it # and go back to the original step size min_theta, min_value = theta, value iterations_with_no_improvement = 0 alpha = alpha_0 else: # otherwise we're not improving, so try shrinking the step size iterations_with_no_improvement += 1 alpha *= 0.9 # and take a gradient step for each of the data points for x_i, y_i in in_random_order(data): gradient_i = gradient_fn(x_i, y_i, theta) theta = vector_subtract(theta, scalar_multiply(alpha, gradient_i)) return min_theta def maximize_stochastic(target_fn, gradient_fn, x, y, theta_0, alpha_0=0.01): return minimize_stochastic(negate(target_fn), negate_all(gradient_fn), x, y, theta_0, alpha_0) if __name__ == "__main__": print "using the gradient" v = [random.randint(-10,10) for i in range(3)] tolerance = 0.0000001 while True: #print v, sum_of_squares(v) gradient = sum_of_squares_gradient(v) # compute the gradient at v next_v = step(v, gradient, -0.01) # take a negative gradient step if distance(next_v, v) < tolerance: # stop if we're converging break v = next_v # continue if we're not print "minimum v", v print "minimum value", sum_of_squares(v) print print "using minimize_batch" v = [random.randint(-10,10) for i in range(3)] v = minimize_batch(sum_of_squares, sum_of_squares_gradient, v) print "minimum v", v print "minimum value", sum_of_squares(v)
unlicense
thientu/scikit-learn
sklearn/linear_model/tests/test_omp.py
272
7752
# Author: Vlad Niculae # Licence: BSD 3 clause import numpy as np from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_true 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 assert_warns from sklearn.utils.testing import ignore_warnings from sklearn.linear_model import (orthogonal_mp, orthogonal_mp_gram, OrthogonalMatchingPursuit, OrthogonalMatchingPursuitCV, LinearRegression) from sklearn.utils import check_random_state from sklearn.datasets import make_sparse_coded_signal n_samples, n_features, n_nonzero_coefs, n_targets = 20, 30, 5, 3 y, X, gamma = make_sparse_coded_signal(n_targets, n_features, n_samples, n_nonzero_coefs, random_state=0) G, Xy = np.dot(X.T, X), np.dot(X.T, y) # this makes X (n_samples, n_features) # and y (n_samples, 3) def test_correct_shapes(): assert_equal(orthogonal_mp(X, y[:, 0], n_nonzero_coefs=5).shape, (n_features,)) assert_equal(orthogonal_mp(X, y, n_nonzero_coefs=5).shape, (n_features, 3)) def test_correct_shapes_gram(): assert_equal(orthogonal_mp_gram(G, Xy[:, 0], n_nonzero_coefs=5).shape, (n_features,)) assert_equal(orthogonal_mp_gram(G, Xy, n_nonzero_coefs=5).shape, (n_features, 3)) def test_n_nonzero_coefs(): assert_true(np.count_nonzero(orthogonal_mp(X, y[:, 0], n_nonzero_coefs=5)) <= 5) assert_true(np.count_nonzero(orthogonal_mp(X, y[:, 0], n_nonzero_coefs=5, precompute=True)) <= 5) def test_tol(): tol = 0.5 gamma = orthogonal_mp(X, y[:, 0], tol=tol) gamma_gram = orthogonal_mp(X, y[:, 0], tol=tol, precompute=True) assert_true(np.sum((y[:, 0] - np.dot(X, gamma)) ** 2) <= tol) assert_true(np.sum((y[:, 0] - np.dot(X, gamma_gram)) ** 2) <= tol) def test_with_without_gram(): assert_array_almost_equal( orthogonal_mp(X, y, n_nonzero_coefs=5), orthogonal_mp(X, y, n_nonzero_coefs=5, precompute=True)) def test_with_without_gram_tol(): assert_array_almost_equal( orthogonal_mp(X, y, tol=1.), orthogonal_mp(X, y, tol=1., precompute=True)) def test_unreachable_accuracy(): assert_array_almost_equal( orthogonal_mp(X, y, tol=0), orthogonal_mp(X, y, n_nonzero_coefs=n_features)) assert_array_almost_equal( assert_warns(RuntimeWarning, orthogonal_mp, X, y, tol=0, precompute=True), orthogonal_mp(X, y, precompute=True, n_nonzero_coefs=n_features)) def test_bad_input(): assert_raises(ValueError, orthogonal_mp, X, y, tol=-1) assert_raises(ValueError, orthogonal_mp, X, y, n_nonzero_coefs=-1) assert_raises(ValueError, orthogonal_mp, X, y, n_nonzero_coefs=n_features + 1) assert_raises(ValueError, orthogonal_mp_gram, G, Xy, tol=-1) assert_raises(ValueError, orthogonal_mp_gram, G, Xy, n_nonzero_coefs=-1) assert_raises(ValueError, orthogonal_mp_gram, G, Xy, n_nonzero_coefs=n_features + 1) def test_perfect_signal_recovery(): idx, = gamma[:, 0].nonzero() gamma_rec = orthogonal_mp(X, y[:, 0], 5) gamma_gram = orthogonal_mp_gram(G, Xy[:, 0], 5) assert_array_equal(idx, np.flatnonzero(gamma_rec)) assert_array_equal(idx, np.flatnonzero(gamma_gram)) assert_array_almost_equal(gamma[:, 0], gamma_rec, decimal=2) assert_array_almost_equal(gamma[:, 0], gamma_gram, decimal=2) def test_estimator(): omp = OrthogonalMatchingPursuit(n_nonzero_coefs=n_nonzero_coefs) omp.fit(X, y[:, 0]) assert_equal(omp.coef_.shape, (n_features,)) assert_equal(omp.intercept_.shape, ()) assert_true(np.count_nonzero(omp.coef_) <= n_nonzero_coefs) omp.fit(X, y) assert_equal(omp.coef_.shape, (n_targets, n_features)) assert_equal(omp.intercept_.shape, (n_targets,)) assert_true(np.count_nonzero(omp.coef_) <= n_targets * n_nonzero_coefs) omp.set_params(fit_intercept=False, normalize=False) omp.fit(X, y[:, 0]) assert_equal(omp.coef_.shape, (n_features,)) assert_equal(omp.intercept_, 0) assert_true(np.count_nonzero(omp.coef_) <= n_nonzero_coefs) omp.fit(X, y) assert_equal(omp.coef_.shape, (n_targets, n_features)) assert_equal(omp.intercept_, 0) assert_true(np.count_nonzero(omp.coef_) <= n_targets * n_nonzero_coefs) def test_identical_regressors(): newX = X.copy() newX[:, 1] = newX[:, 0] gamma = np.zeros(n_features) gamma[0] = gamma[1] = 1. newy = np.dot(newX, gamma) assert_warns(RuntimeWarning, orthogonal_mp, newX, newy, 2) def test_swapped_regressors(): gamma = np.zeros(n_features) # X[:, 21] should be selected first, then X[:, 0] selected second, # which will take X[:, 21]'s place in case the algorithm does # column swapping for optimization (which is the case at the moment) gamma[21] = 1.0 gamma[0] = 0.5 new_y = np.dot(X, gamma) new_Xy = np.dot(X.T, new_y) gamma_hat = orthogonal_mp(X, new_y, 2) gamma_hat_gram = orthogonal_mp_gram(G, new_Xy, 2) assert_array_equal(np.flatnonzero(gamma_hat), [0, 21]) assert_array_equal(np.flatnonzero(gamma_hat_gram), [0, 21]) def test_no_atoms(): y_empty = np.zeros_like(y) Xy_empty = np.dot(X.T, y_empty) gamma_empty = ignore_warnings(orthogonal_mp)(X, y_empty, 1) gamma_empty_gram = ignore_warnings(orthogonal_mp)(G, Xy_empty, 1) assert_equal(np.all(gamma_empty == 0), True) assert_equal(np.all(gamma_empty_gram == 0), True) def test_omp_path(): path = orthogonal_mp(X, y, n_nonzero_coefs=5, return_path=True) last = orthogonal_mp(X, y, n_nonzero_coefs=5, return_path=False) assert_equal(path.shape, (n_features, n_targets, 5)) assert_array_almost_equal(path[:, :, -1], last) path = orthogonal_mp_gram(G, Xy, n_nonzero_coefs=5, return_path=True) last = orthogonal_mp_gram(G, Xy, n_nonzero_coefs=5, return_path=False) assert_equal(path.shape, (n_features, n_targets, 5)) assert_array_almost_equal(path[:, :, -1], last) def test_omp_return_path_prop_with_gram(): path = orthogonal_mp(X, y, n_nonzero_coefs=5, return_path=True, precompute=True) last = orthogonal_mp(X, y, n_nonzero_coefs=5, return_path=False, precompute=True) assert_equal(path.shape, (n_features, n_targets, 5)) assert_array_almost_equal(path[:, :, -1], last) def test_omp_cv(): y_ = y[:, 0] gamma_ = gamma[:, 0] ompcv = OrthogonalMatchingPursuitCV(normalize=True, fit_intercept=False, max_iter=10, cv=5) ompcv.fit(X, y_) assert_equal(ompcv.n_nonzero_coefs_, n_nonzero_coefs) assert_array_almost_equal(ompcv.coef_, gamma_) omp = OrthogonalMatchingPursuit(normalize=True, fit_intercept=False, n_nonzero_coefs=ompcv.n_nonzero_coefs_) omp.fit(X, y_) assert_array_almost_equal(ompcv.coef_, omp.coef_) def test_omp_reaches_least_squares(): # Use small simple data; it's a sanity check but OMP can stop early rng = check_random_state(0) n_samples, n_features = (10, 8) n_targets = 3 X = rng.randn(n_samples, n_features) Y = rng.randn(n_samples, n_targets) omp = OrthogonalMatchingPursuit(n_nonzero_coefs=n_features) lstsq = LinearRegression() omp.fit(X, Y) lstsq.fit(X, Y) assert_array_almost_equal(omp.coef_, lstsq.coef_)
bsd-3-clause
xyguo/scikit-learn
sklearn/metrics/tests/test_common.py
31
41654
from __future__ import division, print_function from functools import partial from itertools import product import numpy as np import scipy.sparse as sp from sklearn.datasets import make_multilabel_classification from sklearn.preprocessing import LabelBinarizer from sklearn.utils.multiclass import type_of_target from sklearn.utils.validation import check_random_state from sklearn.utils import shuffle from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_not_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_true from sklearn.utils.testing import ignore_warnings from sklearn.metrics import accuracy_score from sklearn.metrics import average_precision_score from sklearn.metrics import brier_score_loss from sklearn.metrics import cohen_kappa_score from sklearn.metrics import confusion_matrix from sklearn.metrics import coverage_error from sklearn.metrics import explained_variance_score from sklearn.metrics import f1_score from sklearn.metrics import fbeta_score from sklearn.metrics import hamming_loss from sklearn.metrics import hinge_loss from sklearn.metrics import jaccard_similarity_score from sklearn.metrics import label_ranking_average_precision_score from sklearn.metrics import label_ranking_loss from sklearn.metrics import log_loss from sklearn.metrics import matthews_corrcoef from sklearn.metrics import mean_absolute_error from sklearn.metrics import mean_squared_error from sklearn.metrics import median_absolute_error from sklearn.metrics import precision_score from sklearn.metrics import r2_score from sklearn.metrics import recall_score from sklearn.metrics import roc_auc_score from sklearn.metrics import zero_one_loss # TODO Curve are currently not covered by invariance test # from sklearn.metrics import precision_recall_curve # from sklearn.metrics import roc_curve from sklearn.metrics.base import _average_binary_score # Note toward developers about metric testing # ------------------------------------------- # It is often possible to write one general test for several metrics: # # - invariance properties, e.g. invariance to sample order # - common behavior for an argument, e.g. the "normalize" with value True # will return the mean of the metrics and with value False will return # the sum of the metrics. # # In order to improve the overall metric testing, it is a good idea to write # first a specific test for the given metric and then add a general test for # all metrics that have the same behavior. # # Two types of datastructures are used in order to implement this system: # dictionaries of metrics and lists of metrics wit common properties. # # Dictionaries of metrics # ------------------------ # The goal of having those dictionaries is to have an easy way to call a # particular metric and associate a name to each function: # # - REGRESSION_METRICS: all regression metrics. # - CLASSIFICATION_METRICS: all classification metrics # which compare a ground truth and the estimated targets as returned by a # classifier. # - THRESHOLDED_METRICS: all classification metrics which # compare a ground truth and a score, e.g. estimated probabilities or # decision function (format might vary) # # Those dictionaries will be used to test systematically some invariance # properties, e.g. invariance toward several input layout. # REGRESSION_METRICS = { "mean_absolute_error": mean_absolute_error, "mean_squared_error": mean_squared_error, "median_absolute_error": median_absolute_error, "explained_variance_score": explained_variance_score, "r2_score": partial(r2_score, multioutput='variance_weighted'), } CLASSIFICATION_METRICS = { "accuracy_score": accuracy_score, "unnormalized_accuracy_score": partial(accuracy_score, normalize=False), "confusion_matrix": confusion_matrix, "hamming_loss": hamming_loss, "jaccard_similarity_score": jaccard_similarity_score, "unnormalized_jaccard_similarity_score": partial(jaccard_similarity_score, normalize=False), "zero_one_loss": zero_one_loss, "unnormalized_zero_one_loss": partial(zero_one_loss, normalize=False), # These are needed to test averaging "precision_score": precision_score, "recall_score": recall_score, "f1_score": f1_score, "f2_score": partial(fbeta_score, beta=2), "f0.5_score": partial(fbeta_score, beta=0.5), "matthews_corrcoef_score": matthews_corrcoef, "weighted_f0.5_score": partial(fbeta_score, average="weighted", beta=0.5), "weighted_f1_score": partial(f1_score, average="weighted"), "weighted_f2_score": partial(fbeta_score, average="weighted", beta=2), "weighted_precision_score": partial(precision_score, average="weighted"), "weighted_recall_score": partial(recall_score, average="weighted"), "micro_f0.5_score": partial(fbeta_score, average="micro", beta=0.5), "micro_f1_score": partial(f1_score, average="micro"), "micro_f2_score": partial(fbeta_score, average="micro", beta=2), "micro_precision_score": partial(precision_score, average="micro"), "micro_recall_score": partial(recall_score, average="micro"), "macro_f0.5_score": partial(fbeta_score, average="macro", beta=0.5), "macro_f1_score": partial(f1_score, average="macro"), "macro_f2_score": partial(fbeta_score, average="macro", beta=2), "macro_precision_score": partial(precision_score, average="macro"), "macro_recall_score": partial(recall_score, average="macro"), "samples_f0.5_score": partial(fbeta_score, average="samples", beta=0.5), "samples_f1_score": partial(f1_score, average="samples"), "samples_f2_score": partial(fbeta_score, average="samples", beta=2), "samples_precision_score": partial(precision_score, average="samples"), "samples_recall_score": partial(recall_score, average="samples"), "cohen_kappa_score": cohen_kappa_score, } THRESHOLDED_METRICS = { "coverage_error": coverage_error, "label_ranking_loss": label_ranking_loss, "log_loss": log_loss, "unnormalized_log_loss": partial(log_loss, normalize=False), "hinge_loss": hinge_loss, "brier_score_loss": brier_score_loss, "roc_auc_score": roc_auc_score, "weighted_roc_auc": partial(roc_auc_score, average="weighted"), "samples_roc_auc": partial(roc_auc_score, average="samples"), "micro_roc_auc": partial(roc_auc_score, average="micro"), "macro_roc_auc": partial(roc_auc_score, average="macro"), "average_precision_score": average_precision_score, "weighted_average_precision_score": partial(average_precision_score, average="weighted"), "samples_average_precision_score": partial(average_precision_score, average="samples"), "micro_average_precision_score": partial(average_precision_score, average="micro"), "macro_average_precision_score": partial(average_precision_score, average="macro"), "label_ranking_average_precision_score": label_ranking_average_precision_score, } ALL_METRICS = dict() ALL_METRICS.update(THRESHOLDED_METRICS) ALL_METRICS.update(CLASSIFICATION_METRICS) ALL_METRICS.update(REGRESSION_METRICS) # Lists of metrics with common properties # --------------------------------------- # Lists of metrics with common properties are used to test systematically some # functionalities and invariance, e.g. SYMMETRIC_METRICS lists all metrics that # are symmetric with respect to their input argument y_true and y_pred. # # When you add a new metric or functionality, check if a general test # is already written. # Those metrics don't support binary inputs METRIC_UNDEFINED_BINARY = [ "samples_f0.5_score", "samples_f1_score", "samples_f2_score", "samples_precision_score", "samples_recall_score", "coverage_error", "roc_auc_score", "micro_roc_auc", "weighted_roc_auc", "macro_roc_auc", "samples_roc_auc", "average_precision_score", "weighted_average_precision_score", "micro_average_precision_score", "macro_average_precision_score", "samples_average_precision_score", "label_ranking_loss", "label_ranking_average_precision_score", ] # Those metrics don't support multiclass inputs METRIC_UNDEFINED_MULTICLASS = [ "brier_score_loss", "matthews_corrcoef_score", ] # Metric undefined with "binary" or "multiclass" input METRIC_UNDEFINED_BINARY_MULTICLASS = set(METRIC_UNDEFINED_BINARY).union( set(METRIC_UNDEFINED_MULTICLASS)) # Metrics with an "average" argument METRICS_WITH_AVERAGING = [ "precision_score", "recall_score", "f1_score", "f2_score", "f0.5_score" ] # Threshold-based metrics with an "average" argument THRESHOLDED_METRICS_WITH_AVERAGING = [ "roc_auc_score", "average_precision_score", ] # Metrics with a "pos_label" argument METRICS_WITH_POS_LABEL = [ "roc_curve", "brier_score_loss", "precision_score", "recall_score", "f1_score", "f2_score", "f0.5_score", # pos_label support deprecated; to be removed in 0.18: "weighted_f0.5_score", "weighted_f1_score", "weighted_f2_score", "weighted_precision_score", "weighted_recall_score", "micro_f0.5_score", "micro_f1_score", "micro_f2_score", "micro_precision_score", "micro_recall_score", "macro_f0.5_score", "macro_f1_score", "macro_f2_score", "macro_precision_score", "macro_recall_score", ] # Metrics with a "labels" argument # TODO: Handle multi_class metrics that has a labels argument as well as a # decision function argument. e.g hinge_loss METRICS_WITH_LABELS = [ "confusion_matrix", "precision_score", "recall_score", "f1_score", "f2_score", "f0.5_score", "weighted_f0.5_score", "weighted_f1_score", "weighted_f2_score", "weighted_precision_score", "weighted_recall_score", "micro_f0.5_score", "micro_f1_score", "micro_f2_score", "micro_precision_score", "micro_recall_score", "macro_f0.5_score", "macro_f1_score", "macro_f2_score", "macro_precision_score", "macro_recall_score", "cohen_kappa_score", ] # Metrics with a "normalize" option METRICS_WITH_NORMALIZE_OPTION = [ "accuracy_score", "jaccard_similarity_score", "zero_one_loss", ] # Threshold-based metrics with "multilabel-indicator" format support THRESHOLDED_MULTILABEL_METRICS = [ "log_loss", "unnormalized_log_loss", "roc_auc_score", "weighted_roc_auc", "samples_roc_auc", "micro_roc_auc", "macro_roc_auc", "average_precision_score", "weighted_average_precision_score", "samples_average_precision_score", "micro_average_precision_score", "macro_average_precision_score", "coverage_error", "label_ranking_loss", ] # Classification metrics with "multilabel-indicator" format MULTILABELS_METRICS = [ "accuracy_score", "unnormalized_accuracy_score", "hamming_loss", "jaccard_similarity_score", "unnormalized_jaccard_similarity_score", "zero_one_loss", "unnormalized_zero_one_loss", "precision_score", "recall_score", "f1_score", "f2_score", "f0.5_score", "weighted_f0.5_score", "weighted_f1_score", "weighted_f2_score", "weighted_precision_score", "weighted_recall_score", "micro_f0.5_score", "micro_f1_score", "micro_f2_score", "micro_precision_score", "micro_recall_score", "macro_f0.5_score", "macro_f1_score", "macro_f2_score", "macro_precision_score", "macro_recall_score", "samples_f0.5_score", "samples_f1_score", "samples_f2_score", "samples_precision_score", "samples_recall_score", ] # Regression metrics with "multioutput-continuous" format support MULTIOUTPUT_METRICS = [ "mean_absolute_error", "mean_squared_error", "r2_score", "explained_variance_score" ] # Symmetric with respect to their input arguments y_true and y_pred # metric(y_true, y_pred) == metric(y_pred, y_true). SYMMETRIC_METRICS = [ "accuracy_score", "unnormalized_accuracy_score", "hamming_loss", "jaccard_similarity_score", "unnormalized_jaccard_similarity_score", "zero_one_loss", "unnormalized_zero_one_loss", "f1_score", "weighted_f1_score", "micro_f1_score", "macro_f1_score", "matthews_corrcoef_score", "mean_absolute_error", "mean_squared_error", "median_absolute_error", "cohen_kappa_score", ] # Asymmetric with respect to their input arguments y_true and y_pred # metric(y_true, y_pred) != metric(y_pred, y_true). NOT_SYMMETRIC_METRICS = [ "explained_variance_score", "r2_score", "confusion_matrix", "precision_score", "recall_score", "f2_score", "f0.5_score", "weighted_f0.5_score", "weighted_f2_score", "weighted_precision_score", "weighted_recall_score", "micro_f0.5_score", "micro_f2_score", "micro_precision_score", "micro_recall_score", "macro_f0.5_score", "macro_f2_score", "macro_precision_score", "macro_recall_score", "log_loss", "hinge_loss" ] # No Sample weight support METRICS_WITHOUT_SAMPLE_WEIGHT = [ "cohen_kappa_score", "confusion_matrix", # Left this one here because the tests in this file do # not work for confusion_matrix, as its output is a # matrix instead of a number. Testing of # confusion_matrix with sample_weight is in # test_classification.py "median_absolute_error", ] @ignore_warnings def test_symmetry(): # Test the symmetry of score and loss functions random_state = check_random_state(0) y_true = random_state.randint(0, 2, size=(20, )) y_pred = random_state.randint(0, 2, size=(20, )) # We shouldn't forget any metrics assert_equal(set(SYMMETRIC_METRICS).union( NOT_SYMMETRIC_METRICS, THRESHOLDED_METRICS, METRIC_UNDEFINED_BINARY_MULTICLASS), set(ALL_METRICS)) assert_equal( set(SYMMETRIC_METRICS).intersection(set(NOT_SYMMETRIC_METRICS)), set([])) # Symmetric metric for name in SYMMETRIC_METRICS: metric = ALL_METRICS[name] assert_almost_equal(metric(y_true, y_pred), metric(y_pred, y_true), err_msg="%s is not symmetric" % name) # Not symmetric metrics for name in NOT_SYMMETRIC_METRICS: metric = ALL_METRICS[name] assert_true(np.any(metric(y_true, y_pred) != metric(y_pred, y_true)), msg="%s seems to be symmetric" % name) @ignore_warnings def test_sample_order_invariance(): random_state = check_random_state(0) y_true = random_state.randint(0, 2, size=(20, )) y_pred = random_state.randint(0, 2, size=(20, )) y_true_shuffle, y_pred_shuffle = shuffle(y_true, y_pred, random_state=0) for name, metric in ALL_METRICS.items(): if name in METRIC_UNDEFINED_BINARY_MULTICLASS: continue assert_almost_equal(metric(y_true, y_pred), metric(y_true_shuffle, y_pred_shuffle), err_msg="%s is not sample order invariant" % name) @ignore_warnings def test_sample_order_invariance_multilabel_and_multioutput(): random_state = check_random_state(0) # Generate some data y_true = random_state.randint(0, 2, size=(20, 25)) y_pred = random_state.randint(0, 2, size=(20, 25)) y_score = random_state.normal(size=y_true.shape) y_true_shuffle, y_pred_shuffle, y_score_shuffle = shuffle(y_true, y_pred, y_score, random_state=0) for name in MULTILABELS_METRICS: metric = ALL_METRICS[name] assert_almost_equal(metric(y_true, y_pred), metric(y_true_shuffle, y_pred_shuffle), err_msg="%s is not sample order invariant" % name) for name in THRESHOLDED_MULTILABEL_METRICS: metric = ALL_METRICS[name] assert_almost_equal(metric(y_true, y_score), metric(y_true_shuffle, y_score_shuffle), err_msg="%s is not sample order invariant" % name) for name in MULTIOUTPUT_METRICS: metric = ALL_METRICS[name] assert_almost_equal(metric(y_true, y_score), metric(y_true_shuffle, y_score_shuffle), err_msg="%s is not sample order invariant" % name) assert_almost_equal(metric(y_true, y_pred), metric(y_true_shuffle, y_pred_shuffle), err_msg="%s is not sample order invariant" % name) @ignore_warnings def test_format_invariance_with_1d_vectors(): random_state = check_random_state(0) y1 = random_state.randint(0, 2, size=(20, )) y2 = random_state.randint(0, 2, size=(20, )) y1_list = list(y1) y2_list = list(y2) y1_1d, y2_1d = np.array(y1), np.array(y2) assert_equal(y1_1d.ndim, 1) assert_equal(y2_1d.ndim, 1) y1_column = np.reshape(y1_1d, (-1, 1)) y2_column = np.reshape(y2_1d, (-1, 1)) y1_row = np.reshape(y1_1d, (1, -1)) y2_row = np.reshape(y2_1d, (1, -1)) for name, metric in ALL_METRICS.items(): if name in METRIC_UNDEFINED_BINARY_MULTICLASS: continue measure = metric(y1, y2) assert_almost_equal(metric(y1_list, y2_list), measure, err_msg="%s is not representation invariant " "with list" % name) assert_almost_equal(metric(y1_1d, y2_1d), measure, err_msg="%s is not representation invariant " "with np-array-1d" % name) assert_almost_equal(metric(y1_column, y2_column), measure, err_msg="%s is not representation invariant " "with np-array-column" % name) # Mix format support assert_almost_equal(metric(y1_1d, y2_list), measure, err_msg="%s is not representation invariant " "with mix np-array-1d and list" % name) assert_almost_equal(metric(y1_list, y2_1d), measure, err_msg="%s is not representation invariant " "with mix np-array-1d and list" % name) assert_almost_equal(metric(y1_1d, y2_column), measure, err_msg="%s is not representation invariant " "with mix np-array-1d and np-array-column" % name) assert_almost_equal(metric(y1_column, y2_1d), measure, err_msg="%s is not representation invariant " "with mix np-array-1d and np-array-column" % name) assert_almost_equal(metric(y1_list, y2_column), measure, err_msg="%s is not representation invariant " "with mix list and np-array-column" % name) assert_almost_equal(metric(y1_column, y2_list), measure, err_msg="%s is not representation invariant " "with mix list and np-array-column" % name) # These mix representations aren't allowed assert_raises(ValueError, metric, y1_1d, y2_row) assert_raises(ValueError, metric, y1_row, y2_1d) assert_raises(ValueError, metric, y1_list, y2_row) assert_raises(ValueError, metric, y1_row, y2_list) assert_raises(ValueError, metric, y1_column, y2_row) assert_raises(ValueError, metric, y1_row, y2_column) # NB: We do not test for y1_row, y2_row as these may be # interpreted as multilabel or multioutput data. if (name not in (MULTIOUTPUT_METRICS + THRESHOLDED_MULTILABEL_METRICS + MULTILABELS_METRICS)): assert_raises(ValueError, metric, y1_row, y2_row) @ignore_warnings def test_invariance_string_vs_numbers_labels(): # Ensure that classification metrics with string labels random_state = check_random_state(0) y1 = random_state.randint(0, 2, size=(20, )) y2 = random_state.randint(0, 2, size=(20, )) y1_str = np.array(["eggs", "spam"])[y1] y2_str = np.array(["eggs", "spam"])[y2] pos_label_str = "spam" labels_str = ["eggs", "spam"] for name, metric in CLASSIFICATION_METRICS.items(): if name in METRIC_UNDEFINED_BINARY_MULTICLASS: continue measure_with_number = metric(y1, y2) # Ugly, but handle case with a pos_label and label metric_str = metric if name in METRICS_WITH_POS_LABEL: metric_str = partial(metric_str, pos_label=pos_label_str) measure_with_str = metric_str(y1_str, y2_str) assert_array_equal(measure_with_number, measure_with_str, err_msg="{0} failed string vs number invariance " "test".format(name)) measure_with_strobj = metric_str(y1_str.astype('O'), y2_str.astype('O')) assert_array_equal(measure_with_number, measure_with_strobj, err_msg="{0} failed string object vs number " "invariance test".format(name)) if name in METRICS_WITH_LABELS: metric_str = partial(metric_str, labels=labels_str) measure_with_str = metric_str(y1_str, y2_str) assert_array_equal(measure_with_number, measure_with_str, err_msg="{0} failed string vs number " "invariance test".format(name)) measure_with_strobj = metric_str(y1_str.astype('O'), y2_str.astype('O')) assert_array_equal(measure_with_number, measure_with_strobj, err_msg="{0} failed string vs number " "invariance test".format(name)) for name, metric in THRESHOLDED_METRICS.items(): if name in ("log_loss", "hinge_loss", "unnormalized_log_loss", "brier_score_loss"): # Ugly, but handle case with a pos_label and label metric_str = metric if name in METRICS_WITH_POS_LABEL: metric_str = partial(metric_str, pos_label=pos_label_str) measure_with_number = metric(y1, y2) measure_with_str = metric_str(y1_str, y2) assert_array_equal(measure_with_number, measure_with_str, err_msg="{0} failed string vs number " "invariance test".format(name)) measure_with_strobj = metric(y1_str.astype('O'), y2) assert_array_equal(measure_with_number, measure_with_strobj, err_msg="{0} failed string object vs number " "invariance test".format(name)) else: # TODO those metrics doesn't support string label yet assert_raises(ValueError, metric, y1_str, y2) assert_raises(ValueError, metric, y1_str.astype('O'), y2) @ignore_warnings def check_single_sample(name): # Non-regression test: scores should work with a single sample. # This is important for leave-one-out cross validation. # Score functions tested are those that formerly called np.squeeze, # which turns an array of size 1 into a 0-d array (!). metric = ALL_METRICS[name] # assert that no exception is thrown for i, j in product([0, 1], repeat=2): metric([i], [j]) @ignore_warnings def check_single_sample_multioutput(name): metric = ALL_METRICS[name] for i, j, k, l in product([0, 1], repeat=4): metric(np.array([[i, j]]), np.array([[k, l]])) def test_single_sample(): for name in ALL_METRICS: if (name in METRIC_UNDEFINED_BINARY_MULTICLASS or name in THRESHOLDED_METRICS): # Those metrics are not always defined with one sample # or in multiclass classification continue yield check_single_sample, name for name in MULTIOUTPUT_METRICS + MULTILABELS_METRICS: yield check_single_sample_multioutput, name def test_multioutput_number_of_output_differ(): y_true = np.array([[1, 0, 0, 1], [0, 1, 1, 1], [1, 1, 0, 1]]) y_pred = np.array([[0, 0], [1, 0], [0, 0]]) for name in MULTIOUTPUT_METRICS: metric = ALL_METRICS[name] assert_raises(ValueError, metric, y_true, y_pred) def test_multioutput_regression_invariance_to_dimension_shuffling(): # test invariance to dimension shuffling random_state = check_random_state(0) y_true = random_state.uniform(0, 2, size=(20, 5)) y_pred = random_state.uniform(0, 2, size=(20, 5)) for name in MULTIOUTPUT_METRICS: metric = ALL_METRICS[name] error = metric(y_true, y_pred) for _ in range(3): perm = random_state.permutation(y_true.shape[1]) assert_almost_equal(metric(y_true[:, perm], y_pred[:, perm]), error, err_msg="%s is not dimension shuffling " "invariant" % name) @ignore_warnings def test_multilabel_representation_invariance(): # Generate some data n_classes = 4 n_samples = 50 _, y1 = make_multilabel_classification(n_features=1, n_classes=n_classes, random_state=0, n_samples=n_samples, allow_unlabeled=True) _, y2 = make_multilabel_classification(n_features=1, n_classes=n_classes, random_state=1, n_samples=n_samples, allow_unlabeled=True) # To make sure at least one empty label is present y1 += [0]*n_classes y2 += [0]*n_classes y1_sparse_indicator = sp.coo_matrix(y1) y2_sparse_indicator = sp.coo_matrix(y2) for name in MULTILABELS_METRICS: metric = ALL_METRICS[name] # XXX cruel hack to work with partial functions if isinstance(metric, partial): metric.__module__ = 'tmp' metric.__name__ = name measure = metric(y1, y2) # Check representation invariance assert_almost_equal(metric(y1_sparse_indicator, y2_sparse_indicator), measure, err_msg="%s failed representation invariance " "between dense and sparse indicator " "formats." % name) def test_raise_value_error_multilabel_sequences(): # make sure the multilabel-sequence format raises ValueError multilabel_sequences = [ [[0, 1]], [[1], [2], [0, 1]], [(), (2), (0, 1)], [[]], [()], np.array([[], [1, 2]], dtype='object')] for name in MULTILABELS_METRICS: metric = ALL_METRICS[name] for seq in multilabel_sequences: assert_raises(ValueError, metric, seq, seq) def test_normalize_option_binary_classification(n_samples=20): # Test in the binary case random_state = check_random_state(0) y_true = random_state.randint(0, 2, size=(n_samples, )) y_pred = random_state.randint(0, 2, size=(n_samples, )) for name in METRICS_WITH_NORMALIZE_OPTION: metrics = ALL_METRICS[name] measure = metrics(y_true, y_pred, normalize=True) assert_greater(measure, 0, msg="We failed to test correctly the normalize option") assert_almost_equal(metrics(y_true, y_pred, normalize=False) / n_samples, measure) def test_normalize_option_multiclasss_classification(): # Test in the multiclass case random_state = check_random_state(0) y_true = random_state.randint(0, 4, size=(20, )) y_pred = random_state.randint(0, 4, size=(20, )) n_samples = y_true.shape[0] for name in METRICS_WITH_NORMALIZE_OPTION: metrics = ALL_METRICS[name] measure = metrics(y_true, y_pred, normalize=True) assert_greater(measure, 0, msg="We failed to test correctly the normalize option") assert_almost_equal(metrics(y_true, y_pred, normalize=False) / n_samples, measure) def test_normalize_option_multilabel_classification(): # Test in the multilabel case n_classes = 4 n_samples = 100 # for both random_state 0 and 1, y_true and y_pred has at least one # unlabelled entry _, y_true = make_multilabel_classification(n_features=1, n_classes=n_classes, random_state=0, allow_unlabeled=True, n_samples=n_samples) _, y_pred = make_multilabel_classification(n_features=1, n_classes=n_classes, random_state=1, allow_unlabeled=True, n_samples=n_samples) # To make sure at least one empty label is present y_true += [0]*n_classes y_pred += [0]*n_classes for name in METRICS_WITH_NORMALIZE_OPTION: metrics = ALL_METRICS[name] measure = metrics(y_true, y_pred, normalize=True) assert_greater(measure, 0, msg="We failed to test correctly the normalize option") assert_almost_equal(metrics(y_true, y_pred, normalize=False) / n_samples, measure, err_msg="Failed with %s" % name) @ignore_warnings def _check_averaging(metric, y_true, y_pred, y_true_binarize, y_pred_binarize, is_multilabel): n_samples, n_classes = y_true_binarize.shape # No averaging label_measure = metric(y_true, y_pred, average=None) assert_array_almost_equal(label_measure, [metric(y_true_binarize[:, i], y_pred_binarize[:, i]) for i in range(n_classes)]) # Micro measure micro_measure = metric(y_true, y_pred, average="micro") assert_almost_equal(micro_measure, metric(y_true_binarize.ravel(), y_pred_binarize.ravel())) # Macro measure macro_measure = metric(y_true, y_pred, average="macro") assert_almost_equal(macro_measure, np.mean(label_measure)) # Weighted measure weights = np.sum(y_true_binarize, axis=0, dtype=int) if np.sum(weights) != 0: weighted_measure = metric(y_true, y_pred, average="weighted") assert_almost_equal(weighted_measure, np.average(label_measure, weights=weights)) else: weighted_measure = metric(y_true, y_pred, average="weighted") assert_almost_equal(weighted_measure, 0) # Sample measure if is_multilabel: sample_measure = metric(y_true, y_pred, average="samples") assert_almost_equal(sample_measure, np.mean([metric(y_true_binarize[i], y_pred_binarize[i]) for i in range(n_samples)])) assert_raises(ValueError, metric, y_true, y_pred, average="unknown") assert_raises(ValueError, metric, y_true, y_pred, average="garbage") def check_averaging(name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score): is_multilabel = type_of_target(y_true).startswith("multilabel") metric = ALL_METRICS[name] if name in METRICS_WITH_AVERAGING: _check_averaging(metric, y_true, y_pred, y_true_binarize, y_pred_binarize, is_multilabel) elif name in THRESHOLDED_METRICS_WITH_AVERAGING: _check_averaging(metric, y_true, y_score, y_true_binarize, y_score, is_multilabel) else: raise ValueError("Metric is not recorded as having an average option") def test_averaging_multiclass(n_samples=50, n_classes=3): random_state = check_random_state(0) y_true = random_state.randint(0, n_classes, size=(n_samples, )) y_pred = random_state.randint(0, n_classes, size=(n_samples, )) y_score = random_state.uniform(size=(n_samples, n_classes)) lb = LabelBinarizer().fit(y_true) y_true_binarize = lb.transform(y_true) y_pred_binarize = lb.transform(y_pred) for name in METRICS_WITH_AVERAGING: yield (check_averaging, name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score) def test_averaging_multilabel(n_classes=5, n_samples=40): _, y = make_multilabel_classification(n_features=1, n_classes=n_classes, random_state=5, n_samples=n_samples, allow_unlabeled=False) y_true = y[:20] y_pred = y[20:] y_score = check_random_state(0).normal(size=(20, n_classes)) y_true_binarize = y_true y_pred_binarize = y_pred for name in METRICS_WITH_AVERAGING + THRESHOLDED_METRICS_WITH_AVERAGING: yield (check_averaging, name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score) def test_averaging_multilabel_all_zeroes(): y_true = np.zeros((20, 3)) y_pred = np.zeros((20, 3)) y_score = np.zeros((20, 3)) y_true_binarize = y_true y_pred_binarize = y_pred for name in METRICS_WITH_AVERAGING: yield (check_averaging, name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score) # Test _average_binary_score for weight.sum() == 0 binary_metric = (lambda y_true, y_score, average="macro": _average_binary_score( precision_score, y_true, y_score, average)) _check_averaging(binary_metric, y_true, y_pred, y_true_binarize, y_pred_binarize, is_multilabel=True) def test_averaging_multilabel_all_ones(): y_true = np.ones((20, 3)) y_pred = np.ones((20, 3)) y_score = np.ones((20, 3)) y_true_binarize = y_true y_pred_binarize = y_pred for name in METRICS_WITH_AVERAGING: yield (check_averaging, name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score) @ignore_warnings def check_sample_weight_invariance(name, metric, y1, y2): rng = np.random.RandomState(0) sample_weight = rng.randint(1, 10, size=len(y1)) # check that unit weights gives the same score as no weight unweighted_score = metric(y1, y2, sample_weight=None) assert_almost_equal( unweighted_score, metric(y1, y2, sample_weight=np.ones(shape=len(y1))), err_msg="For %s sample_weight=None is not equivalent to " "sample_weight=ones" % name) # check that the weighted and unweighted scores are unequal weighted_score = metric(y1, y2, sample_weight=sample_weight) assert_not_equal( unweighted_score, weighted_score, msg="Unweighted and weighted scores are unexpectedly " "equal (%f) for %s" % (weighted_score, name)) # check that sample_weight can be a list weighted_score_list = metric(y1, y2, sample_weight=sample_weight.tolist()) assert_almost_equal( weighted_score, weighted_score_list, err_msg=("Weighted scores for array and list " "sample_weight input are not equal (%f != %f) for %s") % ( weighted_score, weighted_score_list, name)) # check that integer weights is the same as repeated samples repeat_weighted_score = metric( np.repeat(y1, sample_weight, axis=0), np.repeat(y2, sample_weight, axis=0), sample_weight=None) assert_almost_equal( weighted_score, repeat_weighted_score, err_msg="Weighting %s is not equal to repeating samples" % name) # check that ignoring a fraction of the samples is equivalent to setting # the corresponding weights to zero sample_weight_subset = sample_weight[1::2] sample_weight_zeroed = np.copy(sample_weight) sample_weight_zeroed[::2] = 0 y1_subset = y1[1::2] y2_subset = y2[1::2] weighted_score_subset = metric(y1_subset, y2_subset, sample_weight=sample_weight_subset) weighted_score_zeroed = metric(y1, y2, sample_weight=sample_weight_zeroed) assert_almost_equal( weighted_score_subset, weighted_score_zeroed, err_msg=("Zeroing weights does not give the same result as " "removing the corresponding samples (%f != %f) for %s" % (weighted_score_zeroed, weighted_score_subset, name))) if not name.startswith('unnormalized'): # check that the score is invariant under scaling of the weights by a # common factor for scaling in [2, 0.3]: assert_almost_equal( weighted_score, metric(y1, y2, sample_weight=sample_weight * scaling), err_msg="%s sample_weight is not invariant " "under scaling" % name) # Check that if sample_weight.shape[0] != y_true.shape[0], it raised an # error assert_raises(Exception, metric, y1, y2, sample_weight=np.hstack([sample_weight, sample_weight])) def test_sample_weight_invariance(n_samples=50): random_state = check_random_state(0) # binary random_state = check_random_state(0) y_true = random_state.randint(0, 2, size=(n_samples, )) y_pred = random_state.randint(0, 2, size=(n_samples, )) y_score = random_state.random_sample(size=(n_samples,)) for name in ALL_METRICS: if (name in METRICS_WITHOUT_SAMPLE_WEIGHT or name in METRIC_UNDEFINED_BINARY): continue metric = ALL_METRICS[name] if name in THRESHOLDED_METRICS: yield check_sample_weight_invariance, name, metric, y_true, y_score else: yield check_sample_weight_invariance, name, metric, y_true, y_pred # multiclass random_state = check_random_state(0) y_true = random_state.randint(0, 5, size=(n_samples, )) y_pred = random_state.randint(0, 5, size=(n_samples, )) y_score = random_state.random_sample(size=(n_samples, 5)) for name in ALL_METRICS: if (name in METRICS_WITHOUT_SAMPLE_WEIGHT or name in METRIC_UNDEFINED_BINARY_MULTICLASS): continue metric = ALL_METRICS[name] if name in THRESHOLDED_METRICS: yield check_sample_weight_invariance, name, metric, y_true, y_score else: yield check_sample_weight_invariance, name, metric, y_true, y_pred # multilabel indicator _, ya = make_multilabel_classification(n_features=1, n_classes=20, random_state=0, n_samples=100, allow_unlabeled=False) _, yb = make_multilabel_classification(n_features=1, n_classes=20, random_state=1, n_samples=100, allow_unlabeled=False) y_true = np.vstack([ya, yb]) y_pred = np.vstack([ya, ya]) y_score = random_state.randint(1, 4, size=y_true.shape) for name in (MULTILABELS_METRICS + THRESHOLDED_MULTILABEL_METRICS + MULTIOUTPUT_METRICS): if name in METRICS_WITHOUT_SAMPLE_WEIGHT: continue metric = ALL_METRICS[name] if name in THRESHOLDED_METRICS: yield (check_sample_weight_invariance, name, metric, y_true, y_score) else: yield (check_sample_weight_invariance, name, metric, y_true, y_pred) def test_no_averaging_labels(): # test labels argument when not using averaging # in multi-class and multi-label cases y_true_multilabel = np.array([[1, 1, 0, 0], [1, 1, 0, 0]]) y_pred_multilabel = np.array([[0, 0, 1, 1], [0, 1, 1, 0]]) y_true_multiclass = np.array([0, 1, 2]) y_pred_multiclass = np.array([0, 2, 3]) labels = np.array([3, 0, 1, 2]) _, inverse_labels = np.unique(labels, return_inverse=True) for name in METRICS_WITH_AVERAGING: for y_true, y_pred in [[y_true_multiclass, y_pred_multiclass], [y_true_multilabel, y_pred_multilabel]]: if name not in MULTILABELS_METRICS and y_pred.shape[1] > 0: continue metric = ALL_METRICS[name] score_labels = metric(y_true, y_pred, labels=labels, average=None) score = metric(y_true, y_pred, average=None) assert_array_equal(score_labels, score[inverse_labels])
bsd-3-clause
asarnow/pyem
csparc2star.py
1
5818
#!/usr/bin/env python # Copyright (C) 2016 Daniel Asarnow # University of California, San Francisco # # Simple program for parsing and altering Relion .star files. # See help text and README file for more information. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # 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/>. from __future__ import print_function import argparse import json import logging import sys import numpy as np import pandas as pd from glob import glob from pyem import metadata from pyem import star def main(args): log = logging.getLogger('root') hdlr = logging.StreamHandler(sys.stdout) log.addHandler(hdlr) log.setLevel(logging.getLevelName(args.loglevel.upper())) if args.input[0].endswith(".cs"): log.debug("Detected CryoSPARC 2+ .cs file") cs = np.load(args.input[0]) try: df = metadata.parse_cryosparc_2_cs(cs, passthroughs=args.input[1:], minphic=args.minphic, boxsize=args.boxsize, swapxy=args.swapxy, invertx=args.invertx, inverty=args.inverty) except (KeyError, ValueError) as e: log.error(e, exc_info=True) log.error("Required fields could not be mapped. Are you using the right input file(s)?") return 1 else: log.debug("Detected CryoSPARC 0.6.5 .csv file") if len(args.input) > 1: log.error("Only one file at a time supported for CryoSPARC 0.6.5 .csv format") return 1 meta = metadata.parse_cryosparc_065_csv(args.input[0]) # Read cryosparc metadata file. df = metadata.cryosparc_065_csv2star(meta, args.minphic) if args.cls is not None: df = star.select_classes(df, args.cls) if args.copy_micrograph_coordinates is not None: df = star.augment_star_ucsf(df, inplace=True) coord_star = pd.concat( (star.parse_star(inp, keep_index=False, augment=True) for inp in glob(args.copy_micrograph_coordinates)), join="inner") key = star.merge_key(df, coord_star) log.debug("Coordinates merge key: %s" % key) if args.cached or key == star.Relion.IMAGE_NAME: fields = star.Relion.MICROGRAPH_COORDS else: fields = star.Relion.MICROGRAPH_COORDS + [star.UCSF.IMAGE_INDEX, star.UCSF.IMAGE_PATH] df = star.smart_merge(df, coord_star, fields=fields, key=key) star.simplify_star_ucsf(df) if args.micrograph_path is not None: df = star.replace_micrograph_path(df, args.micrograph_path, inplace=True) if args.transform is not None: r = np.array(json.loads(args.transform)) df = star.transform_star(df, r, inplace=True) df = star.check_defaults(df, inplace=True) if args.relion2: df = star.remove_new_relion31(df, inplace=True) star.write_star(args.output, df, resort_records=True, optics=False) else: df = star.remove_deprecated_relion2(df, inplace=True) star.write_star(args.output, df, resort_records=True, optics=True) log.info("Output fields: %s" % ", ".join(df.columns)) return 0 if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("input", help="Cryosparc metadata .csv (v0.6.5) or .cs (v2+) files", nargs="*") parser.add_argument("output", help="Output .star file") parser.add_argument("--boxsize", help="Cryosparc refinement box size (if different from particles)", type=float) # parser.add_argument("--passthrough", "-p", help="List file required for some Cryosparc 2+ job types") parser.add_argument("--class", help="Keep this class in output, may be passed multiple times", action="append", type=int, dest="cls") parser.add_argument("--minphic", help="Minimum posterior probability for class assignment", type=float, default=0) parser.add_argument("--stack-path", help="Path to single particle stack", type=str) parser.add_argument("--micrograph-path", help="Replacement path for micrographs") parser.add_argument("--copy-micrograph-coordinates", help="Source for micrograph paths and particle coordinates (file or quoted glob)", type=str) parser.add_argument("--swapxy", help="Swap X and Y axes when converting particle coordinates from normalized to absolute", action="store_true") parser.add_argument("--invertx", help="Invert particle coordinate X axis", action="store_true") parser.add_argument("--inverty", help="Invert particle coordinate Y axis", action="store_true") parser.add_argument("--cached", help="Keep paths from the Cryosparc 2+ cache when merging coordinates", action="store_true") parser.add_argument("--transform", help="Apply rotation matrix or 3x4 rotation plus translation matrix to particles (Numpy format)", type=str) parser.add_argument("--relion2", "-r2", help="Relion 2 compatible outputs", action="store_true") parser.add_argument("--loglevel", "-l", type=str, default="WARNING", help="Logging level and debug output") sys.exit(main(parser.parse_args()))
gpl-3.0
mbayon/TFG-MachineLearning
vbig/lib/python2.7/site-packages/sklearn/datasets/tests/test_lfw.py
42
7253
"""This test for the LFW require medium-size data downloading and processing If the data has not been already downloaded by running the examples, the tests won't run (skipped). If the test are run, the first execution will be long (typically a bit more than a couple of minutes) but as the dataset loader is leveraging joblib, successive runs will be fast (less than 200ms). """ import random import os import shutil import tempfile import numpy as np from sklearn.externals import six try: try: from scipy.misc import imsave except ImportError: from scipy.misc.pilutil import imsave except ImportError: imsave = None from sklearn.datasets import fetch_lfw_pairs from sklearn.datasets import fetch_lfw_people from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_equal from sklearn.utils.testing import SkipTest from sklearn.utils.testing import raises SCIKIT_LEARN_DATA = tempfile.mkdtemp(prefix="scikit_learn_lfw_test_") SCIKIT_LEARN_EMPTY_DATA = tempfile.mkdtemp(prefix="scikit_learn_empty_test_") LFW_HOME = os.path.join(SCIKIT_LEARN_DATA, 'lfw_home') FAKE_NAMES = [ 'Abdelatif_Smith', 'Abhati_Kepler', 'Camara_Alvaro', 'Chen_Dupont', 'John_Lee', 'Lin_Bauman', 'Onur_Lopez', ] def setup_module(): """Test fixture run once and common to all tests of this module""" if imsave is None: raise SkipTest("PIL not installed.") if not os.path.exists(LFW_HOME): os.makedirs(LFW_HOME) random_state = random.Random(42) np_rng = np.random.RandomState(42) # generate some random jpeg files for each person counts = {} for name in FAKE_NAMES: folder_name = os.path.join(LFW_HOME, 'lfw_funneled', name) if not os.path.exists(folder_name): os.makedirs(folder_name) n_faces = np_rng.randint(1, 5) counts[name] = n_faces for i in range(n_faces): file_path = os.path.join(folder_name, name + '_%04d.jpg' % i) uniface = np_rng.randint(0, 255, size=(250, 250, 3)) try: imsave(file_path, uniface) except ImportError: raise SkipTest("PIL not installed") # add some random file pollution to test robustness with open(os.path.join(LFW_HOME, 'lfw_funneled', '.test.swp'), 'wb') as f: f.write(six.b('Text file to be ignored by the dataset loader.')) # generate some pairing metadata files using the same format as LFW with open(os.path.join(LFW_HOME, 'pairsDevTrain.txt'), 'wb') as f: f.write(six.b("10\n")) more_than_two = [name for name, count in six.iteritems(counts) if count >= 2] for i in range(5): name = random_state.choice(more_than_two) first, second = random_state.sample(range(counts[name]), 2) f.write(six.b('%s\t%d\t%d\n' % (name, first, second))) for i in range(5): first_name, second_name = random_state.sample(FAKE_NAMES, 2) first_index = random_state.choice(np.arange(counts[first_name])) second_index = random_state.choice(np.arange(counts[second_name])) f.write(six.b('%s\t%d\t%s\t%d\n' % (first_name, first_index, second_name, second_index))) with open(os.path.join(LFW_HOME, 'pairsDevTest.txt'), 'wb') as f: f.write(six.b("Fake place holder that won't be tested")) with open(os.path.join(LFW_HOME, 'pairs.txt'), 'wb') as f: f.write(six.b("Fake place holder that won't be tested")) def teardown_module(): """Test fixture (clean up) run once after all tests of this module""" if os.path.isdir(SCIKIT_LEARN_DATA): shutil.rmtree(SCIKIT_LEARN_DATA) if os.path.isdir(SCIKIT_LEARN_EMPTY_DATA): shutil.rmtree(SCIKIT_LEARN_EMPTY_DATA) @raises(IOError) def test_load_empty_lfw_people(): fetch_lfw_people(data_home=SCIKIT_LEARN_EMPTY_DATA, download_if_missing=False) def test_load_fake_lfw_people(): lfw_people = fetch_lfw_people(data_home=SCIKIT_LEARN_DATA, min_faces_per_person=3, download_if_missing=False) # The data is croped around the center as a rectangular bounding box # around the face. Colors are converted to gray levels: assert_equal(lfw_people.images.shape, (10, 62, 47)) assert_equal(lfw_people.data.shape, (10, 2914)) # the target is array of person integer ids assert_array_equal(lfw_people.target, [2, 0, 1, 0, 2, 0, 2, 1, 1, 2]) # names of the persons can be found using the target_names array expected_classes = ['Abdelatif Smith', 'Abhati Kepler', 'Onur Lopez'] assert_array_equal(lfw_people.target_names, expected_classes) # It is possible to ask for the original data without any croping or color # conversion and not limit on the number of picture per person lfw_people = fetch_lfw_people(data_home=SCIKIT_LEARN_DATA, resize=None, slice_=None, color=True, download_if_missing=False) assert_equal(lfw_people.images.shape, (17, 250, 250, 3)) # the ids and class names are the same as previously assert_array_equal(lfw_people.target, [0, 0, 1, 6, 5, 6, 3, 6, 0, 3, 6, 1, 2, 4, 5, 1, 2]) assert_array_equal(lfw_people.target_names, ['Abdelatif Smith', 'Abhati Kepler', 'Camara Alvaro', 'Chen Dupont', 'John Lee', 'Lin Bauman', 'Onur Lopez']) @raises(ValueError) def test_load_fake_lfw_people_too_restrictive(): fetch_lfw_people(data_home=SCIKIT_LEARN_DATA, min_faces_per_person=100, download_if_missing=False) @raises(IOError) def test_load_empty_lfw_pairs(): fetch_lfw_pairs(data_home=SCIKIT_LEARN_EMPTY_DATA, download_if_missing=False) def test_load_fake_lfw_pairs(): lfw_pairs_train = fetch_lfw_pairs(data_home=SCIKIT_LEARN_DATA, download_if_missing=False) # The data is croped around the center as a rectangular bounding box # around the face. Colors are converted to gray levels: assert_equal(lfw_pairs_train.pairs.shape, (10, 2, 62, 47)) # the target is whether the person is the same or not assert_array_equal(lfw_pairs_train.target, [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]) # names of the persons can be found using the target_names array expected_classes = ['Different persons', 'Same person'] assert_array_equal(lfw_pairs_train.target_names, expected_classes) # It is possible to ask for the original data without any croping or color # conversion lfw_pairs_train = fetch_lfw_pairs(data_home=SCIKIT_LEARN_DATA, resize=None, slice_=None, color=True, download_if_missing=False) assert_equal(lfw_pairs_train.pairs.shape, (10, 2, 250, 250, 3)) # the ids and class names are the same as previously assert_array_equal(lfw_pairs_train.target, [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]) assert_array_equal(lfw_pairs_train.target_names, expected_classes)
mit
rahul-c1/scikit-learn
sklearn/utils/arpack.py
31
64776
""" This contains a copy of the future version of scipy.sparse.linalg.eigen.arpack.eigsh It's an upgraded wrapper of the ARPACK library which allows the use of shift-invert mode for symmetric matrices. Find a few eigenvectors and eigenvalues of a matrix. Uses ARPACK: http://www.caam.rice.edu/software/ARPACK/ """ # Wrapper implementation notes # # ARPACK Entry Points # ------------------- # The entry points to ARPACK are # - (s,d)seupd : single and double precision symmetric matrix # - (s,d,c,z)neupd: single,double,complex,double complex general matrix # This wrapper puts the *neupd (general matrix) interfaces in eigs() # and the *seupd (symmetric matrix) in eigsh(). # There is no Hermetian complex/double complex interface. # To find eigenvalues of a Hermetian matrix you # must use eigs() and not eigsh() # It might be desirable to handle the Hermetian case differently # and, for example, return real eigenvalues. # Number of eigenvalues returned and complex eigenvalues # ------------------------------------------------------ # The ARPACK nonsymmetric real and double interface (s,d)naupd return # eigenvalues and eigenvectors in real (float,double) arrays. # Since the eigenvalues and eigenvectors are, in general, complex # ARPACK puts the real and imaginary parts in consecutive entries # in real-valued arrays. This wrapper puts the real entries # into complex data types and attempts to return the requested eigenvalues # and eigenvectors. # Solver modes # ------------ # ARPACK and handle shifted and shift-inverse computations # for eigenvalues by providing a shift (sigma) and a solver. __docformat__ = "restructuredtext en" __all__ = ['eigs', 'eigsh', 'svds', 'ArpackError', 'ArpackNoConvergence'] import warnings from scipy.sparse.linalg.eigen.arpack import _arpack import numpy as np from scipy.sparse.linalg.interface import aslinearoperator, LinearOperator from scipy.sparse import identity, isspmatrix, isspmatrix_csr from scipy.linalg import lu_factor, lu_solve from scipy.sparse.sputils import isdense from scipy.sparse.linalg import gmres, splu import scipy from distutils.version import LooseVersion _type_conv = {'f': 's', 'd': 'd', 'F': 'c', 'D': 'z'} _ndigits = {'f': 5, 'd': 12, 'F': 5, 'D': 12} DNAUPD_ERRORS = { 0: "Normal exit.", 1: "Maximum number of iterations taken. " "All possible eigenvalues of OP has been found. IPARAM(5) " "returns the number of wanted converged Ritz values.", 2: "No longer an informational error. Deprecated starting " "with release 2 of ARPACK.", 3: "No shifts could be applied during a cycle of the " "Implicitly restarted Arnoldi iteration. One possibility " "is to increase the size of NCV relative to NEV. ", -1: "N must be positive.", -2: "NEV must be positive.", -3: "NCV-NEV >= 2 and less than or equal to N.", -4: "The maximum number of Arnoldi update iterations allowed " "must be greater than zero.", -5: " WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI'", -6: "BMAT must be one of 'I' or 'G'.", -7: "Length of private work array WORKL is not sufficient.", -8: "Error return from LAPACK eigenvalue calculation;", -9: "Starting vector is zero.", -10: "IPARAM(7) must be 1,2,3,4.", -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "IPARAM(1) must be equal to 0 or 1.", -13: "NEV and WHICH = 'BE' are incompatible.", -9999: "Could not build an Arnoldi factorization. " "IPARAM(5) returns the size of the current Arnoldi " "factorization. The user is advised to check that " "enough workspace and array storage has been allocated." } SNAUPD_ERRORS = DNAUPD_ERRORS ZNAUPD_ERRORS = DNAUPD_ERRORS.copy() ZNAUPD_ERRORS[-10] = "IPARAM(7) must be 1,2,3." CNAUPD_ERRORS = ZNAUPD_ERRORS DSAUPD_ERRORS = { 0: "Normal exit.", 1: "Maximum number of iterations taken. " "All possible eigenvalues of OP has been found.", 2: "No longer an informational error. Deprecated starting with " "release 2 of ARPACK.", 3: "No shifts could be applied during a cycle of the Implicitly " "restarted Arnoldi iteration. One possibility is to increase " "the size of NCV relative to NEV. ", -1: "N must be positive.", -2: "NEV must be positive.", -3: "NCV must be greater than NEV and less than or equal to N.", -4: "The maximum number of Arnoldi update iterations allowed " "must be greater than zero.", -5: "WHICH must be one of 'LM', 'SM', 'LA', 'SA' or 'BE'.", -6: "BMAT must be one of 'I' or 'G'.", -7: "Length of private work array WORKL is not sufficient.", -8: "Error return from trid. eigenvalue calculation; " "Informational error from LAPACK routine dsteqr .", -9: "Starting vector is zero.", -10: "IPARAM(7) must be 1,2,3,4,5.", -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "IPARAM(1) must be equal to 0 or 1.", -13: "NEV and WHICH = 'BE' are incompatible. ", -9999: "Could not build an Arnoldi factorization. " "IPARAM(5) returns the size of the current Arnoldi " "factorization. The user is advised to check that " "enough workspace and array storage has been allocated.", } SSAUPD_ERRORS = DSAUPD_ERRORS DNEUPD_ERRORS = { 0: "Normal exit.", 1: "The Schur form computed by LAPACK routine dlahqr " "could not be reordered by LAPACK routine dtrsen. " "Re-enter subroutine dneupd with IPARAM(5)NCV and " "increase the size of the arrays DR and DI to have " "dimension at least dimension NCV and allocate at least NCV " "columns for Z. NOTE: Not necessary if Z and V share " "the same space. Please notify the authors if this error " "occurs.", -1: "N must be positive.", -2: "NEV must be positive.", -3: "NCV-NEV >= 2 and less than or equal to N.", -5: "WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI'", -6: "BMAT must be one of 'I' or 'G'.", -7: "Length of private work WORKL array is not sufficient.", -8: "Error return from calculation of a real Schur form. " "Informational error from LAPACK routine dlahqr .", -9: "Error return from calculation of eigenvectors. " "Informational error from LAPACK routine dtrevc.", -10: "IPARAM(7) must be 1,2,3,4.", -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "HOWMNY = 'S' not yet implemented", -13: "HOWMNY must be one of 'A' or 'P' if RVEC = .true.", -14: "DNAUPD did not find any eigenvalues to sufficient " "accuracy.", -15: "DNEUPD got a different count of the number of converged " "Ritz values than DNAUPD got. This indicates the user " "probably made an error in passing data from DNAUPD to " "DNEUPD or that the data was modified before entering " "DNEUPD", } SNEUPD_ERRORS = DNEUPD_ERRORS.copy() SNEUPD_ERRORS[1] = ("The Schur form computed by LAPACK routine slahqr " "could not be reordered by LAPACK routine strsen . " "Re-enter subroutine dneupd with IPARAM(5)=NCV and " "increase the size of the arrays DR and DI to have " "dimension at least dimension NCV and allocate at least " "NCV columns for Z. NOTE: Not necessary if Z and V share " "the same space. Please notify the authors if this error " "occurs.") SNEUPD_ERRORS[-14] = ("SNAUPD did not find any eigenvalues to sufficient " "accuracy.") SNEUPD_ERRORS[-15] = ("SNEUPD got a different count of the number of " "converged Ritz values than SNAUPD got. This indicates " "the user probably made an error in passing data from " "SNAUPD to SNEUPD or that the data was modified before " "entering SNEUPD") ZNEUPD_ERRORS = {0: "Normal exit.", 1: "The Schur form computed by LAPACK routine csheqr " "could not be reordered by LAPACK routine ztrsen. " "Re-enter subroutine zneupd with IPARAM(5)=NCV and " "increase the size of the array D to have " "dimension at least dimension NCV and allocate at least " "NCV columns for Z. NOTE: Not necessary if Z and V share " "the same space. Please notify the authors if this error " "occurs.", -1: "N must be positive.", -2: "NEV must be positive.", -3: "NCV-NEV >= 1 and less than or equal to N.", -5: "WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI'", -6: "BMAT must be one of 'I' or 'G'.", -7: "Length of private work WORKL array is not sufficient.", -8: "Error return from LAPACK eigenvalue calculation. " "This should never happened.", -9: "Error return from calculation of eigenvectors. " "Informational error from LAPACK routine ztrevc.", -10: "IPARAM(7) must be 1,2,3", -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "HOWMNY = 'S' not yet implemented", -13: "HOWMNY must be one of 'A' or 'P' if RVEC = .true.", -14: "ZNAUPD did not find any eigenvalues to sufficient " "accuracy.", -15: "ZNEUPD got a different count of the number of " "converged Ritz values than ZNAUPD got. This " "indicates the user probably made an error in passing " "data from ZNAUPD to ZNEUPD or that the data was " "modified before entering ZNEUPD"} CNEUPD_ERRORS = ZNEUPD_ERRORS.copy() CNEUPD_ERRORS[-14] = ("CNAUPD did not find any eigenvalues to sufficient " "accuracy.") CNEUPD_ERRORS[-15] = ("CNEUPD got a different count of the number of " "converged Ritz values than CNAUPD got. This indicates " "the user probably made an error in passing data from " "CNAUPD to CNEUPD or that the data was modified before " "entering CNEUPD") DSEUPD_ERRORS = { 0: "Normal exit.", -1: "N must be positive.", -2: "NEV must be positive.", -3: "NCV must be greater than NEV and less than or equal to N.", -5: "WHICH must be one of 'LM', 'SM', 'LA', 'SA' or 'BE'.", -6: "BMAT must be one of 'I' or 'G'.", -7: "Length of private work WORKL array is not sufficient.", -8: ("Error return from trid. eigenvalue calculation; " "Information error from LAPACK routine dsteqr."), -9: "Starting vector is zero.", -10: "IPARAM(7) must be 1,2,3,4,5.", -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "NEV and WHICH = 'BE' are incompatible.", -14: "DSAUPD did not find any eigenvalues to sufficient accuracy.", -15: "HOWMNY must be one of 'A' or 'S' if RVEC = .true.", -16: "HOWMNY = 'S' not yet implemented", -17: ("DSEUPD got a different count of the number of converged " "Ritz values than DSAUPD got. This indicates the user " "probably made an error in passing data from DSAUPD to " "DSEUPD or that the data was modified before entering " "DSEUPD.") } SSEUPD_ERRORS = DSEUPD_ERRORS.copy() SSEUPD_ERRORS[-14] = ("SSAUPD did not find any eigenvalues " "to sufficient accuracy.") SSEUPD_ERRORS[-17] = ("SSEUPD got a different count of the number of " "converged " "Ritz values than SSAUPD got. This indicates the user " "probably made an error in passing data from SSAUPD to " "SSEUPD or that the data was modified before entering " "SSEUPD.") _SAUPD_ERRORS = {'d': DSAUPD_ERRORS, 's': SSAUPD_ERRORS} _NAUPD_ERRORS = {'d': DNAUPD_ERRORS, 's': SNAUPD_ERRORS, 'z': ZNAUPD_ERRORS, 'c': CNAUPD_ERRORS} _SEUPD_ERRORS = {'d': DSEUPD_ERRORS, 's': SSEUPD_ERRORS} _NEUPD_ERRORS = {'d': DNEUPD_ERRORS, 's': SNEUPD_ERRORS, 'z': ZNEUPD_ERRORS, 'c': CNEUPD_ERRORS} # accepted values of parameter WHICH in _SEUPD _SEUPD_WHICH = ['LM', 'SM', 'LA', 'SA', 'BE'] # accepted values of parameter WHICH in _NAUPD _NEUPD_WHICH = ['LM', 'SM', 'LR', 'SR', 'LI', 'SI'] class ArpackError(RuntimeError): """ ARPACK error """ def __init__(self, info, infodict=_NAUPD_ERRORS): msg = infodict.get(info, "Unknown error") RuntimeError.__init__(self, "ARPACK error %d: %s" % (info, msg)) class ArpackNoConvergence(ArpackError): """ ARPACK iteration did not converge Attributes ---------- eigenvalues : ndarray Partial result. Converged eigenvalues. eigenvectors : ndarray Partial result. Converged eigenvectors. """ def __init__(self, msg, eigenvalues, eigenvectors): ArpackError.__init__(self, -1, {-1: msg}) self.eigenvalues = eigenvalues self.eigenvectors = eigenvectors class _ArpackParams(object): def __init__(self, n, k, tp, mode=1, sigma=None, ncv=None, v0=None, maxiter=None, which="LM", tol=0): if k <= 0: raise ValueError("k must be positive, k=%d" % k) if maxiter is None: maxiter = n * 10 if maxiter <= 0: raise ValueError("maxiter must be positive, maxiter=%d" % maxiter) if tp not in 'fdFD': raise ValueError("matrix type must be 'f', 'd', 'F', or 'D'") if v0 is not None: # ARPACK overwrites its initial resid, make a copy self.resid = np.array(v0, copy=True) info = 1 else: self.resid = np.zeros(n, tp) info = 0 if sigma is None: #sigma not used self.sigma = 0 else: self.sigma = sigma if ncv is None: ncv = 2 * k + 1 ncv = min(ncv, n) self.v = np.zeros((n, ncv), tp) # holds Ritz vectors self.iparam = np.zeros(11, "int") # set solver mode and parameters ishfts = 1 self.mode = mode self.iparam[0] = ishfts self.iparam[2] = maxiter self.iparam[3] = 1 self.iparam[6] = mode self.n = n self.tol = tol self.k = k self.maxiter = maxiter self.ncv = ncv self.which = which self.tp = tp self.info = info self.converged = False self.ido = 0 def _raise_no_convergence(self): msg = "No convergence (%d iterations, %d/%d eigenvectors converged)" k_ok = self.iparam[4] num_iter = self.iparam[2] try: ev, vec = self.extract(True) except ArpackError as err: msg = "%s [%s]" % (msg, err) ev = np.zeros((0,)) vec = np.zeros((self.n, 0)) k_ok = 0 raise ArpackNoConvergence(msg % (num_iter, k_ok, self.k), ev, vec) class _SymmetricArpackParams(_ArpackParams): def __init__(self, n, k, tp, matvec, mode=1, M_matvec=None, Minv_matvec=None, sigma=None, ncv=None, v0=None, maxiter=None, which="LM", tol=0): # The following modes are supported: # mode = 1: # Solve the standard eigenvalue problem: # A*x = lambda*x : # A - symmetric # Arguments should be # matvec = left multiplication by A # M_matvec = None [not used] # Minv_matvec = None [not used] # # mode = 2: # Solve the general eigenvalue problem: # A*x = lambda*M*x # A - symmetric # M - symmetric positive definite # Arguments should be # matvec = left multiplication by A # M_matvec = left multiplication by M # Minv_matvec = left multiplication by M^-1 # # mode = 3: # Solve the general eigenvalue problem in shift-invert mode: # A*x = lambda*M*x # A - symmetric # M - symmetric positive semi-definite # Arguments should be # matvec = None [not used] # M_matvec = left multiplication by M # or None, if M is the identity # Minv_matvec = left multiplication by [A-sigma*M]^-1 # # mode = 4: # Solve the general eigenvalue problem in Buckling mode: # A*x = lambda*AG*x # A - symmetric positive semi-definite # AG - symmetric indefinite # Arguments should be # matvec = left multiplication by A # M_matvec = None [not used] # Minv_matvec = left multiplication by [A-sigma*AG]^-1 # # mode = 5: # Solve the general eigenvalue problem in Cayley-transformed mode: # A*x = lambda*M*x # A - symmetric # M - symmetric positive semi-definite # Arguments should be # matvec = left multiplication by A # M_matvec = left multiplication by M # or None, if M is the identity # Minv_matvec = left multiplication by [A-sigma*M]^-1 if mode == 1: if matvec is None: raise ValueError("matvec must be specified for mode=1") if M_matvec is not None: raise ValueError("M_matvec cannot be specified for mode=1") if Minv_matvec is not None: raise ValueError("Minv_matvec cannot be specified for mode=1") self.OP = matvec self.B = lambda x: x self.bmat = 'I' elif mode == 2: if matvec is None: raise ValueError("matvec must be specified for mode=2") if M_matvec is None: raise ValueError("M_matvec must be specified for mode=2") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified for mode=2") self.OP = lambda x: Minv_matvec(matvec(x)) self.OPa = Minv_matvec self.OPb = matvec self.B = M_matvec self.bmat = 'G' elif mode == 3: if matvec is not None: raise ValueError("matvec must not be specified for mode=3") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified for mode=3") if M_matvec is None: self.OP = Minv_matvec self.OPa = Minv_matvec self.B = lambda x: x self.bmat = 'I' else: self.OP = lambda x: Minv_matvec(M_matvec(x)) self.OPa = Minv_matvec self.B = M_matvec self.bmat = 'G' elif mode == 4: if matvec is None: raise ValueError("matvec must be specified for mode=4") if M_matvec is not None: raise ValueError("M_matvec must not be specified for mode=4") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified for mode=4") self.OPa = Minv_matvec self.OP = lambda x: self.OPa(matvec(x)) self.B = matvec self.bmat = 'G' elif mode == 5: if matvec is None: raise ValueError("matvec must be specified for mode=5") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified for mode=5") self.OPa = Minv_matvec self.A_matvec = matvec if M_matvec is None: self.OP = lambda x: Minv_matvec(matvec(x) + sigma * x) self.B = lambda x: x self.bmat = 'I' else: self.OP = lambda x: Minv_matvec(matvec(x) + sigma * M_matvec(x)) self.B = M_matvec self.bmat = 'G' else: raise ValueError("mode=%i not implemented" % mode) if which not in _SEUPD_WHICH: raise ValueError("which must be one of %s" % ' '.join(_SEUPD_WHICH)) if k >= n: raise ValueError("k must be less than rank(A), k=%d" % k) _ArpackParams.__init__(self, n, k, tp, mode, sigma, ncv, v0, maxiter, which, tol) if self.ncv > n or self.ncv <= k: raise ValueError("ncv must be k<ncv<=n, ncv=%s" % self.ncv) self.workd = np.zeros(3 * n, self.tp) self.workl = np.zeros(self.ncv * (self.ncv + 8), self.tp) ltr = _type_conv[self.tp] if ltr not in ["s", "d"]: raise ValueError("Input matrix is not real-valued.") self._arpack_solver = _arpack.__dict__[ltr + 'saupd'] self._arpack_extract = _arpack.__dict__[ltr + 'seupd'] self.iterate_infodict = _SAUPD_ERRORS[ltr] self.extract_infodict = _SEUPD_ERRORS[ltr] self.ipntr = np.zeros(11, "int") def iterate(self): self.ido, self.resid, self.v, self.iparam, self.ipntr, self.info = \ self._arpack_solver(self.ido, self.bmat, self.which, self.k, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.workd, self.workl, self.info) xslice = slice(self.ipntr[0] - 1, self.ipntr[0] - 1 + self.n) yslice = slice(self.ipntr[1] - 1, self.ipntr[1] - 1 + self.n) if self.ido == -1: # initialization self.workd[yslice] = self.OP(self.workd[xslice]) elif self.ido == 1: # compute y = Op*x if self.mode == 1: self.workd[yslice] = self.OP(self.workd[xslice]) elif self.mode == 2: self.workd[xslice] = self.OPb(self.workd[xslice]) self.workd[yslice] = self.OPa(self.workd[xslice]) elif self.mode == 5: Bxslice = slice(self.ipntr[2] - 1, self.ipntr[2] - 1 + self.n) Ax = self.A_matvec(self.workd[xslice]) self.workd[yslice] = self.OPa(Ax + (self.sigma * self.workd[Bxslice])) else: Bxslice = slice(self.ipntr[2] - 1, self.ipntr[2] - 1 + self.n) self.workd[yslice] = self.OPa(self.workd[Bxslice]) elif self.ido == 2: self.workd[yslice] = self.B(self.workd[xslice]) elif self.ido == 3: raise ValueError("ARPACK requested user shifts. Assure ISHIFT==0") else: self.converged = True if self.info == 0: pass elif self.info == 1: self._raise_no_convergence() else: raise ArpackError(self.info, infodict=self.iterate_infodict) def extract(self, return_eigenvectors): rvec = return_eigenvectors ierr = 0 howmny = 'A' # return all eigenvectors sselect = np.zeros(self.ncv, 'int') # unused d, z, ierr = self._arpack_extract(rvec, howmny, sselect, self.sigma, self.bmat, self.which, self.k, self.tol, self.resid, self.v, self.iparam[0:7], self.ipntr, self.workd[0:2 * self.n], self.workl, ierr) if ierr != 0: raise ArpackError(ierr, infodict=self.extract_infodict) k_ok = self.iparam[4] d = d[:k_ok] z = z[:, :k_ok] if return_eigenvectors: return d, z else: return d class _UnsymmetricArpackParams(_ArpackParams): def __init__(self, n, k, tp, matvec, mode=1, M_matvec=None, Minv_matvec=None, sigma=None, ncv=None, v0=None, maxiter=None, which="LM", tol=0): # The following modes are supported: # mode = 1: # Solve the standard eigenvalue problem: # A*x = lambda*x # A - square matrix # Arguments should be # matvec = left multiplication by A # M_matvec = None [not used] # Minv_matvec = None [not used] # # mode = 2: # Solve the generalized eigenvalue problem: # A*x = lambda*M*x # A - square matrix # M - symmetric, positive semi-definite # Arguments should be # matvec = left multiplication by A # M_matvec = left multiplication by M # Minv_matvec = left multiplication by M^-1 # # mode = 3,4: # Solve the general eigenvalue problem in shift-invert mode: # A*x = lambda*M*x # A - square matrix # M - symmetric, positive semi-definite # Arguments should be # matvec = None [not used] # M_matvec = left multiplication by M # or None, if M is the identity # Minv_matvec = left multiplication by [A-sigma*M]^-1 # if A is real and mode==3, use the real part of Minv_matvec # if A is real and mode==4, use the imag part of Minv_matvec # if A is complex and mode==3, # use real and imag parts of Minv_matvec if mode == 1: if matvec is None: raise ValueError("matvec must be specified for mode=1") if M_matvec is not None: raise ValueError("M_matvec cannot be specified for mode=1") if Minv_matvec is not None: raise ValueError("Minv_matvec cannot be specified for mode=1") self.OP = matvec self.B = lambda x: x self.bmat = 'I' elif mode == 2: if matvec is None: raise ValueError("matvec must be specified for mode=2") if M_matvec is None: raise ValueError("M_matvec must be specified for mode=2") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified for mode=2") self.OP = lambda x: Minv_matvec(matvec(x)) self.OPa = Minv_matvec self.OPb = matvec self.B = M_matvec self.bmat = 'G' elif mode in (3, 4): if matvec is None: raise ValueError("matvec must be specified " "for mode in (3,4)") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified " "for mode in (3,4)") self.matvec = matvec if tp in 'DF': # complex type if mode == 3: self.OPa = Minv_matvec else: raise ValueError("mode=4 invalid for complex A") else: # real type if mode == 3: self.OPa = lambda x: np.real(Minv_matvec(x)) else: self.OPa = lambda x: np.imag(Minv_matvec(x)) if M_matvec is None: self.B = lambda x: x self.bmat = 'I' self.OP = self.OPa else: self.B = M_matvec self.bmat = 'G' self.OP = lambda x: self.OPa(M_matvec(x)) else: raise ValueError("mode=%i not implemented" % mode) if which not in _NEUPD_WHICH: raise ValueError("Parameter which must be one of %s" % ' '.join(_NEUPD_WHICH)) if k >= n - 1: raise ValueError("k must be less than rank(A)-1, k=%d" % k) _ArpackParams.__init__(self, n, k, tp, mode, sigma, ncv, v0, maxiter, which, tol) if self.ncv > n or self.ncv <= k + 1: raise ValueError("ncv must be k+1<ncv<=n, ncv=%s" % self.ncv) self.workd = np.zeros(3 * n, self.tp) self.workl = np.zeros(3 * self.ncv * (self.ncv + 2), self.tp) ltr = _type_conv[self.tp] self._arpack_solver = _arpack.__dict__[ltr + 'naupd'] self._arpack_extract = _arpack.__dict__[ltr + 'neupd'] self.iterate_infodict = _NAUPD_ERRORS[ltr] self.extract_infodict = _NEUPD_ERRORS[ltr] self.ipntr = np.zeros(14, "int") if self.tp in 'FD': self.rwork = np.zeros(self.ncv, self.tp.lower()) else: self.rwork = None def iterate(self): if self.tp in 'fd': self.ido, self.resid, self.v, self.iparam, self.ipntr, self.info =\ self._arpack_solver(self.ido, self.bmat, self.which, self.k, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.workd, self.workl, self.info) else: self.ido, self.resid, self.v, self.iparam, self.ipntr, self.info =\ self._arpack_solver(self.ido, self.bmat, self.which, self.k, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.workd, self.workl, self.rwork, self.info) xslice = slice(self.ipntr[0] - 1, self.ipntr[0] - 1 + self.n) yslice = slice(self.ipntr[1] - 1, self.ipntr[1] - 1 + self.n) if self.ido == -1: # initialization self.workd[yslice] = self.OP(self.workd[xslice]) elif self.ido == 1: # compute y = Op*x if self.mode in (1, 2): self.workd[yslice] = self.OP(self.workd[xslice]) else: Bxslice = slice(self.ipntr[2] - 1, self.ipntr[2] - 1 + self.n) self.workd[yslice] = self.OPa(self.workd[Bxslice]) elif self.ido == 2: self.workd[yslice] = self.B(self.workd[xslice]) elif self.ido == 3: raise ValueError("ARPACK requested user shifts. Assure ISHIFT==0") else: self.converged = True if self.info == 0: pass elif self.info == 1: self._raise_no_convergence() else: raise ArpackError(self.info, infodict=self.iterate_infodict) def extract(self, return_eigenvectors): k, n = self.k, self.n ierr = 0 howmny = 'A' # return all eigenvectors sselect = np.zeros(self.ncv, 'int') # unused sigmar = np.real(self.sigma) sigmai = np.imag(self.sigma) workev = np.zeros(3 * self.ncv, self.tp) if self.tp in 'fd': dr = np.zeros(k + 1, self.tp) di = np.zeros(k + 1, self.tp) zr = np.zeros((n, k + 1), self.tp) dr, di, zr, ierr = \ self._arpack_extract( return_eigenvectors, howmny, sselect, sigmar, sigmai, workev, self.bmat, self.which, k, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.workd, self.workl, self.info) if ierr != 0: raise ArpackError(ierr, infodict=self.extract_infodict) nreturned = self.iparam[4] # number of good eigenvalues returned # Build complex eigenvalues from real and imaginary parts d = dr + 1.0j * di # Arrange the eigenvectors: complex eigenvectors are stored as # real,imaginary in consecutive columns z = zr.astype(self.tp.upper()) # The ARPACK nonsymmetric real and double interface (s,d)naupd # return eigenvalues and eigenvectors in real (float,double) # arrays. # Efficiency: this should check that return_eigenvectors == True # before going through this construction. if sigmai == 0: i = 0 while i <= k: # check if complex if abs(d[i].imag) != 0: # this is a complex conjugate pair with eigenvalues # in consecutive columns if i < k: z[:, i] = zr[:, i] + 1.0j * zr[:, i + 1] z[:, i + 1] = z[:, i].conjugate() i += 1 else: #last eigenvalue is complex: the imaginary part of # the eigenvector has not been returned #this can only happen if nreturned > k, so we'll # throw out this case. nreturned -= 1 i += 1 else: # real matrix, mode 3 or 4, imag(sigma) is nonzero: # see remark 3 in <s,d>neupd.f # Build complex eigenvalues from real and imaginary parts i = 0 while i <= k: if abs(d[i].imag) == 0: d[i] = np.dot(zr[:, i], self.matvec(zr[:, i])) else: if i < k: z[:, i] = zr[:, i] + 1.0j * zr[:, i + 1] z[:, i + 1] = z[:, i].conjugate() d[i] = ((np.dot(zr[:, i], self.matvec(zr[:, i])) + np.dot(zr[:, i + 1], self.matvec(zr[:, i + 1]))) + 1j * (np.dot(zr[:, i], self.matvec(zr[:, i + 1])) - np.dot(zr[:, i + 1], self.matvec(zr[:, i])))) d[i + 1] = d[i].conj() i += 1 else: #last eigenvalue is complex: the imaginary part of # the eigenvector has not been returned #this can only happen if nreturned > k, so we'll # throw out this case. nreturned -= 1 i += 1 # Now we have k+1 possible eigenvalues and eigenvectors # Return the ones specified by the keyword "which" if nreturned <= k: # we got less or equal as many eigenvalues we wanted d = d[:nreturned] z = z[:, :nreturned] else: # we got one extra eigenvalue (likely a cc pair, but which?) # cut at approx precision for sorting rd = np.round(d, decimals=_ndigits[self.tp]) if self.which in ['LR', 'SR']: ind = np.argsort(rd.real) elif self.which in ['LI', 'SI']: # for LI,SI ARPACK returns largest,smallest # abs(imaginary) why? ind = np.argsort(abs(rd.imag)) else: ind = np.argsort(abs(rd)) if self.which in ['LR', 'LM', 'LI']: d = d[ind[-k:]] z = z[:, ind[-k:]] if self.which in ['SR', 'SM', 'SI']: d = d[ind[:k]] z = z[:, ind[:k]] else: # complex is so much simpler... d, z, ierr =\ self._arpack_extract( return_eigenvectors, howmny, sselect, self.sigma, workev, self.bmat, self.which, k, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.workd, self.workl, self.rwork, ierr) if ierr != 0: raise ArpackError(ierr, infodict=self.extract_infodict) k_ok = self.iparam[4] d = d[:k_ok] z = z[:, :k_ok] if return_eigenvectors: return d, z else: return d def _aslinearoperator_with_dtype(m): m = aslinearoperator(m) if not hasattr(m, 'dtype'): x = np.zeros(m.shape[1]) m.dtype = (m * x).dtype return m class SpLuInv(LinearOperator): """ SpLuInv: helper class to repeatedly solve M*x=b using a sparse LU-decopposition of M """ def __init__(self, M): self.M_lu = splu(M) LinearOperator.__init__(self, M.shape, self._matvec, dtype=M.dtype) self.isreal = not np.issubdtype(self.dtype, np.complexfloating) def _matvec(self, x): # careful here: splu.solve will throw away imaginary # part of x if M is real if self.isreal and np.issubdtype(x.dtype, np.complexfloating): return (self.M_lu.solve(np.real(x)) + 1j * self.M_lu.solve(np.imag(x))) else: return self.M_lu.solve(x) class LuInv(LinearOperator): """ LuInv: helper class to repeatedly solve M*x=b using an LU-decomposition of M """ def __init__(self, M): self.M_lu = lu_factor(M) LinearOperator.__init__(self, M.shape, self._matvec, dtype=M.dtype) def _matvec(self, x): return lu_solve(self.M_lu, x) class IterInv(LinearOperator): """ IterInv: helper class to repeatedly solve M*x=b using an iterative method. """ def __init__(self, M, ifunc=gmres, tol=0): if tol <= 0: # when tol=0, ARPACK uses machine tolerance as calculated # by LAPACK's _LAMCH function. We should match this tol = np.finfo(M.dtype).eps self.M = M self.ifunc = ifunc self.tol = tol if hasattr(M, 'dtype'): dtype = M.dtype else: x = np.zeros(M.shape[1]) dtype = (M * x).dtype LinearOperator.__init__(self, M.shape, self._matvec, dtype=dtype) def _matvec(self, x): b, info = self.ifunc(self.M, x, tol=self.tol) if info != 0: raise ValueError("Error in inverting M: function " "%s did not converge (info = %i)." % (self.ifunc.__name__, info)) return b class IterOpInv(LinearOperator): """ IterOpInv: helper class to repeatedly solve [A-sigma*M]*x = b using an iterative method """ def __init__(self, A, M, sigma, ifunc=gmres, tol=0): if tol <= 0: # when tol=0, ARPACK uses machine tolerance as calculated # by LAPACK's _LAMCH function. We should match this tol = np.finfo(A.dtype).eps self.A = A self.M = M self.sigma = sigma self.ifunc = ifunc self.tol = tol x = np.zeros(A.shape[1]) if M is None: dtype = self.mult_func_M_None(x).dtype self.OP = LinearOperator(self.A.shape, self.mult_func_M_None, dtype=dtype) else: dtype = self.mult_func(x).dtype self.OP = LinearOperator(self.A.shape, self.mult_func, dtype=dtype) LinearOperator.__init__(self, A.shape, self._matvec, dtype=dtype) def mult_func(self, x): return self.A.matvec(x) - self.sigma * self.M.matvec(x) def mult_func_M_None(self, x): return self.A.matvec(x) - self.sigma * x def _matvec(self, x): b, info = self.ifunc(self.OP, x, tol=self.tol) if info != 0: raise ValueError("Error in inverting [A-sigma*M]: function " "%s did not converge (info = %i)." % (self.ifunc.__name__, info)) return b def get_inv_matvec(M, symmetric=False, tol=0): if isdense(M): return LuInv(M).matvec elif isspmatrix(M): if isspmatrix_csr(M) and symmetric: M = M.T return SpLuInv(M).matvec else: return IterInv(M, tol=tol).matvec def get_OPinv_matvec(A, M, sigma, symmetric=False, tol=0): if sigma == 0: return get_inv_matvec(A, symmetric=symmetric, tol=tol) if M is None: #M is the identity matrix if isdense(A): if (np.issubdtype(A.dtype, np.complexfloating) or np.imag(sigma) == 0): A = np.copy(A) else: A = A + 0j A.flat[::A.shape[1] + 1] -= sigma return LuInv(A).matvec elif isspmatrix(A): A = A - sigma * identity(A.shape[0]) if symmetric and isspmatrix_csr(A): A = A.T return SpLuInv(A.tocsc()).matvec else: return IterOpInv(_aslinearoperator_with_dtype(A), M, sigma, tol=tol).matvec else: if ((not isdense(A) and not isspmatrix(A)) or (not isdense(M) and not isspmatrix(M))): return IterOpInv(_aslinearoperator_with_dtype(A), _aslinearoperator_with_dtype(M), sigma, tol=tol).matvec elif isdense(A) or isdense(M): return LuInv(A - sigma * M).matvec else: OP = A - sigma * M if symmetric and isspmatrix_csr(OP): OP = OP.T return SpLuInv(OP.tocsc()).matvec def _eigs(A, k=6, M=None, sigma=None, which='LM', v0=None, ncv=None, maxiter=None, tol=0, return_eigenvectors=True, Minv=None, OPinv=None, OPpart=None): """ Find k eigenvalues and eigenvectors of the square matrix A. Solves ``A * x[i] = w[i] * x[i]``, the standard eigenvalue problem for w[i] eigenvalues with corresponding eigenvectors x[i]. If M is specified, solves ``A * x[i] = w[i] * M * x[i]``, the generalized eigenvalue problem for w[i] eigenvalues with corresponding eigenvectors x[i] Parameters ---------- A : An N x N matrix, array, sparse matrix, or LinearOperator representing the operation A * x, where A is a real or complex square matrix. k : integer The number of eigenvalues and eigenvectors desired. `k` must be smaller than N. It is not possible to compute all eigenvectors of a matrix. Returns ------- w : array Array of k eigenvalues. v : array An array of `k` eigenvectors. ``v[:, i]`` is the eigenvector corresponding to the eigenvalue w[i]. Other Parameters ---------------- M : An N x N matrix, array, sparse matrix, or LinearOperator representing the operation M*x for the generalized eigenvalue problem ``A * x = w * M * x`` M must represent a real symmetric matrix. For best results, M should be of the same type as A. Additionally: * If sigma==None, M is positive definite * If sigma is specified, M is positive semi-definite If sigma==None, eigs requires an operator to compute the solution of the linear equation `M * x = b`. This is done internally via a (sparse) LU decomposition for an explicit matrix M, or via an iterative solver for a general linear operator. Alternatively, the user can supply the matrix or operator Minv, which gives x = Minv * b = M^-1 * b sigma : real or complex Find eigenvalues near sigma using shift-invert mode. This requires an operator to compute the solution of the linear system `[A - sigma * M] * x = b`, where M is the identity matrix if unspecified. This is computed internally via a (sparse) LU decomposition for explicit matrices A & M, or via an iterative solver if either A or M is a general linear operator. Alternatively, the user can supply the matrix or operator OPinv, which gives x = OPinv * b = [A - sigma * M]^-1 * b. For a real matrix A, shift-invert can either be done in imaginary mode or real mode, specified by the parameter OPpart ('r' or 'i'). Note that when sigma is specified, the keyword 'which' (below) refers to the shifted eigenvalues w'[i] where: * If A is real and OPpart == 'r' (default), w'[i] = 1/2 * [ 1/(w[i]-sigma) + 1/(w[i]-conj(sigma)) ] * If A is real and OPpart == 'i', w'[i] = 1/2i * [ 1/(w[i]-sigma) - 1/(w[i]-conj(sigma)) ] * If A is complex, w'[i] = 1/(w[i]-sigma) v0 : array Starting vector for iteration. ncv : integer The number of Lanczos vectors generated `ncv` must be greater than `k`; it is recommended that ``ncv > 2*k``. which : string ['LM' | 'SM' | 'LR' | 'SR' | 'LI' | 'SI'] Which `k` eigenvectors and eigenvalues to find: - 'LM' : largest magnitude - 'SM' : smallest magnitude - 'LR' : largest real part - 'SR' : smallest real part - 'LI' : largest imaginary part - 'SI' : smallest imaginary part When sigma != None, 'which' refers to the shifted eigenvalues w'[i] (see discussion in 'sigma', above). ARPACK is generally better at finding large values than small values. If small eigenvalues are desired, consider using shift-invert mode for better performance. maxiter : integer Maximum number of Arnoldi update iterations allowed tol : float Relative accuracy for eigenvalues (stopping criterion) The default value of 0 implies machine precision. return_eigenvectors : boolean Return eigenvectors (True) in addition to eigenvalues Minv : N x N matrix, array, sparse matrix, or linear operator See notes in M, above. OPinv : N x N matrix, array, sparse matrix, or linear operator See notes in sigma, above. OPpart : 'r' or 'i'. See notes in sigma, above Raises ------ ArpackNoConvergence When the requested convergence is not obtained. The currently converged eigenvalues and eigenvectors can be found as ``eigenvalues`` and ``eigenvectors`` attributes of the exception object. See Also -------- eigsh : eigenvalues and eigenvectors for symmetric matrix A svds : singular value decomposition for a matrix A Examples -------- Find 6 eigenvectors of the identity matrix: >>> from sklearn.utils.arpack import eigs >>> id = np.identity(13) >>> vals, vecs = eigs(id, k=6) >>> vals array([ 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j]) >>> vecs.shape (13, 6) Notes ----- This function is a wrapper to the ARPACK [1]_ SNEUPD, DNEUPD, CNEUPD, ZNEUPD, functions which use the Implicitly Restarted Arnoldi Method to find the eigenvalues and eigenvectors [2]_. References ---------- .. [1] ARPACK Software, http://www.caam.rice.edu/software/ARPACK/ .. [2] R. B. Lehoucq, D. C. Sorensen, and C. Yang, ARPACK USERS GUIDE: Solution of Large Scale Eigenvalue Problems by Implicitly Restarted Arnoldi Methods. SIAM, Philadelphia, PA, 1998. """ if A.shape[0] != A.shape[1]: raise ValueError('expected square matrix (shape=%s)' % (A.shape,)) if M is not None: if M.shape != A.shape: raise ValueError('wrong M dimensions %s, should be %s' % (M.shape, A.shape)) if np.dtype(M.dtype).char.lower() != np.dtype(A.dtype).char.lower(): warnings.warn('M does not have the same type precision as A. ' 'This may adversely affect ARPACK convergence') n = A.shape[0] if k <= 0 or k >= n: raise ValueError("k must be between 1 and rank(A)-1") if sigma is None: matvec = _aslinearoperator_with_dtype(A).matvec if OPinv is not None: raise ValueError("OPinv should not be specified " "with sigma = None.") if OPpart is not None: raise ValueError("OPpart should not be specified with " "sigma = None or complex A") if M is None: #standard eigenvalue problem mode = 1 M_matvec = None Minv_matvec = None if Minv is not None: raise ValueError("Minv should not be " "specified with M = None.") else: #general eigenvalue problem mode = 2 if Minv is None: Minv_matvec = get_inv_matvec(M, symmetric=True, tol=tol) else: Minv = _aslinearoperator_with_dtype(Minv) Minv_matvec = Minv.matvec M_matvec = _aslinearoperator_with_dtype(M).matvec else: #sigma is not None: shift-invert mode if np.issubdtype(A.dtype, np.complexfloating): if OPpart is not None: raise ValueError("OPpart should not be specified " "with sigma=None or complex A") mode = 3 elif OPpart is None or OPpart.lower() == 'r': mode = 3 elif OPpart.lower() == 'i': if np.imag(sigma) == 0: raise ValueError("OPpart cannot be 'i' if sigma is real") mode = 4 else: raise ValueError("OPpart must be one of ('r','i')") matvec = _aslinearoperator_with_dtype(A).matvec if Minv is not None: raise ValueError("Minv should not be specified when sigma is") if OPinv is None: Minv_matvec = get_OPinv_matvec(A, M, sigma, symmetric=False, tol=tol) else: OPinv = _aslinearoperator_with_dtype(OPinv) Minv_matvec = OPinv.matvec if M is None: M_matvec = None else: M_matvec = _aslinearoperator_with_dtype(M).matvec params = _UnsymmetricArpackParams(n, k, A.dtype.char, matvec, mode, M_matvec, Minv_matvec, sigma, ncv, v0, maxiter, which, tol) while not params.converged: params.iterate() return params.extract(return_eigenvectors) def _eigsh(A, k=6, M=None, sigma=None, which='LM', v0=None, ncv=None, maxiter=None, tol=0, return_eigenvectors=True, Minv=None, OPinv=None, mode='normal'): """ Find k eigenvalues and eigenvectors of the real symmetric square matrix or complex hermitian matrix A. Solves ``A * x[i] = w[i] * x[i]``, the standard eigenvalue problem for w[i] eigenvalues with corresponding eigenvectors x[i]. If M is specified, solves ``A * x[i] = w[i] * M * x[i]``, the generalized eigenvalue problem for w[i] eigenvalues with corresponding eigenvectors x[i] Parameters ---------- A : An N x N matrix, array, sparse matrix, or LinearOperator representing the operation A * x, where A is a real symmetric matrix For buckling mode (see below) A must additionally be positive-definite k : integer The number of eigenvalues and eigenvectors desired. `k` must be smaller than N. It is not possible to compute all eigenvectors of a matrix. Returns ------- w : array Array of k eigenvalues v : array An array of k eigenvectors The v[i] is the eigenvector corresponding to the eigenvector w[i] Other Parameters ---------------- M : An N x N matrix, array, sparse matrix, or linear operator representing the operation M * x for the generalized eigenvalue problem ``A * x = w * M * x``. M must represent a real, symmetric matrix. For best results, M should be of the same type as A. Additionally: * If sigma == None, M is symmetric positive definite * If sigma is specified, M is symmetric positive semi-definite * In buckling mode, M is symmetric indefinite. If sigma == None, eigsh requires an operator to compute the solution of the linear equation `M * x = b`. This is done internally via a (sparse) LU decomposition for an explicit matrix M, or via an iterative solver for a general linear operator. Alternatively, the user can supply the matrix or operator Minv, which gives x = Minv * b = M^-1 * b sigma : real Find eigenvalues near sigma using shift-invert mode. This requires an operator to compute the solution of the linear system `[A - sigma * M] x = b`, where M is the identity matrix if unspecified. This is computed internally via a (sparse) LU decomposition for explicit matrices A & M, or via an iterative solver if either A or M is a general linear operator. Alternatively, the user can supply the matrix or operator OPinv, which gives x = OPinv * b = [A - sigma * M]^-1 * b. Note that when sigma is specified, the keyword 'which' refers to the shifted eigenvalues w'[i] where: - if mode == 'normal', w'[i] = 1 / (w[i] - sigma) - if mode == 'cayley', w'[i] = (w[i] + sigma) / (w[i] - sigma) - if mode == 'buckling', w'[i] = w[i] / (w[i] - sigma) (see further discussion in 'mode' below) v0 : array Starting vector for iteration. ncv : integer The number of Lanczos vectors generated ncv must be greater than k and smaller than n; it is recommended that ncv > 2*k which : string ['LM' | 'SM' | 'LA' | 'SA' | 'BE'] If A is a complex hermitian matrix, 'BE' is invalid. Which `k` eigenvectors and eigenvalues to find: - 'LM' : Largest (in magnitude) eigenvalues - 'SM' : Smallest (in magnitude) eigenvalues - 'LA' : Largest (algebraic) eigenvalues - 'SA' : Smallest (algebraic) eigenvalues - 'BE' : Half (k/2) from each end of the spectrum When k is odd, return one more (k/2+1) from the high end When sigma != None, 'which' refers to the shifted eigenvalues w'[i] (see discussion in 'sigma', above). ARPACK is generally better at finding large values than small values. If small eigenvalues are desired, consider using shift-invert mode for better performance. maxiter : integer Maximum number of Arnoldi update iterations allowed tol : float Relative accuracy for eigenvalues (stopping criterion). The default value of 0 implies machine precision. Minv : N x N matrix, array, sparse matrix, or LinearOperator See notes in M, above OPinv : N x N matrix, array, sparse matrix, or LinearOperator See notes in sigma, above. return_eigenvectors : boolean Return eigenvectors (True) in addition to eigenvalues mode : string ['normal' | 'buckling' | 'cayley'] Specify strategy to use for shift-invert mode. This argument applies only for real-valued A and sigma != None. For shift-invert mode, ARPACK internally solves the eigenvalue problem ``OP * x'[i] = w'[i] * B * x'[i]`` and transforms the resulting Ritz vectors x'[i] and Ritz values w'[i] into the desired eigenvectors and eigenvalues of the problem ``A * x[i] = w[i] * M * x[i]``. The modes are as follows: - 'normal' : OP = [A - sigma * M]^-1 * M B = M w'[i] = 1 / (w[i] - sigma) - 'buckling' : OP = [A - sigma * M]^-1 * A B = A w'[i] = w[i] / (w[i] - sigma) - 'cayley' : OP = [A - sigma * M]^-1 * [A + sigma * M] B = M w'[i] = (w[i] + sigma) / (w[i] - sigma) The choice of mode will affect which eigenvalues are selected by the keyword 'which', and can also impact the stability of convergence (see [2] for a discussion) Raises ------ ArpackNoConvergence When the requested convergence is not obtained. The currently converged eigenvalues and eigenvectors can be found as ``eigenvalues`` and ``eigenvectors`` attributes of the exception object. See Also -------- eigs : eigenvalues and eigenvectors for a general (nonsymmetric) matrix A svds : singular value decomposition for a matrix A Notes ----- This function is a wrapper to the ARPACK [1]_ SSEUPD and DSEUPD functions which use the Implicitly Restarted Lanczos Method to find the eigenvalues and eigenvectors [2]_. Examples -------- >>> from sklearn.utils.arpack import eigsh >>> id = np.identity(13) >>> vals, vecs = eigsh(id, k=6) >>> vals # doctest: +SKIP array([ 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j]) >>> print(vecs.shape) (13, 6) References ---------- .. [1] ARPACK Software, http://www.caam.rice.edu/software/ARPACK/ .. [2] R. B. Lehoucq, D. C. Sorensen, and C. Yang, ARPACK USERS GUIDE: Solution of Large Scale Eigenvalue Problems by Implicitly Restarted Arnoldi Methods. SIAM, Philadelphia, PA, 1998. """ # complex hermitian matrices should be solved with eigs if np.issubdtype(A.dtype, np.complexfloating): if mode != 'normal': raise ValueError("mode=%s cannot be used with " "complex matrix A" % mode) if which == 'BE': raise ValueError("which='BE' cannot be used with complex matrix A") elif which == 'LA': which = 'LR' elif which == 'SA': which = 'SR' ret = eigs(A, k, M=M, sigma=sigma, which=which, v0=v0, ncv=ncv, maxiter=maxiter, tol=tol, return_eigenvectors=return_eigenvectors, Minv=Minv, OPinv=OPinv) if return_eigenvectors: return ret[0].real, ret[1] else: return ret.real if A.shape[0] != A.shape[1]: raise ValueError('expected square matrix (shape=%s)' % (A.shape,)) if M is not None: if M.shape != A.shape: raise ValueError('wrong M dimensions %s, should be %s' % (M.shape, A.shape)) if np.dtype(M.dtype).char.lower() != np.dtype(A.dtype).char.lower(): warnings.warn('M does not have the same type precision as A. ' 'This may adversely affect ARPACK convergence') n = A.shape[0] if k <= 0 or k >= n: raise ValueError("k must be between 1 and rank(A)-1") if sigma is None: A = _aslinearoperator_with_dtype(A) matvec = A.matvec if OPinv is not None: raise ValueError("OPinv should not be specified " "with sigma = None.") if M is None: #standard eigenvalue problem mode = 1 M_matvec = None Minv_matvec = None if Minv is not None: raise ValueError("Minv should not be " "specified with M = None.") else: #general eigenvalue problem mode = 2 if Minv is None: Minv_matvec = get_inv_matvec(M, symmetric=True, tol=tol) else: Minv = _aslinearoperator_with_dtype(Minv) Minv_matvec = Minv.matvec M_matvec = _aslinearoperator_with_dtype(M).matvec else: # sigma is not None: shift-invert mode if Minv is not None: raise ValueError("Minv should not be specified when sigma is") # normal mode if mode == 'normal': mode = 3 matvec = None if OPinv is None: Minv_matvec = get_OPinv_matvec(A, M, sigma, symmetric=True, tol=tol) else: OPinv = _aslinearoperator_with_dtype(OPinv) Minv_matvec = OPinv.matvec if M is None: M_matvec = None else: M = _aslinearoperator_with_dtype(M) M_matvec = M.matvec # buckling mode elif mode == 'buckling': mode = 4 if OPinv is None: Minv_matvec = get_OPinv_matvec(A, M, sigma, symmetric=True, tol=tol) else: Minv_matvec = _aslinearoperator_with_dtype(OPinv).matvec matvec = _aslinearoperator_with_dtype(A).matvec M_matvec = None # cayley-transform mode elif mode == 'cayley': mode = 5 matvec = _aslinearoperator_with_dtype(A).matvec if OPinv is None: Minv_matvec = get_OPinv_matvec(A, M, sigma, symmetric=True, tol=tol) else: Minv_matvec = _aslinearoperator_with_dtype(OPinv).matvec if M is None: M_matvec = None else: M_matvec = _aslinearoperator_with_dtype(M).matvec # unrecognized mode else: raise ValueError("unrecognized mode '%s'" % mode) params = _SymmetricArpackParams(n, k, A.dtype.char, matvec, mode, M_matvec, Minv_matvec, sigma, ncv, v0, maxiter, which, tol) while not params.converged: params.iterate() return params.extract(return_eigenvectors) def _svds(A, k=6, ncv=None, tol=0): """Compute k singular values/vectors for a sparse matrix using ARPACK. Parameters ---------- A : sparse matrix Array to compute the SVD on k : int, optional Number of singular values and vectors to compute. ncv : integer The number of Lanczos vectors generated ncv must be greater than k+1 and smaller than n; it is recommended that ncv > 2*k tol : float, optional Tolerance for singular values. Zero (default) means machine precision. Notes ----- This is a naive implementation using an eigensolver on A.H * A or A * A.H, depending on which one is more efficient. """ if not (isinstance(A, np.ndarray) or isspmatrix(A)): A = np.asarray(A) n, m = A.shape if np.issubdtype(A.dtype, np.complexfloating): herm = lambda x: x.T.conjugate() eigensolver = eigs else: herm = lambda x: x.T eigensolver = eigsh if n > m: X = A XH = herm(A) else: XH = A X = herm(A) if hasattr(XH, 'dot'): def matvec_XH_X(x): return XH.dot(X.dot(x)) else: def matvec_XH_X(x): return np.dot(XH, np.dot(X, x)) XH_X = LinearOperator(matvec=matvec_XH_X, dtype=X.dtype, shape=(X.shape[1], X.shape[1])) # Ignore deprecation warnings here: dot on matrices is deprecated, # but this code is a backport anyhow with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) eigvals, eigvec = eigensolver(XH_X, k=k, tol=tol ** 2) s = np.sqrt(eigvals) if n > m: v = eigvec if hasattr(X, 'dot'): u = X.dot(v) / s else: u = np.dot(X, v) / s vh = herm(v) else: u = eigvec if hasattr(X, 'dot'): vh = herm(X.dot(u) / s) else: vh = herm(np.dot(X, u) / s) return u, s, vh # check if backport is actually needed: if scipy.version.version >= LooseVersion('0.10'): from scipy.sparse.linalg import eigs, eigsh, svds else: eigs, eigsh, svds = _eigs, _eigsh, _svds
bsd-3-clause
xyguo/scikit-learn
sklearn/utils/tests/test_sparsefuncs.py
78
17611
import numpy as np import scipy.sparse as sp from scipy import linalg from numpy.testing import (assert_array_almost_equal, assert_array_equal, assert_equal) from numpy.random import RandomState from sklearn.datasets import make_classification from sklearn.utils.sparsefuncs import (mean_variance_axis, incr_mean_variance_axis, inplace_column_scale, inplace_row_scale, inplace_swap_row, inplace_swap_column, min_max_axis, count_nonzero, csc_median_axis_0) from sklearn.utils.sparsefuncs_fast import (assign_rows_csr, inplace_csr_row_normalize_l1, inplace_csr_row_normalize_l2) from sklearn.utils.testing import assert_raises def test_mean_variance_axis0(): X, _ = make_classification(5, 4, random_state=0) # Sparsify the array a little bit X[0, 0] = 0 X[2, 1] = 0 X[4, 3] = 0 X_lil = sp.lil_matrix(X) X_lil[1, 0] = 0 X[1, 0] = 0 assert_raises(TypeError, mean_variance_axis, X_lil, axis=0) X_csr = sp.csr_matrix(X_lil) X_csc = sp.csc_matrix(X_lil) expected_dtypes = [(np.float32, np.float32), (np.float64, np.float64), (np.int32, np.float64), (np.int64, np.float64)] for input_dtype, output_dtype in expected_dtypes: X_test = X.astype(input_dtype) for X_sparse in (X_csr, X_csc): X_sparse = X_sparse.astype(input_dtype) X_means, X_vars = mean_variance_axis(X_sparse, axis=0) assert_equal(X_means.dtype, output_dtype) assert_equal(X_vars.dtype, output_dtype) assert_array_almost_equal(X_means, np.mean(X_test, axis=0)) assert_array_almost_equal(X_vars, np.var(X_test, axis=0)) def test_mean_variance_axis1(): X, _ = make_classification(5, 4, random_state=0) # Sparsify the array a little bit X[0, 0] = 0 X[2, 1] = 0 X[4, 3] = 0 X_lil = sp.lil_matrix(X) X_lil[1, 0] = 0 X[1, 0] = 0 assert_raises(TypeError, mean_variance_axis, X_lil, axis=1) X_csr = sp.csr_matrix(X_lil) X_csc = sp.csc_matrix(X_lil) expected_dtypes = [(np.float32, np.float32), (np.float64, np.float64), (np.int32, np.float64), (np.int64, np.float64)] for input_dtype, output_dtype in expected_dtypes: X_test = X.astype(input_dtype) for X_sparse in (X_csr, X_csc): X_sparse = X_sparse.astype(input_dtype) X_means, X_vars = mean_variance_axis(X_sparse, axis=0) assert_equal(X_means.dtype, output_dtype) assert_equal(X_vars.dtype, output_dtype) assert_array_almost_equal(X_means, np.mean(X_test, axis=0)) assert_array_almost_equal(X_vars, np.var(X_test, axis=0)) def test_incr_mean_variance_axis(): for axis in [0, 1]: rng = np.random.RandomState(0) n_features = 50 n_samples = 10 data_chunks = [rng.randint(0, 2, size=n_features) for i in range(n_samples)] # default params for incr_mean_variance last_mean = np.zeros(n_features) last_var = np.zeros_like(last_mean) last_n = 0 # Test errors X = np.array(data_chunks[0]) X = np.atleast_2d(X) X_lil = sp.lil_matrix(X) X_csr = sp.csr_matrix(X_lil) assert_raises(TypeError, incr_mean_variance_axis, axis, last_mean, last_var, last_n) assert_raises(TypeError, incr_mean_variance_axis, axis, last_mean, last_var, last_n) assert_raises(TypeError, incr_mean_variance_axis, X_lil, axis, last_mean, last_var, last_n) # Test _incr_mean_and_var with a 1 row input X_means, X_vars = mean_variance_axis(X_csr, axis) X_means_incr, X_vars_incr, n_incr = \ incr_mean_variance_axis(X_csr, axis, last_mean, last_var, last_n) assert_array_almost_equal(X_means, X_means_incr) assert_array_almost_equal(X_vars, X_vars_incr) assert_equal(X.shape[axis], n_incr) # X.shape[axis] picks # samples X_csc = sp.csc_matrix(X_lil) X_means, X_vars = mean_variance_axis(X_csc, axis) assert_array_almost_equal(X_means, X_means_incr) assert_array_almost_equal(X_vars, X_vars_incr) assert_equal(X.shape[axis], n_incr) # Test _incremental_mean_and_var with whole data X = np.vstack(data_chunks) X_lil = sp.lil_matrix(X) X_csr = sp.csr_matrix(X_lil) X_csc = sp.csc_matrix(X_lil) expected_dtypes = [(np.float32, np.float32), (np.float64, np.float64), (np.int32, np.float64), (np.int64, np.float64)] for input_dtype, output_dtype in expected_dtypes: for X_sparse in (X_csr, X_csc): X_sparse = X_sparse.astype(input_dtype) X_means, X_vars = mean_variance_axis(X_sparse, axis) X_means_incr, X_vars_incr, n_incr = \ incr_mean_variance_axis(X_sparse, axis, last_mean, last_var, last_n) assert_equal(X_means_incr.dtype, output_dtype) assert_equal(X_vars_incr.dtype, output_dtype) assert_array_almost_equal(X_means, X_means_incr) assert_array_almost_equal(X_vars, X_vars_incr) assert_equal(X.shape[axis], n_incr) def test_mean_variance_illegal_axis(): X, _ = make_classification(5, 4, random_state=0) # Sparsify the array a little bit X[0, 0] = 0 X[2, 1] = 0 X[4, 3] = 0 X_csr = sp.csr_matrix(X) assert_raises(ValueError, mean_variance_axis, X_csr, axis=-3) assert_raises(ValueError, mean_variance_axis, X_csr, axis=2) assert_raises(ValueError, mean_variance_axis, X_csr, axis=-1) assert_raises(ValueError, incr_mean_variance_axis, X_csr, axis=-3, last_mean=None, last_var=None, last_n=None) assert_raises(ValueError, incr_mean_variance_axis, X_csr, axis=2, last_mean=None, last_var=None, last_n=None) assert_raises(ValueError, incr_mean_variance_axis, X_csr, axis=-1, last_mean=None, last_var=None, last_n=None) def test_densify_rows(): for dtype in (np.float32, np.float64): X = sp.csr_matrix([[0, 3, 0], [2, 4, 0], [0, 0, 0], [9, 8, 7], [4, 0, 5]], dtype=dtype) X_rows = np.array([0, 2, 3], dtype=np.intp) out = np.ones((6, X.shape[1]), dtype=dtype) out_rows = np.array([1, 3, 4], dtype=np.intp) expect = np.ones_like(out) expect[out_rows] = X[X_rows, :].toarray() assign_rows_csr(X, X_rows, out_rows, out) assert_array_equal(out, expect) def test_inplace_column_scale(): rng = np.random.RandomState(0) X = sp.rand(100, 200, 0.05) Xr = X.tocsr() Xc = X.tocsc() XA = X.toarray() scale = rng.rand(200) XA *= scale inplace_column_scale(Xc, scale) inplace_column_scale(Xr, scale) assert_array_almost_equal(Xr.toarray(), Xc.toarray()) assert_array_almost_equal(XA, Xc.toarray()) assert_array_almost_equal(XA, Xr.toarray()) assert_raises(TypeError, inplace_column_scale, X.tolil(), scale) X = X.astype(np.float32) scale = scale.astype(np.float32) Xr = X.tocsr() Xc = X.tocsc() XA = X.toarray() XA *= scale inplace_column_scale(Xc, scale) inplace_column_scale(Xr, scale) assert_array_almost_equal(Xr.toarray(), Xc.toarray()) assert_array_almost_equal(XA, Xc.toarray()) assert_array_almost_equal(XA, Xr.toarray()) assert_raises(TypeError, inplace_column_scale, X.tolil(), scale) def test_inplace_row_scale(): rng = np.random.RandomState(0) X = sp.rand(100, 200, 0.05) Xr = X.tocsr() Xc = X.tocsc() XA = X.toarray() scale = rng.rand(100) XA *= scale.reshape(-1, 1) inplace_row_scale(Xc, scale) inplace_row_scale(Xr, scale) assert_array_almost_equal(Xr.toarray(), Xc.toarray()) assert_array_almost_equal(XA, Xc.toarray()) assert_array_almost_equal(XA, Xr.toarray()) assert_raises(TypeError, inplace_column_scale, X.tolil(), scale) X = X.astype(np.float32) scale = scale.astype(np.float32) Xr = X.tocsr() Xc = X.tocsc() XA = X.toarray() XA *= scale.reshape(-1, 1) inplace_row_scale(Xc, scale) inplace_row_scale(Xr, scale) assert_array_almost_equal(Xr.toarray(), Xc.toarray()) assert_array_almost_equal(XA, Xc.toarray()) assert_array_almost_equal(XA, Xr.toarray()) assert_raises(TypeError, inplace_column_scale, X.tolil(), scale) def test_inplace_swap_row(): X = np.array([[0, 3, 0], [2, 4, 0], [0, 0, 0], [9, 8, 7], [4, 0, 5]], dtype=np.float64) X_csr = sp.csr_matrix(X) X_csc = sp.csc_matrix(X) swap = linalg.get_blas_funcs(('swap',), (X,)) swap = swap[0] X[0], X[-1] = swap(X[0], X[-1]) inplace_swap_row(X_csr, 0, -1) inplace_swap_row(X_csc, 0, -1) assert_array_equal(X_csr.toarray(), X_csc.toarray()) assert_array_equal(X, X_csc.toarray()) assert_array_equal(X, X_csr.toarray()) X[2], X[3] = swap(X[2], X[3]) inplace_swap_row(X_csr, 2, 3) inplace_swap_row(X_csc, 2, 3) assert_array_equal(X_csr.toarray(), X_csc.toarray()) assert_array_equal(X, X_csc.toarray()) assert_array_equal(X, X_csr.toarray()) assert_raises(TypeError, inplace_swap_row, X_csr.tolil()) X = np.array([[0, 3, 0], [2, 4, 0], [0, 0, 0], [9, 8, 7], [4, 0, 5]], dtype=np.float32) X_csr = sp.csr_matrix(X) X_csc = sp.csc_matrix(X) swap = linalg.get_blas_funcs(('swap',), (X,)) swap = swap[0] X[0], X[-1] = swap(X[0], X[-1]) inplace_swap_row(X_csr, 0, -1) inplace_swap_row(X_csc, 0, -1) assert_array_equal(X_csr.toarray(), X_csc.toarray()) assert_array_equal(X, X_csc.toarray()) assert_array_equal(X, X_csr.toarray()) X[2], X[3] = swap(X[2], X[3]) inplace_swap_row(X_csr, 2, 3) inplace_swap_row(X_csc, 2, 3) assert_array_equal(X_csr.toarray(), X_csc.toarray()) assert_array_equal(X, X_csc.toarray()) assert_array_equal(X, X_csr.toarray()) assert_raises(TypeError, inplace_swap_row, X_csr.tolil()) def test_inplace_swap_column(): X = np.array([[0, 3, 0], [2, 4, 0], [0, 0, 0], [9, 8, 7], [4, 0, 5]], dtype=np.float64) X_csr = sp.csr_matrix(X) X_csc = sp.csc_matrix(X) swap = linalg.get_blas_funcs(('swap',), (X,)) swap = swap[0] X[:, 0], X[:, -1] = swap(X[:, 0], X[:, -1]) inplace_swap_column(X_csr, 0, -1) inplace_swap_column(X_csc, 0, -1) assert_array_equal(X_csr.toarray(), X_csc.toarray()) assert_array_equal(X, X_csc.toarray()) assert_array_equal(X, X_csr.toarray()) X[:, 0], X[:, 1] = swap(X[:, 0], X[:, 1]) inplace_swap_column(X_csr, 0, 1) inplace_swap_column(X_csc, 0, 1) assert_array_equal(X_csr.toarray(), X_csc.toarray()) assert_array_equal(X, X_csc.toarray()) assert_array_equal(X, X_csr.toarray()) assert_raises(TypeError, inplace_swap_column, X_csr.tolil()) X = np.array([[0, 3, 0], [2, 4, 0], [0, 0, 0], [9, 8, 7], [4, 0, 5]], dtype=np.float32) X_csr = sp.csr_matrix(X) X_csc = sp.csc_matrix(X) swap = linalg.get_blas_funcs(('swap',), (X,)) swap = swap[0] X[:, 0], X[:, -1] = swap(X[:, 0], X[:, -1]) inplace_swap_column(X_csr, 0, -1) inplace_swap_column(X_csc, 0, -1) assert_array_equal(X_csr.toarray(), X_csc.toarray()) assert_array_equal(X, X_csc.toarray()) assert_array_equal(X, X_csr.toarray()) X[:, 0], X[:, 1] = swap(X[:, 0], X[:, 1]) inplace_swap_column(X_csr, 0, 1) inplace_swap_column(X_csc, 0, 1) assert_array_equal(X_csr.toarray(), X_csc.toarray()) assert_array_equal(X, X_csc.toarray()) assert_array_equal(X, X_csr.toarray()) assert_raises(TypeError, inplace_swap_column, X_csr.tolil()) def test_min_max_axis0(): X = np.array([[0, 3, 0], [2, -1, 0], [0, 0, 0], [9, 8, 7], [4, 0, 5]], dtype=np.float64) X_csr = sp.csr_matrix(X) X_csc = sp.csc_matrix(X) mins_csr, maxs_csr = min_max_axis(X_csr, axis=0) assert_array_equal(mins_csr, X.min(axis=0)) assert_array_equal(maxs_csr, X.max(axis=0)) mins_csc, maxs_csc = min_max_axis(X_csc, axis=0) assert_array_equal(mins_csc, X.min(axis=0)) assert_array_equal(maxs_csc, X.max(axis=0)) X = X.astype(np.float32) X_csr = sp.csr_matrix(X) X_csc = sp.csc_matrix(X) mins_csr, maxs_csr = min_max_axis(X_csr, axis=0) assert_array_equal(mins_csr, X.min(axis=0)) assert_array_equal(maxs_csr, X.max(axis=0)) mins_csc, maxs_csc = min_max_axis(X_csc, axis=0) assert_array_equal(mins_csc, X.min(axis=0)) assert_array_equal(maxs_csc, X.max(axis=0)) def test_min_max_axis1(): X = np.array([[0, 3, 0], [2, -1, 0], [0, 0, 0], [9, 8, 7], [4, 0, 5]], dtype=np.float64) X_csr = sp.csr_matrix(X) X_csc = sp.csc_matrix(X) mins_csr, maxs_csr = min_max_axis(X_csr, axis=1) assert_array_equal(mins_csr, X.min(axis=1)) assert_array_equal(maxs_csr, X.max(axis=1)) mins_csc, maxs_csc = min_max_axis(X_csc, axis=1) assert_array_equal(mins_csc, X.min(axis=1)) assert_array_equal(maxs_csc, X.max(axis=1)) X = X.astype(np.float32) X_csr = sp.csr_matrix(X) X_csc = sp.csc_matrix(X) mins_csr, maxs_csr = min_max_axis(X_csr, axis=1) assert_array_equal(mins_csr, X.min(axis=1)) assert_array_equal(maxs_csr, X.max(axis=1)) mins_csc, maxs_csc = min_max_axis(X_csc, axis=1) assert_array_equal(mins_csc, X.min(axis=1)) assert_array_equal(maxs_csc, X.max(axis=1)) def test_min_max_axis_errors(): X = np.array([[0, 3, 0], [2, -1, 0], [0, 0, 0], [9, 8, 7], [4, 0, 5]], dtype=np.float64) X_csr = sp.csr_matrix(X) X_csc = sp.csc_matrix(X) assert_raises(TypeError, min_max_axis, X_csr.tolil(), axis=0) assert_raises(ValueError, min_max_axis, X_csr, axis=2) assert_raises(ValueError, min_max_axis, X_csc, axis=-3) def test_count_nonzero(): X = np.array([[0, 3, 0], [2, -1, 0], [0, 0, 0], [9, 8, 7], [4, 0, 5]], dtype=np.float64) X_csr = sp.csr_matrix(X) X_csc = sp.csc_matrix(X) X_nonzero = X != 0 sample_weight = [.5, .2, .3, .1, .1] X_nonzero_weighted = X_nonzero * np.array(sample_weight)[:, None] for axis in [0, 1, -1, -2, None]: assert_array_almost_equal(count_nonzero(X_csr, axis=axis), X_nonzero.sum(axis=axis)) assert_array_almost_equal(count_nonzero(X_csr, axis=axis, sample_weight=sample_weight), X_nonzero_weighted.sum(axis=axis)) assert_raises(TypeError, count_nonzero, X_csc) assert_raises(ValueError, count_nonzero, X_csr, axis=2) def test_csc_row_median(): # Test csc_row_median actually calculates the median. # Test that it gives the same output when X is dense. rng = np.random.RandomState(0) X = rng.rand(100, 50) dense_median = np.median(X, axis=0) csc = sp.csc_matrix(X) sparse_median = csc_median_axis_0(csc) assert_array_equal(sparse_median, dense_median) # Test that it gives the same output when X is sparse X = rng.rand(51, 100) X[X < 0.7] = 0.0 ind = rng.randint(0, 50, 10) X[ind] = -X[ind] csc = sp.csc_matrix(X) dense_median = np.median(X, axis=0) sparse_median = csc_median_axis_0(csc) assert_array_equal(sparse_median, dense_median) # Test for toy data. X = [[0, -2], [-1, -1], [1, 0], [2, 1]] csc = sp.csc_matrix(X) assert_array_equal(csc_median_axis_0(csc), np.array([0.5, -0.5])) X = [[0, -2], [-1, -5], [1, -3]] csc = sp.csc_matrix(X) assert_array_equal(csc_median_axis_0(csc), np.array([0., -3])) # Test that it raises an Error for non-csc matrices. assert_raises(TypeError, csc_median_axis_0, sp.csr_matrix(X)) def test_inplace_normalize(): ones = np.ones((10, 1)) rs = RandomState(10) for inplace_csr_row_normalize in (inplace_csr_row_normalize_l1, inplace_csr_row_normalize_l2): for dtype in (np.float64, np.float32): X = rs.randn(10, 5).astype(dtype) X_csr = sp.csr_matrix(X) inplace_csr_row_normalize(X_csr) assert_equal(X_csr.dtype, dtype) if inplace_csr_row_normalize is inplace_csr_row_normalize_l2: X_csr.data **= 2 assert_array_almost_equal(np.abs(X_csr).sum(axis=1), ones)
bsd-3-clause
ifuding/Kaggle
TalkingDataFraudDetect/Code/lgb_predict.py
3
2602
import pandas as pd import time import numpy as np import gc from feature_engineer import gen_features from feature_engineer import timer import keras_train from nfold_train import nfold_train, models_eval import tensorflow as tf import os import shutil from lcc_sample import neg_sample from sklearn import metrics import lightgbm as lgb from main import * DENSE_FEATURE_TYPE = keras_train.DENSE_FEATURE_TYPE def find_best_iteration_search(bst): """ """ valide_df = load_valide_data() valide_data = valide_df[keras_train.USED_FEATURE_LIST].values.astype(DENSE_FEATURE_TYPE) valide_label = valide_df['is_attributed'].values.astype(np.uint8) del valide_df gc.collect() if FLAGS.stacking: valide_data = gen_stacking_data(valide_data) pos_cnt = valide_label.sum() neg_cnt = len(valide_label) - pos_cnt print ("valide type: {0} valide size: {1} valide data pos: {2} neg: {3}".format( valide_data.dtype, len(valide_data), pos_cnt, neg_cnt)) with timer("finding best iteration..."): search_iterations = [int(ii.strip()) for ii in FLAGS.search_iterations.split(',')] for i in range(search_iterations[0], search_iterations[1], search_iterations[2]): y_pred = bst.predict(valide_data, num_iteration=i) score = metrics.roc_auc_score(valide_label, y_pred) loss = metrics.log_loss(valide_label, y_pred) print ("Iteration: {0} AUC: {1} Logloss: {2}".format(i, score, loss)) def predict_test(bst): test_df = load_test_data() test_data = test_df[keras_train.USED_FEATURE_LIST].values.astype(DENSE_FEATURE_TYPE) test_id = test_df['click_id'].values #.astype(np.uint32) print ("test type {0}".format(test_data.dtype)) del test_df gc.collect() if FLAGS.stacking: test_data = gen_stacking_data(test_data) with timer("predicting test data"): print('predicting test data...') sub_re = pd.DataFrame(test_id, columns = ['click_id']) sub_re['is_attributed'] = bst.predict(test_data, num_iteration=FLAGS.best_iteration) time_label = time.strftime('_%Y_%m_%d_%H_%M_%S', time.gmtime()) sub_name = FLAGS.output_model_path + "sub" + time_label + ".csv" sub_re.to_csv(sub_name, index=False) if __name__ == "__main__": # load model to predict bst = lgb.Booster(model_file= FLAGS.input_previous_model_path + '/model.txt') if FLAGS.search_best_iteration: find_best_iteration_search(bst) else: predict_test(bst)
apache-2.0
RachitKansal/scikit-learn
sklearn/datasets/tests/test_20news.py
280
3045
"""Test the 20news downloader, if the data is available.""" import numpy as np import scipy.sparse as sp from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_true from sklearn.utils.testing import SkipTest from sklearn import datasets def test_20news(): try: data = datasets.fetch_20newsgroups( subset='all', download_if_missing=False, shuffle=False) except IOError: raise SkipTest("Download 20 newsgroups to run this test") # Extract a reduced dataset data2cats = datasets.fetch_20newsgroups( subset='all', categories=data.target_names[-1:-3:-1], shuffle=False) # Check that the ordering of the target_names is the same # as the ordering in the full dataset assert_equal(data2cats.target_names, data.target_names[-2:]) # Assert that we have only 0 and 1 as labels assert_equal(np.unique(data2cats.target).tolist(), [0, 1]) # Check that the number of filenames is consistent with data/target assert_equal(len(data2cats.filenames), len(data2cats.target)) assert_equal(len(data2cats.filenames), len(data2cats.data)) # Check that the first entry of the reduced dataset corresponds to # the first entry of the corresponding category in the full dataset entry1 = data2cats.data[0] category = data2cats.target_names[data2cats.target[0]] label = data.target_names.index(category) entry2 = data.data[np.where(data.target == label)[0][0]] assert_equal(entry1, entry2) def test_20news_length_consistency(): """Checks the length consistencies within the bunch This is a non-regression test for a bug present in 0.16.1. """ try: data = datasets.fetch_20newsgroups( subset='all', download_if_missing=False, shuffle=False) except IOError: raise SkipTest("Download 20 newsgroups to run this test") # Extract the full dataset data = datasets.fetch_20newsgroups(subset='all') assert_equal(len(data['data']), len(data.data)) assert_equal(len(data['target']), len(data.target)) assert_equal(len(data['filenames']), len(data.filenames)) def test_20news_vectorized(): # This test is slow. raise SkipTest("Test too slow.") bunch = datasets.fetch_20newsgroups_vectorized(subset="train") assert_true(sp.isspmatrix_csr(bunch.data)) assert_equal(bunch.data.shape, (11314, 107428)) assert_equal(bunch.target.shape[0], 11314) assert_equal(bunch.data.dtype, np.float64) bunch = datasets.fetch_20newsgroups_vectorized(subset="test") assert_true(sp.isspmatrix_csr(bunch.data)) assert_equal(bunch.data.shape, (7532, 107428)) assert_equal(bunch.target.shape[0], 7532) assert_equal(bunch.data.dtype, np.float64) bunch = datasets.fetch_20newsgroups_vectorized(subset="all") assert_true(sp.isspmatrix_csr(bunch.data)) assert_equal(bunch.data.shape, (11314 + 7532, 107428)) assert_equal(bunch.target.shape[0], 11314 + 7532) assert_equal(bunch.data.dtype, np.float64)
bsd-3-clause
Nyker510/scikit-learn
sklearn/tree/tests/test_tree.py
72
47440
""" Testing for the tree module (sklearn.tree). """ import pickle from functools import partial from itertools import product import platform import numpy as np from scipy.sparse import csc_matrix from scipy.sparse import csr_matrix from scipy.sparse import coo_matrix from sklearn.random_projection import sparse_random_matrix from sklearn.metrics import accuracy_score from sklearn.metrics import mean_squared_error from sklearn.utils.testing import assert_array_equal 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_in from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_greater_equal from sklearn.utils.testing import assert_less from sklearn.utils.testing import assert_true from sklearn.utils.testing import raises from sklearn.utils.validation import check_random_state from sklearn.utils.validation import NotFittedError from sklearn.tree import DecisionTreeClassifier from sklearn.tree import DecisionTreeRegressor from sklearn.tree import ExtraTreeClassifier from sklearn.tree import ExtraTreeRegressor from sklearn import tree from sklearn.tree.tree import SPARSE_SPLITTERS from sklearn.tree._tree import TREE_LEAF from sklearn import datasets from sklearn.preprocessing._weights import _balance_weights CLF_CRITERIONS = ("gini", "entropy") REG_CRITERIONS = ("mse", ) CLF_TREES = { "DecisionTreeClassifier": DecisionTreeClassifier, "Presort-DecisionTreeClassifier": partial(DecisionTreeClassifier, splitter="presort-best"), "ExtraTreeClassifier": ExtraTreeClassifier, } REG_TREES = { "DecisionTreeRegressor": DecisionTreeRegressor, "Presort-DecisionTreeRegressor": partial(DecisionTreeRegressor, splitter="presort-best"), "ExtraTreeRegressor": ExtraTreeRegressor, } ALL_TREES = dict() ALL_TREES.update(CLF_TREES) ALL_TREES.update(REG_TREES) SPARSE_TREES = [name for name, Tree in ALL_TREES.items() if Tree().splitter in SPARSE_SPLITTERS] X_small = np.array([ [0, 0, 4, 0, 0, 0, 1, -14, 0, -4, 0, 0, 0, 0, ], [0, 0, 5, 3, 0, -4, 0, 0, 1, -5, 0.2, 0, 4, 1, ], [-1, -1, 0, 0, -4.5, 0, 0, 2.1, 1, 0, 0, -4.5, 0, 1, ], [-1, -1, 0, -1.2, 0, 0, 0, 0, 0, 0, 0.2, 0, 0, 1, ], [-1, -1, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 1, ], [-1, -2, 0, 4, -3, 10, 4, 0, -3.2, 0, 4, 3, -4, 1, ], [2.11, 0, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0.5, 0, -3, 1, ], [2.11, 0, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0, 0, -2, 1, ], [2.11, 8, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0, 0, -2, 1, ], [2.11, 8, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0.5, 0, -1, 0, ], [2, 8, 5, 1, 0.5, -4, 10, 0, 1, -5, 3, 0, 2, 0, ], [2, 0, 1, 1, 1, -1, 1, 0, 0, -2, 3, 0, 1, 0, ], [2, 0, 1, 2, 3, -1, 10, 2, 0, -1, 1, 2, 2, 0, ], [1, 1, 0, 2, 2, -1, 1, 2, 0, -5, 1, 2, 3, 0, ], [3, 1, 0, 3, 0, -4, 10, 0, 1, -5, 3, 0, 3, 1, ], [2.11, 8, -6, -0.5, 0, 1, 0, 0, -3.2, 6, 0.5, 0, -3, 1, ], [2.11, 8, -6, -0.5, 0, 1, 0, 0, -3.2, 6, 1.5, 1, -1, -1, ], [2.11, 8, -6, -0.5, 0, 10, 0, 0, -3.2, 6, 0.5, 0, -1, -1, ], [2, 0, 5, 1, 0.5, -2, 10, 0, 1, -5, 3, 1, 0, -1, ], [2, 0, 1, 1, 1, -2, 1, 0, 0, -2, 0, 0, 0, 1, ], [2, 1, 1, 1, 2, -1, 10, 2, 0, -1, 0, 2, 1, 1, ], [1, 1, 0, 0, 1, -3, 1, 2, 0, -5, 1, 2, 1, 1, ], [3, 1, 0, 1, 0, -4, 1, 0, 1, -2, 0, 0, 1, 0, ]]) y_small = [1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0] y_small_reg = [1.0, 2.1, 1.2, 0.05, 10, 2.4, 3.1, 1.01, 0.01, 2.98, 3.1, 1.1, 0.0, 1.2, 2, 11, 0, 0, 4.5, 0.201, 1.06, 0.9, 0] # toy sample X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] y = [-1, -1, -1, 1, 1, 1] T = [[-1, -1], [2, 2], [3, 2]] true_result = [-1, 1, 1] # also load the iris dataset # and randomly permute it iris = datasets.load_iris() rng = np.random.RandomState(1) perm = rng.permutation(iris.target.size) iris.data = iris.data[perm] iris.target = iris.target[perm] # also load the boston dataset # and randomly permute it boston = datasets.load_boston() perm = rng.permutation(boston.target.size) boston.data = boston.data[perm] boston.target = boston.target[perm] digits = datasets.load_digits() perm = rng.permutation(digits.target.size) digits.data = digits.data[perm] digits.target = digits.target[perm] random_state = check_random_state(0) X_multilabel, y_multilabel = datasets.make_multilabel_classification( random_state=0, return_indicator=True, n_samples=30, n_features=10) X_sparse_pos = random_state.uniform(size=(20, 5)) X_sparse_pos[X_sparse_pos <= 0.8] = 0. y_random = random_state.randint(0, 4, size=(20, )) X_sparse_mix = sparse_random_matrix(20, 10, density=0.25, random_state=0) DATASETS = { "iris": {"X": iris.data, "y": iris.target}, "boston": {"X": boston.data, "y": boston.target}, "digits": {"X": digits.data, "y": digits.target}, "toy": {"X": X, "y": y}, "clf_small": {"X": X_small, "y": y_small}, "reg_small": {"X": X_small, "y": y_small_reg}, "multilabel": {"X": X_multilabel, "y": y_multilabel}, "sparse-pos": {"X": X_sparse_pos, "y": y_random}, "sparse-neg": {"X": - X_sparse_pos, "y": y_random}, "sparse-mix": {"X": X_sparse_mix, "y": y_random}, "zeros": {"X": np.zeros((20, 3)), "y": y_random} } for name in DATASETS: DATASETS[name]["X_sparse"] = csc_matrix(DATASETS[name]["X"]) def assert_tree_equal(d, s, message): assert_equal(s.node_count, d.node_count, "{0}: inequal number of node ({1} != {2})" "".format(message, s.node_count, d.node_count)) assert_array_equal(d.children_right, s.children_right, message + ": inequal children_right") assert_array_equal(d.children_left, s.children_left, message + ": inequal children_left") external = d.children_right == TREE_LEAF internal = np.logical_not(external) assert_array_equal(d.feature[internal], s.feature[internal], message + ": inequal features") assert_array_equal(d.threshold[internal], s.threshold[internal], message + ": inequal threshold") assert_array_equal(d.n_node_samples.sum(), s.n_node_samples.sum(), message + ": inequal sum(n_node_samples)") assert_array_equal(d.n_node_samples, s.n_node_samples, message + ": inequal n_node_samples") assert_almost_equal(d.impurity, s.impurity, err_msg=message + ": inequal impurity") assert_array_almost_equal(d.value[external], s.value[external], err_msg=message + ": inequal value") def test_classification_toy(): # Check classification on a toy dataset. for name, Tree in CLF_TREES.items(): clf = Tree(random_state=0) clf.fit(X, y) assert_array_equal(clf.predict(T), true_result, "Failed with {0}".format(name)) clf = Tree(max_features=1, random_state=1) clf.fit(X, y) assert_array_equal(clf.predict(T), true_result, "Failed with {0}".format(name)) def test_weighted_classification_toy(): # Check classification on a weighted toy dataset. for name, Tree in CLF_TREES.items(): clf = Tree(random_state=0) clf.fit(X, y, sample_weight=np.ones(len(X))) assert_array_equal(clf.predict(T), true_result, "Failed with {0}".format(name)) clf.fit(X, y, sample_weight=np.ones(len(X)) * 0.5) assert_array_equal(clf.predict(T), true_result, "Failed with {0}".format(name)) def test_regression_toy(): # Check regression on a toy dataset. for name, Tree in REG_TREES.items(): reg = Tree(random_state=1) reg.fit(X, y) assert_almost_equal(reg.predict(T), true_result, err_msg="Failed with {0}".format(name)) clf = Tree(max_features=1, random_state=1) clf.fit(X, y) assert_almost_equal(reg.predict(T), true_result, err_msg="Failed with {0}".format(name)) def test_xor(): # Check on a XOR problem y = np.zeros((10, 10)) y[:5, :5] = 1 y[5:, 5:] = 1 gridx, gridy = np.indices(y.shape) X = np.vstack([gridx.ravel(), gridy.ravel()]).T y = y.ravel() for name, Tree in CLF_TREES.items(): clf = Tree(random_state=0) clf.fit(X, y) assert_equal(clf.score(X, y), 1.0, "Failed with {0}".format(name)) clf = Tree(random_state=0, max_features=1) clf.fit(X, y) assert_equal(clf.score(X, y), 1.0, "Failed with {0}".format(name)) def test_iris(): # Check consistency on dataset iris. for (name, Tree), criterion in product(CLF_TREES.items(), CLF_CRITERIONS): clf = Tree(criterion=criterion, random_state=0) clf.fit(iris.data, iris.target) score = accuracy_score(clf.predict(iris.data), iris.target) assert_greater(score, 0.9, "Failed with {0}, criterion = {1} and score = {2}" "".format(name, criterion, score)) clf = Tree(criterion=criterion, max_features=2, random_state=0) clf.fit(iris.data, iris.target) score = accuracy_score(clf.predict(iris.data), iris.target) assert_greater(score, 0.5, "Failed with {0}, criterion = {1} and score = {2}" "".format(name, criterion, score)) def test_boston(): # Check consistency on dataset boston house prices. for (name, Tree), criterion in product(REG_TREES.items(), REG_CRITERIONS): reg = Tree(criterion=criterion, random_state=0) reg.fit(boston.data, boston.target) score = mean_squared_error(boston.target, reg.predict(boston.data)) assert_less(score, 1, "Failed with {0}, criterion = {1} and score = {2}" "".format(name, criterion, score)) # using fewer features reduces the learning ability of this tree, # but reduces training time. reg = Tree(criterion=criterion, max_features=6, random_state=0) reg.fit(boston.data, boston.target) score = mean_squared_error(boston.target, reg.predict(boston.data)) assert_less(score, 2, "Failed with {0}, criterion = {1} and score = {2}" "".format(name, criterion, score)) def test_probability(): # Predict probabilities using DecisionTreeClassifier. for name, Tree in CLF_TREES.items(): clf = Tree(max_depth=1, max_features=1, random_state=42) clf.fit(iris.data, iris.target) prob_predict = clf.predict_proba(iris.data) assert_array_almost_equal(np.sum(prob_predict, 1), np.ones(iris.data.shape[0]), err_msg="Failed with {0}".format(name)) assert_array_equal(np.argmax(prob_predict, 1), clf.predict(iris.data), err_msg="Failed with {0}".format(name)) assert_almost_equal(clf.predict_proba(iris.data), np.exp(clf.predict_log_proba(iris.data)), 8, err_msg="Failed with {0}".format(name)) def test_arrayrepr(): # Check the array representation. # Check resize X = np.arange(10000)[:, np.newaxis] y = np.arange(10000) for name, Tree in REG_TREES.items(): reg = Tree(max_depth=None, random_state=0) reg.fit(X, y) def test_pure_set(): # Check when y is pure. X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] y = [1, 1, 1, 1, 1, 1] for name, TreeClassifier in CLF_TREES.items(): clf = TreeClassifier(random_state=0) clf.fit(X, y) assert_array_equal(clf.predict(X), y, err_msg="Failed with {0}".format(name)) for name, TreeRegressor in REG_TREES.items(): reg = TreeRegressor(random_state=0) reg.fit(X, y) assert_almost_equal(clf.predict(X), y, err_msg="Failed with {0}".format(name)) def test_numerical_stability(): # Check numerical stability. X = np.array([ [152.08097839, 140.40744019, 129.75102234, 159.90493774], [142.50700378, 135.81935120, 117.82884979, 162.75781250], [127.28772736, 140.40744019, 129.75102234, 159.90493774], [132.37025452, 143.71923828, 138.35694885, 157.84558105], [103.10237122, 143.71928406, 138.35696411, 157.84559631], [127.71276855, 143.71923828, 138.35694885, 157.84558105], [120.91514587, 140.40744019, 129.75102234, 159.90493774]]) y = np.array( [1., 0.70209277, 0.53896582, 0., 0.90914464, 0.48026916, 0.49622521]) with np.errstate(all="raise"): for name, Tree in REG_TREES.items(): reg = Tree(random_state=0) reg.fit(X, y) reg.fit(X, -y) reg.fit(-X, y) reg.fit(-X, -y) def test_importances(): # Check variable importances. X, y = datasets.make_classification(n_samples=2000, n_features=10, n_informative=3, n_redundant=0, n_repeated=0, shuffle=False, random_state=0) for name, Tree in CLF_TREES.items(): clf = Tree(random_state=0) clf.fit(X, y) importances = clf.feature_importances_ n_important = np.sum(importances > 0.1) assert_equal(importances.shape[0], 10, "Failed with {0}".format(name)) assert_equal(n_important, 3, "Failed with {0}".format(name)) X_new = clf.transform(X, threshold="mean") assert_less(0, X_new.shape[1], "Failed with {0}".format(name)) assert_less(X_new.shape[1], X.shape[1], "Failed with {0}".format(name)) # Check on iris that importances are the same for all builders clf = DecisionTreeClassifier(random_state=0) clf.fit(iris.data, iris.target) clf2 = DecisionTreeClassifier(random_state=0, max_leaf_nodes=len(iris.data)) clf2.fit(iris.data, iris.target) assert_array_equal(clf.feature_importances_, clf2.feature_importances_) @raises(ValueError) def test_importances_raises(): # Check if variable importance before fit raises ValueError. clf = DecisionTreeClassifier() clf.feature_importances_ def test_importances_gini_equal_mse(): # Check that gini is equivalent to mse for binary output variable X, y = datasets.make_classification(n_samples=2000, n_features=10, n_informative=3, n_redundant=0, n_repeated=0, shuffle=False, random_state=0) # The gini index and the mean square error (variance) might differ due # to numerical instability. Since those instabilities mainly occurs at # high tree depth, we restrict this maximal depth. clf = DecisionTreeClassifier(criterion="gini", max_depth=5, random_state=0).fit(X, y) reg = DecisionTreeRegressor(criterion="mse", max_depth=5, random_state=0).fit(X, y) assert_almost_equal(clf.feature_importances_, reg.feature_importances_) assert_array_equal(clf.tree_.feature, reg.tree_.feature) assert_array_equal(clf.tree_.children_left, reg.tree_.children_left) assert_array_equal(clf.tree_.children_right, reg.tree_.children_right) assert_array_equal(clf.tree_.n_node_samples, reg.tree_.n_node_samples) def test_max_features(): # Check max_features. for name, TreeRegressor in REG_TREES.items(): reg = TreeRegressor(max_features="auto") reg.fit(boston.data, boston.target) assert_equal(reg.max_features_, boston.data.shape[1]) for name, TreeClassifier in CLF_TREES.items(): clf = TreeClassifier(max_features="auto") clf.fit(iris.data, iris.target) assert_equal(clf.max_features_, 2) for name, TreeEstimator in ALL_TREES.items(): est = TreeEstimator(max_features="sqrt") est.fit(iris.data, iris.target) assert_equal(est.max_features_, int(np.sqrt(iris.data.shape[1]))) est = TreeEstimator(max_features="log2") est.fit(iris.data, iris.target) assert_equal(est.max_features_, int(np.log2(iris.data.shape[1]))) est = TreeEstimator(max_features=1) est.fit(iris.data, iris.target) assert_equal(est.max_features_, 1) est = TreeEstimator(max_features=3) est.fit(iris.data, iris.target) assert_equal(est.max_features_, 3) est = TreeEstimator(max_features=0.01) est.fit(iris.data, iris.target) assert_equal(est.max_features_, 1) est = TreeEstimator(max_features=0.5) est.fit(iris.data, iris.target) assert_equal(est.max_features_, int(0.5 * iris.data.shape[1])) est = TreeEstimator(max_features=1.0) est.fit(iris.data, iris.target) assert_equal(est.max_features_, iris.data.shape[1]) est = TreeEstimator(max_features=None) est.fit(iris.data, iris.target) assert_equal(est.max_features_, iris.data.shape[1]) # use values of max_features that are invalid est = TreeEstimator(max_features=10) assert_raises(ValueError, est.fit, X, y) est = TreeEstimator(max_features=-1) assert_raises(ValueError, est.fit, X, y) est = TreeEstimator(max_features=0.0) assert_raises(ValueError, est.fit, X, y) est = TreeEstimator(max_features=1.5) assert_raises(ValueError, est.fit, X, y) est = TreeEstimator(max_features="foobar") assert_raises(ValueError, est.fit, X, y) def test_error(): # Test that it gives proper exception on deficient input. for name, TreeEstimator in CLF_TREES.items(): # predict before fit est = TreeEstimator() assert_raises(NotFittedError, est.predict_proba, X) est.fit(X, y) X2 = [-2, -1, 1] # wrong feature shape for sample assert_raises(ValueError, est.predict_proba, X2) for name, TreeEstimator in ALL_TREES.items(): # Invalid values for parameters assert_raises(ValueError, TreeEstimator(min_samples_leaf=-1).fit, X, y) assert_raises(ValueError, TreeEstimator(min_weight_fraction_leaf=-1).fit, X, y) assert_raises(ValueError, TreeEstimator(min_weight_fraction_leaf=0.51).fit, X, y) assert_raises(ValueError, TreeEstimator(min_samples_split=-1).fit, X, y) assert_raises(ValueError, TreeEstimator(max_depth=-1).fit, X, y) assert_raises(ValueError, TreeEstimator(max_features=42).fit, X, y) # Wrong dimensions est = TreeEstimator() y2 = y[:-1] assert_raises(ValueError, est.fit, X, y2) # Test with arrays that are non-contiguous. Xf = np.asfortranarray(X) est = TreeEstimator() est.fit(Xf, y) assert_almost_equal(est.predict(T), true_result) # predict before fitting est = TreeEstimator() assert_raises(NotFittedError, est.predict, T) # predict on vector with different dims est.fit(X, y) t = np.asarray(T) assert_raises(ValueError, est.predict, t[:, 1:]) # wrong sample shape Xt = np.array(X).T est = TreeEstimator() est.fit(np.dot(X, Xt), y) assert_raises(ValueError, est.predict, X) assert_raises(ValueError, est.apply, X) clf = TreeEstimator() clf.fit(X, y) assert_raises(ValueError, clf.predict, Xt) assert_raises(ValueError, clf.apply, Xt) # apply before fitting est = TreeEstimator() assert_raises(NotFittedError, est.apply, T) def test_min_samples_leaf(): # Test if leaves contain more than leaf_count training examples X = np.asfortranarray(iris.data.astype(tree._tree.DTYPE)) y = iris.target # test both DepthFirstTreeBuilder and BestFirstTreeBuilder # by setting max_leaf_nodes for max_leaf_nodes in (None, 1000): for name, TreeEstimator in ALL_TREES.items(): est = TreeEstimator(min_samples_leaf=5, max_leaf_nodes=max_leaf_nodes, random_state=0) est.fit(X, y) out = est.tree_.apply(X) node_counts = np.bincount(out) # drop inner nodes leaf_count = node_counts[node_counts != 0] assert_greater(np.min(leaf_count), 4, "Failed with {0}".format(name)) def check_min_weight_fraction_leaf(name, datasets, sparse=False): """Test if leaves contain at least min_weight_fraction_leaf of the training set""" if sparse: X = DATASETS[datasets]["X_sparse"].astype(np.float32) else: X = DATASETS[datasets]["X"].astype(np.float32) y = DATASETS[datasets]["y"] weights = rng.rand(X.shape[0]) total_weight = np.sum(weights) TreeEstimator = ALL_TREES[name] # test both DepthFirstTreeBuilder and BestFirstTreeBuilder # by setting max_leaf_nodes for max_leaf_nodes, frac in product((None, 1000), np.linspace(0, 0.5, 6)): est = TreeEstimator(min_weight_fraction_leaf=frac, max_leaf_nodes=max_leaf_nodes, random_state=0) est.fit(X, y, sample_weight=weights) if sparse: out = est.tree_.apply(X.tocsr()) else: out = est.tree_.apply(X) node_weights = np.bincount(out, weights=weights) # drop inner nodes leaf_weights = node_weights[node_weights != 0] assert_greater_equal( np.min(leaf_weights), total_weight * est.min_weight_fraction_leaf, "Failed with {0} " "min_weight_fraction_leaf={1}".format( name, est.min_weight_fraction_leaf)) def test_min_weight_fraction_leaf(): # Check on dense input for name in ALL_TREES: yield check_min_weight_fraction_leaf, name, "iris" # Check on sparse input for name in SPARSE_TREES: yield check_min_weight_fraction_leaf, name, "multilabel", True def test_pickle(): # Check that tree estimator are pickable for name, TreeClassifier in CLF_TREES.items(): clf = TreeClassifier(random_state=0) clf.fit(iris.data, iris.target) score = clf.score(iris.data, iris.target) serialized_object = pickle.dumps(clf) clf2 = pickle.loads(serialized_object) assert_equal(type(clf2), clf.__class__) score2 = clf2.score(iris.data, iris.target) assert_equal(score, score2, "Failed to generate same score " "after pickling (classification) " "with {0}".format(name)) for name, TreeRegressor in REG_TREES.items(): reg = TreeRegressor(random_state=0) reg.fit(boston.data, boston.target) score = reg.score(boston.data, boston.target) serialized_object = pickle.dumps(reg) reg2 = pickle.loads(serialized_object) assert_equal(type(reg2), reg.__class__) score2 = reg2.score(boston.data, boston.target) assert_equal(score, score2, "Failed to generate same score " "after pickling (regression) " "with {0}".format(name)) def test_multioutput(): # Check estimators on multi-output problems. X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1], [-2, 1], [-1, 1], [-1, 2], [2, -1], [1, -1], [1, -2]] y = [[-1, 0], [-1, 0], [-1, 0], [1, 1], [1, 1], [1, 1], [-1, 2], [-1, 2], [-1, 2], [1, 3], [1, 3], [1, 3]] T = [[-1, -1], [1, 1], [-1, 1], [1, -1]] y_true = [[-1, 0], [1, 1], [-1, 2], [1, 3]] # toy classification problem for name, TreeClassifier in CLF_TREES.items(): clf = TreeClassifier(random_state=0) y_hat = clf.fit(X, y).predict(T) assert_array_equal(y_hat, y_true) assert_equal(y_hat.shape, (4, 2)) proba = clf.predict_proba(T) assert_equal(len(proba), 2) assert_equal(proba[0].shape, (4, 2)) assert_equal(proba[1].shape, (4, 4)) log_proba = clf.predict_log_proba(T) assert_equal(len(log_proba), 2) assert_equal(log_proba[0].shape, (4, 2)) assert_equal(log_proba[1].shape, (4, 4)) # toy regression problem for name, TreeRegressor in REG_TREES.items(): reg = TreeRegressor(random_state=0) y_hat = reg.fit(X, y).predict(T) assert_almost_equal(y_hat, y_true) assert_equal(y_hat.shape, (4, 2)) def test_classes_shape(): # Test that n_classes_ and classes_ have proper shape. for name, TreeClassifier in CLF_TREES.items(): # Classification, single output clf = TreeClassifier(random_state=0) clf.fit(X, y) assert_equal(clf.n_classes_, 2) assert_array_equal(clf.classes_, [-1, 1]) # Classification, multi-output _y = np.vstack((y, np.array(y) * 2)).T clf = TreeClassifier(random_state=0) clf.fit(X, _y) assert_equal(len(clf.n_classes_), 2) assert_equal(len(clf.classes_), 2) assert_array_equal(clf.n_classes_, [2, 2]) assert_array_equal(clf.classes_, [[-1, 1], [-2, 2]]) def test_unbalanced_iris(): # Check class rebalancing. unbalanced_X = iris.data[:125] unbalanced_y = iris.target[:125] sample_weight = _balance_weights(unbalanced_y) for name, TreeClassifier in CLF_TREES.items(): clf = TreeClassifier(random_state=0) clf.fit(unbalanced_X, unbalanced_y, sample_weight=sample_weight) assert_almost_equal(clf.predict(unbalanced_X), unbalanced_y) def test_memory_layout(): # Check that it works no matter the memory layout for (name, TreeEstimator), dtype in product(ALL_TREES.items(), [np.float64, np.float32]): est = TreeEstimator(random_state=0) # Nothing X = np.asarray(iris.data, dtype=dtype) y = iris.target assert_array_equal(est.fit(X, y).predict(X), y) # C-order X = np.asarray(iris.data, order="C", dtype=dtype) y = iris.target assert_array_equal(est.fit(X, y).predict(X), y) # F-order X = np.asarray(iris.data, order="F", dtype=dtype) y = iris.target assert_array_equal(est.fit(X, y).predict(X), y) # Contiguous X = np.ascontiguousarray(iris.data, dtype=dtype) y = iris.target assert_array_equal(est.fit(X, y).predict(X), y) if est.splitter in SPARSE_SPLITTERS: # csr matrix X = csr_matrix(iris.data, dtype=dtype) y = iris.target assert_array_equal(est.fit(X, y).predict(X), y) # csc_matrix X = csc_matrix(iris.data, dtype=dtype) y = iris.target assert_array_equal(est.fit(X, y).predict(X), y) # Strided X = np.asarray(iris.data[::3], dtype=dtype) y = iris.target[::3] assert_array_equal(est.fit(X, y).predict(X), y) def test_sample_weight(): # Check sample weighting. # Test that zero-weighted samples are not taken into account X = np.arange(100)[:, np.newaxis] y = np.ones(100) y[:50] = 0.0 sample_weight = np.ones(100) sample_weight[y == 0] = 0.0 clf = DecisionTreeClassifier(random_state=0) clf.fit(X, y, sample_weight=sample_weight) assert_array_equal(clf.predict(X), np.ones(100)) # Test that low weighted samples are not taken into account at low depth X = np.arange(200)[:, np.newaxis] y = np.zeros(200) y[50:100] = 1 y[100:200] = 2 X[100:200, 0] = 200 sample_weight = np.ones(200) sample_weight[y == 2] = .51 # Samples of class '2' are still weightier clf = DecisionTreeClassifier(max_depth=1, random_state=0) clf.fit(X, y, sample_weight=sample_weight) assert_equal(clf.tree_.threshold[0], 149.5) sample_weight[y == 2] = .5 # Samples of class '2' are no longer weightier clf = DecisionTreeClassifier(max_depth=1, random_state=0) clf.fit(X, y, sample_weight=sample_weight) assert_equal(clf.tree_.threshold[0], 49.5) # Threshold should have moved # Test that sample weighting is the same as having duplicates X = iris.data y = iris.target duplicates = rng.randint(0, X.shape[0], 200) clf = DecisionTreeClassifier(random_state=1) clf.fit(X[duplicates], y[duplicates]) sample_weight = np.bincount(duplicates, minlength=X.shape[0]) clf2 = DecisionTreeClassifier(random_state=1) clf2.fit(X, y, sample_weight=sample_weight) internal = clf.tree_.children_left != tree._tree.TREE_LEAF assert_array_almost_equal(clf.tree_.threshold[internal], clf2.tree_.threshold[internal]) def test_sample_weight_invalid(): # Check sample weighting raises errors. X = np.arange(100)[:, np.newaxis] y = np.ones(100) y[:50] = 0.0 clf = DecisionTreeClassifier(random_state=0) sample_weight = np.random.rand(100, 1) assert_raises(ValueError, clf.fit, X, y, sample_weight=sample_weight) sample_weight = np.array(0) assert_raises(ValueError, clf.fit, X, y, sample_weight=sample_weight) sample_weight = np.ones(101) assert_raises(ValueError, clf.fit, X, y, sample_weight=sample_weight) sample_weight = np.ones(99) assert_raises(ValueError, clf.fit, X, y, sample_weight=sample_weight) def check_class_weights(name): """Check class_weights resemble sample_weights behavior.""" TreeClassifier = CLF_TREES[name] # Iris is balanced, so no effect expected for using 'balanced' weights clf1 = TreeClassifier(random_state=0) clf1.fit(iris.data, iris.target) clf2 = TreeClassifier(class_weight='balanced', random_state=0) clf2.fit(iris.data, iris.target) assert_almost_equal(clf1.feature_importances_, clf2.feature_importances_) # Make a multi-output problem with three copies of Iris iris_multi = np.vstack((iris.target, iris.target, iris.target)).T # Create user-defined weights that should balance over the outputs clf3 = TreeClassifier(class_weight=[{0: 2., 1: 2., 2: 1.}, {0: 2., 1: 1., 2: 2.}, {0: 1., 1: 2., 2: 2.}], random_state=0) clf3.fit(iris.data, iris_multi) assert_almost_equal(clf2.feature_importances_, clf3.feature_importances_) # Check against multi-output "auto" which should also have no effect clf4 = TreeClassifier(class_weight='balanced', random_state=0) clf4.fit(iris.data, iris_multi) assert_almost_equal(clf3.feature_importances_, clf4.feature_importances_) # Inflate importance of class 1, check against user-defined weights sample_weight = np.ones(iris.target.shape) sample_weight[iris.target == 1] *= 100 class_weight = {0: 1., 1: 100., 2: 1.} clf1 = TreeClassifier(random_state=0) clf1.fit(iris.data, iris.target, sample_weight) clf2 = TreeClassifier(class_weight=class_weight, random_state=0) clf2.fit(iris.data, iris.target) assert_almost_equal(clf1.feature_importances_, clf2.feature_importances_) # Check that sample_weight and class_weight are multiplicative clf1 = TreeClassifier(random_state=0) clf1.fit(iris.data, iris.target, sample_weight ** 2) clf2 = TreeClassifier(class_weight=class_weight, random_state=0) clf2.fit(iris.data, iris.target, sample_weight) assert_almost_equal(clf1.feature_importances_, clf2.feature_importances_) def test_class_weights(): for name in CLF_TREES: yield check_class_weights, name def check_class_weight_errors(name): # Test if class_weight raises errors and warnings when expected. TreeClassifier = CLF_TREES[name] _y = np.vstack((y, np.array(y) * 2)).T # Invalid preset string clf = TreeClassifier(class_weight='the larch', random_state=0) assert_raises(ValueError, clf.fit, X, y) assert_raises(ValueError, clf.fit, X, _y) # Not a list or preset for multi-output clf = TreeClassifier(class_weight=1, random_state=0) assert_raises(ValueError, clf.fit, X, _y) # Incorrect length list for multi-output clf = TreeClassifier(class_weight=[{-1: 0.5, 1: 1.}], random_state=0) assert_raises(ValueError, clf.fit, X, _y) def test_class_weight_errors(): for name in CLF_TREES: yield check_class_weight_errors, name def test_max_leaf_nodes(): # Test greedy trees with max_depth + 1 leafs. from sklearn.tree._tree import TREE_LEAF X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) k = 4 for name, TreeEstimator in ALL_TREES.items(): est = TreeEstimator(max_depth=None, max_leaf_nodes=k + 1).fit(X, y) tree = est.tree_ assert_equal((tree.children_left == TREE_LEAF).sum(), k + 1) # max_leaf_nodes in (0, 1) should raise ValueError est = TreeEstimator(max_depth=None, max_leaf_nodes=0) assert_raises(ValueError, est.fit, X, y) est = TreeEstimator(max_depth=None, max_leaf_nodes=1) assert_raises(ValueError, est.fit, X, y) est = TreeEstimator(max_depth=None, max_leaf_nodes=0.1) assert_raises(ValueError, est.fit, X, y) def test_max_leaf_nodes_max_depth(): # Test preceedence of max_leaf_nodes over max_depth. X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) k = 4 for name, TreeEstimator in ALL_TREES.items(): est = TreeEstimator(max_depth=1, max_leaf_nodes=k).fit(X, y) tree = est.tree_ assert_greater(tree.max_depth, 1) def test_arrays_persist(): # Ensure property arrays' memory stays alive when tree disappears # non-regression for #2726 for attr in ['n_classes', 'value', 'children_left', 'children_right', 'threshold', 'impurity', 'feature', 'n_node_samples']: value = getattr(DecisionTreeClassifier().fit([[0]], [0]).tree_, attr) # if pointing to freed memory, contents may be arbitrary assert_true(-2 <= value.flat[0] < 2, 'Array points to arbitrary memory') def test_only_constant_features(): random_state = check_random_state(0) X = np.zeros((10, 20)) y = random_state.randint(0, 2, (10, )) for name, TreeEstimator in ALL_TREES.items(): est = TreeEstimator(random_state=0) est.fit(X, y) assert_equal(est.tree_.max_depth, 0) def test_with_only_one_non_constant_features(): X = np.hstack([np.array([[1.], [1.], [0.], [0.]]), np.zeros((4, 1000))]) y = np.array([0., 1., 0., 1.0]) for name, TreeEstimator in CLF_TREES.items(): est = TreeEstimator(random_state=0, max_features=1) est.fit(X, y) assert_equal(est.tree_.max_depth, 1) assert_array_equal(est.predict_proba(X), 0.5 * np.ones((4, 2))) for name, TreeEstimator in REG_TREES.items(): est = TreeEstimator(random_state=0, max_features=1) est.fit(X, y) assert_equal(est.tree_.max_depth, 1) assert_array_equal(est.predict(X), 0.5 * np.ones((4, ))) def test_big_input(): # Test if the warning for too large inputs is appropriate. X = np.repeat(10 ** 40., 4).astype(np.float64).reshape(-1, 1) clf = DecisionTreeClassifier() try: clf.fit(X, [0, 1, 0, 1]) except ValueError as e: assert_in("float32", str(e)) def test_realloc(): from sklearn.tree._tree import _realloc_test assert_raises(MemoryError, _realloc_test) def test_huge_allocations(): n_bits = int(platform.architecture()[0].rstrip('bit')) X = np.random.randn(10, 2) y = np.random.randint(0, 2, 10) # Sanity check: we cannot request more memory than the size of the address # space. Currently raises OverflowError. huge = 2 ** (n_bits + 1) clf = DecisionTreeClassifier(splitter='best', max_leaf_nodes=huge) assert_raises(Exception, clf.fit, X, y) # Non-regression test: MemoryError used to be dropped by Cython # because of missing "except *". huge = 2 ** (n_bits - 1) - 1 clf = DecisionTreeClassifier(splitter='best', max_leaf_nodes=huge) assert_raises(MemoryError, clf.fit, X, y) def check_sparse_input(tree, dataset, max_depth=None): TreeEstimator = ALL_TREES[tree] X = DATASETS[dataset]["X"] X_sparse = DATASETS[dataset]["X_sparse"] y = DATASETS[dataset]["y"] # Gain testing time if dataset in ["digits", "boston"]: n_samples = X.shape[0] // 5 X = X[:n_samples] X_sparse = X_sparse[:n_samples] y = y[:n_samples] for sparse_format in (csr_matrix, csc_matrix, coo_matrix): X_sparse = sparse_format(X_sparse) # Check the default (depth first search) d = TreeEstimator(random_state=0, max_depth=max_depth).fit(X, y) s = TreeEstimator(random_state=0, max_depth=max_depth).fit(X_sparse, y) assert_tree_equal(d.tree_, s.tree_, "{0} with dense and sparse format gave different " "trees".format(tree)) y_pred = d.predict(X) if tree in CLF_TREES: y_proba = d.predict_proba(X) y_log_proba = d.predict_log_proba(X) for sparse_matrix in (csr_matrix, csc_matrix, coo_matrix): X_sparse_test = sparse_matrix(X_sparse, dtype=np.float32) assert_array_almost_equal(s.predict(X_sparse_test), y_pred) if tree in CLF_TREES: assert_array_almost_equal(s.predict_proba(X_sparse_test), y_proba) assert_array_almost_equal(s.predict_log_proba(X_sparse_test), y_log_proba) def test_sparse_input(): for tree, dataset in product(SPARSE_TREES, ("clf_small", "toy", "digits", "multilabel", "sparse-pos", "sparse-neg", "sparse-mix", "zeros")): max_depth = 3 if dataset == "digits" else None yield (check_sparse_input, tree, dataset, max_depth) # Due to numerical instability of MSE and too strict test, we limit the # maximal depth for tree, dataset in product(REG_TREES, ["boston", "reg_small"]): if tree in SPARSE_TREES: yield (check_sparse_input, tree, dataset, 2) def check_sparse_parameters(tree, dataset): TreeEstimator = ALL_TREES[tree] X = DATASETS[dataset]["X"] X_sparse = DATASETS[dataset]["X_sparse"] y = DATASETS[dataset]["y"] # Check max_features d = TreeEstimator(random_state=0, max_features=1, max_depth=2).fit(X, y) s = TreeEstimator(random_state=0, max_features=1, max_depth=2).fit(X_sparse, y) assert_tree_equal(d.tree_, s.tree_, "{0} with dense and sparse format gave different " "trees".format(tree)) assert_array_almost_equal(s.predict(X), d.predict(X)) # Check min_samples_split d = TreeEstimator(random_state=0, max_features=1, min_samples_split=10).fit(X, y) s = TreeEstimator(random_state=0, max_features=1, min_samples_split=10).fit(X_sparse, y) assert_tree_equal(d.tree_, s.tree_, "{0} with dense and sparse format gave different " "trees".format(tree)) assert_array_almost_equal(s.predict(X), d.predict(X)) # Check min_samples_leaf d = TreeEstimator(random_state=0, min_samples_leaf=X_sparse.shape[0] // 2).fit(X, y) s = TreeEstimator(random_state=0, min_samples_leaf=X_sparse.shape[0] // 2).fit(X_sparse, y) assert_tree_equal(d.tree_, s.tree_, "{0} with dense and sparse format gave different " "trees".format(tree)) assert_array_almost_equal(s.predict(X), d.predict(X)) # Check best-first search d = TreeEstimator(random_state=0, max_leaf_nodes=3).fit(X, y) s = TreeEstimator(random_state=0, max_leaf_nodes=3).fit(X_sparse, y) assert_tree_equal(d.tree_, s.tree_, "{0} with dense and sparse format gave different " "trees".format(tree)) assert_array_almost_equal(s.predict(X), d.predict(X)) def test_sparse_parameters(): for tree, dataset in product(SPARSE_TREES, ["sparse-pos", "sparse-neg", "sparse-mix", "zeros"]): yield (check_sparse_parameters, tree, dataset) def check_sparse_criterion(tree, dataset): TreeEstimator = ALL_TREES[tree] X = DATASETS[dataset]["X"] X_sparse = DATASETS[dataset]["X_sparse"] y = DATASETS[dataset]["y"] # Check various criterion CRITERIONS = REG_CRITERIONS if tree in REG_TREES else CLF_CRITERIONS for criterion in CRITERIONS: d = TreeEstimator(random_state=0, max_depth=3, criterion=criterion).fit(X, y) s = TreeEstimator(random_state=0, max_depth=3, criterion=criterion).fit(X_sparse, y) assert_tree_equal(d.tree_, s.tree_, "{0} with dense and sparse format gave different " "trees".format(tree)) assert_array_almost_equal(s.predict(X), d.predict(X)) def test_sparse_criterion(): for tree, dataset in product(SPARSE_TREES, ["sparse-pos", "sparse-neg", "sparse-mix", "zeros"]): yield (check_sparse_criterion, tree, dataset) def check_explicit_sparse_zeros(tree, max_depth=3, n_features=10): TreeEstimator = ALL_TREES[tree] # n_samples set n_feature to ease construction of a simultaneous # construction of a csr and csc matrix n_samples = n_features samples = np.arange(n_samples) # Generate X, y random_state = check_random_state(0) indices = [] data = [] offset = 0 indptr = [offset] for i in range(n_features): n_nonzero_i = random_state.binomial(n_samples, 0.5) indices_i = random_state.permutation(samples)[:n_nonzero_i] indices.append(indices_i) data_i = random_state.binomial(3, 0.5, size=(n_nonzero_i, )) - 1 data.append(data_i) offset += n_nonzero_i indptr.append(offset) indices = np.concatenate(indices) data = np.array(np.concatenate(data), dtype=np.float32) X_sparse = csc_matrix((data, indices, indptr), shape=(n_samples, n_features)) X = X_sparse.toarray() X_sparse_test = csr_matrix((data, indices, indptr), shape=(n_samples, n_features)) X_test = X_sparse_test.toarray() y = random_state.randint(0, 3, size=(n_samples, )) # Ensure that X_sparse_test owns its data, indices and indptr array X_sparse_test = X_sparse_test.copy() # Ensure that we have explicit zeros assert_greater((X_sparse.data == 0.).sum(), 0) assert_greater((X_sparse_test.data == 0.).sum(), 0) # Perform the comparison d = TreeEstimator(random_state=0, max_depth=max_depth).fit(X, y) s = TreeEstimator(random_state=0, max_depth=max_depth).fit(X_sparse, y) assert_tree_equal(d.tree_, s.tree_, "{0} with dense and sparse format gave different " "trees".format(tree)) Xs = (X_test, X_sparse_test) for X1, X2 in product(Xs, Xs): assert_array_almost_equal(s.tree_.apply(X1), d.tree_.apply(X2)) assert_array_almost_equal(s.apply(X1), d.apply(X2)) assert_array_almost_equal(s.apply(X1), s.tree_.apply(X1)) assert_array_almost_equal(s.predict(X1), d.predict(X2)) if tree in CLF_TREES: assert_array_almost_equal(s.predict_proba(X1), d.predict_proba(X2)) def test_explicit_sparse_zeros(): for tree in SPARSE_TREES: yield (check_explicit_sparse_zeros, tree) def check_raise_error_on_1d_input(name): TreeEstimator = ALL_TREES[name] X = iris.data[:, 0].ravel() X_2d = iris.data[:, 0].reshape((-1, 1)) y = iris.target assert_raises(ValueError, TreeEstimator(random_state=0).fit, X, y) est = TreeEstimator(random_state=0) est.fit(X_2d, y) assert_raises(ValueError, est.predict, X) def test_1d_input(): for name in ALL_TREES: yield check_raise_error_on_1d_input, name def _check_min_weight_leaf_split_level(TreeEstimator, X, y, sample_weight): # Private function to keep pretty printing in nose yielded tests est = TreeEstimator(random_state=0) est.fit(X, y, sample_weight=sample_weight) assert_equal(est.tree_.max_depth, 1) est = TreeEstimator(random_state=0, min_weight_fraction_leaf=0.4) est.fit(X, y, sample_weight=sample_weight) assert_equal(est.tree_.max_depth, 0) def check_min_weight_leaf_split_level(name): TreeEstimator = ALL_TREES[name] X = np.array([[0], [0], [0], [0], [1]]) y = [0, 0, 0, 0, 1] sample_weight = [0.2, 0.2, 0.2, 0.2, 0.2] _check_min_weight_leaf_split_level(TreeEstimator, X, y, sample_weight) if TreeEstimator().splitter in SPARSE_SPLITTERS: _check_min_weight_leaf_split_level(TreeEstimator, csc_matrix(X), y, sample_weight) def test_min_weight_leaf_split_level(): for name in ALL_TREES: yield check_min_weight_leaf_split_level, name def check_public_apply(name): X_small32 = X_small.astype(tree._tree.DTYPE) est = ALL_TREES[name]() est.fit(X_small, y_small) assert_array_equal(est.apply(X_small), est.tree_.apply(X_small32)) def check_public_apply_sparse(name): X_small32 = csr_matrix(X_small.astype(tree._tree.DTYPE)) est = ALL_TREES[name]() est.fit(X_small, y_small) assert_array_equal(est.apply(X_small), est.tree_.apply(X_small32)) def test_public_apply(): for name in ALL_TREES: yield (check_public_apply, name) for name in SPARSE_TREES: yield (check_public_apply_sparse, name)
bsd-3-clause
richardbeare/SimpleITK
Examples/DicomConvert/DicomConvert.py
4
6196
# ========================================================================= # # Copyright NumFOCUS # # 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.txt # # 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. # # ========================================================================= import argparse import csv import functools import itertools import multiprocessing import os import sys import SimpleITK as sitk def convert_image(input_file_name, output_file_name, new_width=None): try: image_file_reader = sitk.ImageFileReader() # only read DICOM images image_file_reader.SetImageIO('GDCMImageIO') image_file_reader.SetFileName(input_file_name) image_file_reader.ReadImageInformation() image_size = list(image_file_reader.GetSize()) if len(image_size) == 3 and image_size[2] == 1: image_size[2] = 0 image_file_reader.SetExtractSize(image_size) image = image_file_reader.Execute() if new_width: original_size = image.GetSize() original_spacing = image.GetSpacing() new_spacing = [(original_size[0] - 1) * original_spacing[0] / (new_width - 1)] * 2 new_size = [new_width, int((original_size[1] - 1) * original_spacing[1] / new_spacing[1])] image = sitk.Resample(image1=image, size=new_size, transform=sitk.Transform(), interpolator=sitk.sitkLinear, outputOrigin=image.GetOrigin(), outputSpacing=new_spacing, outputDirection=image.GetDirection(), defaultPixelValue=0, outputPixelType=image.GetPixelID()) # If a single channel image, rescale to [0,255]. Also modify the # intensity values based on the photometric interpretation. If # MONOCHROME2 (minimum should be displayed as black) we don't need to # do anything, if image has MONOCRHOME1 (minimum should be displayed as # white) we flip # the intensities. This is a constraint imposed by ITK # which always assumes MONOCHROME2. if image.GetNumberOfComponentsPerPixel() == 1: image = sitk.RescaleIntensity(image, 0, 255) if image_file_reader.GetMetaData('0028|0004').strip() \ == 'MONOCHROME1': image = sitk.InvertIntensity(image, maximum=255) image = sitk.Cast(image, sitk.sitkUInt8) sitk.WriteImage(image, output_file_name) return True except BaseException: return False def convert_images(input_file_names, output_file_names, new_width): MAX_PROCESSES = 15 with multiprocessing.Pool(processes=MAX_PROCESSES) as pool: return pool.starmap(functools.partial(convert_image, new_width=new_width), zip(input_file_names, output_file_names)) def positive_int(int_str): value = int(int_str) if value <= 0: raise argparse.ArgumentTypeError( int_str + ' is not a positive integer value') return value def directory(dir_name): if not os.path.isdir(dir_name): raise argparse.ArgumentTypeError(dir_name + ' is not a valid directory name') return dir_name def main(argv=None): parser = argparse.ArgumentParser( description='Convert and resize DICOM files to common image types.') parser.add_argument('root_of_data_directory', type=directory, help='Path to the topmost directory containing data.') parser.add_argument( 'output_file_extension', help='Image file extension, this determines output file type ' '(e.g. png) .') parser.add_argument('--w', type=positive_int, help='Width of converted images.') parser.add_argument('--od', type=directory, help='Output directory.') args = parser.parse_args(argv) input_file_names = [] for dir_name, subdir_names, file_names in os.walk( args.root_of_data_directory): input_file_names += [os.path.join(os.path.abspath(dir_name), fname) for fname in file_names] if args.od: # if all output files are written to the same directory we need them # to have a unique name, so use an index. file_names = [os.path.join(os.path.abspath(args.od), str(i)) for i in range(len(input_file_names))] else: file_names = input_file_names output_file_names = [file_name + '.' + args.output_file_extension for file_name in file_names] res = convert_images(input_file_names, output_file_names, args.w) input_file_names = list(itertools.compress(input_file_names, res)) output_file_names = list(itertools.compress(output_file_names, res)) # save csv file mapping input and output file names. # using csv module and not pandas so as not to create more dependencies # for the examples. pandas based code is more elegant/shorter. dir_name = args.od if args.od else os.getcwd() with open(os.path.join(dir_name, 'file_names.csv'), mode='w') as fp: fp_writer = csv.writer(fp, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) fp_writer.writerow(['input file name', 'output file name']) for data in zip(input_file_names, output_file_names): fp_writer.writerow(data) if __name__ == "__main__": sys.exit(main())
apache-2.0
nan86150/ImageFusion
lib/python2.7/site-packages/scipy/interpolate/interpolate.py
18
80196
""" Classes for interpolating values. """ from __future__ import division, print_function, absolute_import __all__ = ['interp1d', 'interp2d', 'spline', 'spleval', 'splmake', 'spltopp', 'ppform', 'lagrange', 'PPoly', 'BPoly', 'RegularGridInterpolator', 'interpn'] import itertools from numpy import (shape, sometrue, array, transpose, searchsorted, ones, logical_or, atleast_1d, atleast_2d, ravel, dot, poly1d, asarray, intp) import numpy as np import scipy.linalg import scipy.special as spec from scipy.special import comb import math import warnings import functools import operator from scipy._lib.six import xrange, integer_types from . import fitpack from . import dfitpack from . import _fitpack from .polyint import _Interpolator1D from . import _ppoly from .fitpack2 import RectBivariateSpline from .interpnd import _ndim_coords_from_arrays def reduce_sometrue(a): all = a while len(shape(all)) > 1: all = sometrue(all, axis=0) return all def prod(x): """Product of a list of numbers; ~40x faster vs np.prod for Python tuples""" if len(x) == 0: return 1 return functools.reduce(operator.mul, x) def lagrange(x, w): """ Return a Lagrange interpolating polynomial. Given two 1-D arrays `x` and `w,` returns the Lagrange interpolating polynomial through the points ``(x, w)``. Warning: This implementation is numerically unstable. Do not expect to be able to use more than about 20 points even if they are chosen optimally. Parameters ---------- x : array_like `x` represents the x-coordinates of a set of datapoints. w : array_like `w` represents the y-coordinates of a set of datapoints, i.e. f(`x`). Returns ------- lagrange : numpy.poly1d instance The Lagrange interpolating polynomial. """ M = len(x) p = poly1d(0.0) for j in xrange(M): pt = poly1d(w[j]) for k in xrange(M): if k == j: continue fac = x[j]-x[k] pt *= poly1d([1.0, -x[k]])/fac p += pt return p # !! Need to find argument for keeping initialize. If it isn't # !! found, get rid of it! class interp2d(object): """ interp2d(x, y, z, kind='linear', copy=True, bounds_error=False, fill_value=nan) Interpolate over a 2-D grid. `x`, `y` and `z` are arrays of values used to approximate some function f: ``z = f(x, y)``. This class returns a function whose call method uses spline interpolation to find the value of new points. If `x` and `y` represent a regular grid, consider using RectBivariateSpline. Methods ------- __call__ Parameters ---------- x, y : array_like Arrays defining the data point coordinates. If the points lie on a regular grid, `x` can specify the column coordinates and `y` the row coordinates, for example:: >>> x = [0,1,2]; y = [0,3]; z = [[1,2,3], [4,5,6]] Otherwise, `x` and `y` must specify the full coordinates for each point, for example:: >>> x = [0,1,2,0,1,2]; y = [0,0,0,3,3,3]; z = [1,2,3,4,5,6] If `x` and `y` are multi-dimensional, they are flattened before use. z : array_like The values of the function to interpolate at the data points. If `z` is a multi-dimensional array, it is flattened before use. The length of a flattened `z` array is either len(`x`)*len(`y`) if `x` and `y` specify the column and row coordinates or ``len(z) == len(x) == len(y)`` if `x` and `y` specify coordinates for each point. kind : {'linear', 'cubic', 'quintic'}, optional The kind of spline interpolation to use. Default is 'linear'. copy : bool, optional If True, the class makes internal copies of x, y and z. If False, references may be used. The default is to copy. bounds_error : bool, optional If True, when interpolated values are requested outside of the domain of the input data (x,y), a ValueError is raised. If False, then `fill_value` is used. fill_value : number, optional If provided, the value to use for points outside of the interpolation domain. If omitted (None), values outside the domain are extrapolated. Returns ------- values_x : ndarray, shape xi.shape[:-1] + values.shape[ndim:] Interpolated values at input coordinates. See Also -------- RectBivariateSpline : Much faster 2D interpolation if your input data is on a grid bisplrep, bisplev : Spline interpolation based on FITPACK BivariateSpline : a more recent wrapper of the FITPACK routines interp1d : one dimension version of this function Notes ----- The minimum number of data points required along the interpolation axis is ``(k+1)**2``, with k=1 for linear, k=3 for cubic and k=5 for quintic interpolation. The interpolator is constructed by `bisplrep`, with a smoothing factor of 0. If more control over smoothing is needed, `bisplrep` should be used directly. Examples -------- Construct a 2-D grid and interpolate on it: >>> from scipy import interpolate >>> x = np.arange(-5.01, 5.01, 0.25) >>> y = np.arange(-5.01, 5.01, 0.25) >>> xx, yy = np.meshgrid(x, y) >>> z = np.sin(xx**2+yy**2) >>> f = interpolate.interp2d(x, y, z, kind='cubic') Now use the obtained interpolation function and plot the result: >>> import matplotlib.pyplot as plt >>> xnew = np.arange(-5.01, 5.01, 1e-2) >>> ynew = np.arange(-5.01, 5.01, 1e-2) >>> znew = f(xnew, ynew) >>> plt.plot(x, z[0, :], 'ro-', xnew, znew[0, :], 'b-') >>> plt.show() """ def __init__(self, x, y, z, kind='linear', copy=True, bounds_error=False, fill_value=None): x = ravel(x) y = ravel(y) z = asarray(z) rectangular_grid = (z.size == len(x) * len(y)) if rectangular_grid: if z.ndim == 2: if z.shape != (len(y), len(x)): raise ValueError("When on a regular grid with x.size = m " "and y.size = n, if z.ndim == 2, then z " "must have shape (n, m)") if not np.all(x[1:] >= x[:-1]): j = np.argsort(x) x = x[j] z = z[:, j] if not np.all(y[1:] >= y[:-1]): j = np.argsort(y) y = y[j] z = z[j, :] z = ravel(z.T) else: z = ravel(z) if len(x) != len(y): raise ValueError( "x and y must have equal lengths for non rectangular grid") if len(z) != len(x): raise ValueError( "Invalid length for input z for non rectangular grid") try: kx = ky = {'linear': 1, 'cubic': 3, 'quintic': 5}[kind] except KeyError: raise ValueError("Unsupported interpolation type.") if not rectangular_grid: # TODO: surfit is really not meant for interpolation! self.tck = fitpack.bisplrep(x, y, z, kx=kx, ky=ky, s=0.0) else: nx, tx, ny, ty, c, fp, ier = dfitpack.regrid_smth( x, y, z, None, None, None, None, kx=kx, ky=ky, s=0.0) self.tck = (tx[:nx], ty[:ny], c[:(nx - kx - 1) * (ny - ky - 1)], kx, ky) self.bounds_error = bounds_error self.fill_value = fill_value self.x, self.y, self.z = [array(a, copy=copy) for a in (x, y, z)] self.x_min, self.x_max = np.amin(x), np.amax(x) self.y_min, self.y_max = np.amin(y), np.amax(y) def __call__(self, x, y, dx=0, dy=0, assume_sorted=False): """Interpolate the function. Parameters ---------- x : 1D array x-coordinates of the mesh on which to interpolate. y : 1D array y-coordinates of the mesh on which to interpolate. dx : int >= 0, < kx Order of partial derivatives in x. dy : int >= 0, < ky Order of partial derivatives in y. assume_sorted : bool, optional If False, values of `x` and `y` can be in any order and they are sorted first. If True, `x` and `y` have to be arrays of monotonically increasing values. Returns ------- z : 2D array with shape (len(y), len(x)) The interpolated values. """ x = atleast_1d(x) y = atleast_1d(y) if x.ndim != 1 or y.ndim != 1: raise ValueError("x and y should both be 1-D arrays") if not assume_sorted: x = np.sort(x) y = np.sort(y) if self.bounds_error or self.fill_value is not None: out_of_bounds_x = (x < self.x_min) | (x > self.x_max) out_of_bounds_y = (y < self.y_min) | (y > self.y_max) any_out_of_bounds_x = np.any(out_of_bounds_x) any_out_of_bounds_y = np.any(out_of_bounds_y) if self.bounds_error and (any_out_of_bounds_x or any_out_of_bounds_y): raise ValueError("Values out of range; x must be in %r, y in %r" % ((self.x_min, self.x_max), (self.y_min, self.y_max))) z = fitpack.bisplev(x, y, self.tck, dx, dy) z = atleast_2d(z) z = transpose(z) if self.fill_value is not None: if any_out_of_bounds_x: z[:, out_of_bounds_x] = self.fill_value if any_out_of_bounds_y: z[out_of_bounds_y, :] = self.fill_value if len(z) == 1: z = z[0] return array(z) class interp1d(_Interpolator1D): """ Interpolate a 1-D function. `x` and `y` are arrays of values used to approximate some function f: ``y = f(x)``. This class returns a function whose call method uses interpolation to find the value of new points. Parameters ---------- x : (N,) array_like A 1-D array of real values. y : (...,N,...) array_like A N-D array of real values. The length of `y` along the interpolation axis must be equal to the length of `x`. kind : str or int, optional Specifies the kind of interpolation as a string ('linear', 'nearest', 'zero', 'slinear', 'quadratic, 'cubic' where 'slinear', 'quadratic' and 'cubic' refer to a spline interpolation of first, second or third order) or as an integer specifying the order of the spline interpolator to use. Default is 'linear'. axis : int, optional Specifies the axis of `y` along which to interpolate. Interpolation defaults to the last axis of `y`. copy : bool, optional If True, the class makes internal copies of x and y. If False, references to `x` and `y` are used. The default is to copy. bounds_error : bool, optional If True, a ValueError is raised any time interpolation is attempted on a value outside of the range of x (where extrapolation is necessary). If False, out of bounds values are assigned `fill_value`. By default, an error is raised. fill_value : float, optional If provided, then this value will be used to fill in for requested points outside of the data range. If not provided, then the default is NaN. assume_sorted : bool, optional If False, values of `x` can be in any order and they are sorted first. If True, `x` has to be an array of monotonically increasing values. Methods ------- __call__ See Also -------- splrep, splev Spline interpolation/smoothing based on FITPACK. UnivariateSpline : An object-oriented wrapper of the FITPACK routines. interp2d : 2-D interpolation Examples -------- >>> import matplotlib.pyplot as plt >>> from scipy import interpolate >>> x = np.arange(0, 10) >>> y = np.exp(-x/3.0) >>> f = interpolate.interp1d(x, y) >>> xnew = np.arange(0, 9, 0.1) >>> ynew = f(xnew) # use interpolation function returned by `interp1d` >>> plt.plot(x, y, 'o', xnew, ynew, '-') >>> plt.show() """ def __init__(self, x, y, kind='linear', axis=-1, copy=True, bounds_error=True, fill_value=np.nan, assume_sorted=False): """ Initialize a 1D linear interpolation class.""" _Interpolator1D.__init__(self, x, y, axis=axis) self.copy = copy self.bounds_error = bounds_error self.fill_value = fill_value if kind in ['zero', 'slinear', 'quadratic', 'cubic']: order = {'nearest': 0, 'zero': 0,'slinear': 1, 'quadratic': 2, 'cubic': 3}[kind] kind = 'spline' elif isinstance(kind, int): order = kind kind = 'spline' elif kind not in ('linear', 'nearest'): raise NotImplementedError("%s is unsupported: Use fitpack " "routines for other types." % kind) x = array(x, copy=self.copy) y = array(y, copy=self.copy) if not assume_sorted: ind = np.argsort(x) x = x[ind] y = np.take(y, ind, axis=axis) if x.ndim != 1: raise ValueError("the x array must have exactly one dimension.") if y.ndim == 0: raise ValueError("the y array must have at least one dimension.") # Force-cast y to a floating-point type, if it's not yet one if not issubclass(y.dtype.type, np.inexact): y = y.astype(np.float_) # Backward compatibility self.axis = axis % y.ndim # Interpolation goes internally along the first axis self.y = y y = self._reshape_yi(y) # Adjust to interpolation kind; store reference to *unbound* # interpolation methods, in order to avoid circular references to self # stored in the bound instance methods, and therefore delayed garbage # collection. See: http://docs.python.org/2/reference/datamodel.html if kind in ('linear', 'nearest'): # Make a "view" of the y array that is rotated to the interpolation # axis. minval = 2 if kind == 'nearest': self.x_bds = (x[1:] + x[:-1]) / 2.0 self._call = self.__class__._call_nearest else: self._call = self.__class__._call_linear else: minval = order + 1 self._spline = splmake(x, y, order=order) self._call = self.__class__._call_spline if len(x) < minval: raise ValueError("x and y arrays must have at " "least %d entries" % minval) self._kind = kind self.x = x self._y = y def _call_linear(self, x_new): # 2. Find where in the orignal data, the values to interpolate # would be inserted. # Note: If x_new[n] == x[m], then m is returned by searchsorted. x_new_indices = searchsorted(self.x, x_new) # 3. Clip x_new_indices so that they are within the range of # self.x indices and at least 1. Removes mis-interpolation # of x_new[n] = x[0] x_new_indices = x_new_indices.clip(1, len(self.x)-1).astype(int) # 4. Calculate the slope of regions that each x_new value falls in. lo = x_new_indices - 1 hi = x_new_indices x_lo = self.x[lo] x_hi = self.x[hi] y_lo = self._y[lo] y_hi = self._y[hi] # Note that the following two expressions rely on the specifics of the # broadcasting semantics. slope = (y_hi - y_lo) / (x_hi - x_lo)[:, None] # 5. Calculate the actual value for each entry in x_new. y_new = slope*(x_new - x_lo)[:, None] + y_lo return y_new def _call_nearest(self, x_new): """ Find nearest neighbour interpolated y_new = f(x_new).""" # 2. Find where in the averaged data the values to interpolate # would be inserted. # Note: use side='left' (right) to searchsorted() to define the # halfway point to be nearest to the left (right) neighbour x_new_indices = searchsorted(self.x_bds, x_new, side='left') # 3. Clip x_new_indices so that they are within the range of x indices. x_new_indices = x_new_indices.clip(0, len(self.x)-1).astype(intp) # 4. Calculate the actual value for each entry in x_new. y_new = self._y[x_new_indices] return y_new def _call_spline(self, x_new): return spleval(self._spline, x_new) def _evaluate(self, x_new): # 1. Handle values in x_new that are outside of x. Throw error, # or return a list of mask array indicating the outofbounds values. # The behavior is set by the bounds_error variable. x_new = asarray(x_new) out_of_bounds = self._check_bounds(x_new) y_new = self._call(self, x_new) if len(y_new) > 0: y_new[out_of_bounds] = self.fill_value return y_new def _check_bounds(self, x_new): """Check the inputs for being in the bounds of the interpolated data. Parameters ---------- x_new : array Returns ------- out_of_bounds : bool array The mask on x_new of values that are out of the bounds. """ # If self.bounds_error is True, we raise an error if any x_new values # fall outside the range of x. Otherwise, we return an array indicating # which values are outside the boundary region. below_bounds = x_new < self.x[0] above_bounds = x_new > self.x[-1] # !! Could provide more information about which values are out of bounds if self.bounds_error and below_bounds.any(): raise ValueError("A value in x_new is below the interpolation " "range.") if self.bounds_error and above_bounds.any(): raise ValueError("A value in x_new is above the interpolation " "range.") # !! Should we emit a warning if some values are out of bounds? # !! matlab does not. out_of_bounds = logical_or(below_bounds, above_bounds) return out_of_bounds class _PPolyBase(object): """ Base class for piecewise polynomials. """ __slots__ = ('c', 'x', 'extrapolate', 'axis') def __init__(self, c, x, extrapolate=None, axis=0): self.c = np.asarray(c) self.x = np.ascontiguousarray(x, dtype=np.float64) if extrapolate is None: extrapolate = True self.extrapolate = bool(extrapolate) if not (0 <= axis < self.c.ndim - 1): raise ValueError("%s must be between 0 and %s" % (axis, c.ndim-1)) self.axis = axis if axis != 0: # roll the interpolation axis to be the first one in self.c # More specifically, the target shape for self.c is (k, m, ...), # and axis !=0 means that we have c.shape (..., k, m, ...) # ^ # axis # So we roll two of them. self.c = np.rollaxis(self.c, axis+1) self.c = np.rollaxis(self.c, axis+1) if self.x.ndim != 1: raise ValueError("x must be 1-dimensional") if self.x.size < 2: raise ValueError("at least 2 breakpoints are needed") if self.c.ndim < 2: raise ValueError("c must have at least 2 dimensions") if self.c.shape[0] == 0: raise ValueError("polynomial must be at least of order 0") if self.c.shape[1] != self.x.size-1: raise ValueError("number of coefficients != len(x)-1") if np.any(self.x[1:] - self.x[:-1] < 0): raise ValueError("x-coordinates are not in increasing order") dtype = self._get_dtype(self.c.dtype) self.c = np.ascontiguousarray(self.c, dtype=dtype) def _get_dtype(self, dtype): if np.issubdtype(dtype, np.complexfloating) \ or np.issubdtype(self.c.dtype, np.complexfloating): return np.complex_ else: return np.float_ @classmethod def construct_fast(cls, c, x, extrapolate=None, axis=0): """ Construct the piecewise polynomial without making checks. Takes the same parameters as the constructor. Input arguments `c` and `x` must be arrays of the correct shape and type. The `c` array can only be of dtypes float and complex, and `x` array must have dtype float. """ self = object.__new__(cls) self.c = c self.x = x self.axis = axis if extrapolate is None: extrapolate = True self.extrapolate = extrapolate return self def _ensure_c_contiguous(self): """ c and x may be modified by the user. The Cython code expects that they are C contiguous. """ if not self.x.flags.c_contiguous: self.x = self.x.copy() if not self.c.flags.c_contiguous: self.c = self.c.copy() def extend(self, c, x, right=True): """ Add additional breakpoints and coefficients to the polynomial. Parameters ---------- c : ndarray, size (k, m, ...) Additional coefficients for polynomials in intervals ``self.x[-1] <= x < x_right[0]``, ``x_right[0] <= x < x_right[1]``, ..., ``x_right[m-2] <= x < x_right[m-1]`` x : ndarray, size (m,) Additional breakpoints. Must be sorted and either to the right or to the left of the current breakpoints. right : bool, optional Whether the new intervals are to the right or to the left of the current intervals. """ c = np.asarray(c) x = np.asarray(x) if c.ndim < 2: raise ValueError("invalid dimensions for c") if x.ndim != 1: raise ValueError("invalid dimensions for x") if x.shape[0] != c.shape[1]: raise ValueError("x and c have incompatible sizes") if c.shape[2:] != self.c.shape[2:] or c.ndim != self.c.ndim: raise ValueError("c and self.c have incompatible shapes") if right: if x[0] < self.x[-1]: raise ValueError("new x are not to the right of current ones") else: if x[-1] > self.x[0]: raise ValueError("new x are not to the left of current ones") if c.size == 0: return dtype = self._get_dtype(c.dtype) k2 = max(c.shape[0], self.c.shape[0]) c2 = np.zeros((k2, self.c.shape[1] + c.shape[1]) + self.c.shape[2:], dtype=dtype) if right: c2[k2-self.c.shape[0]:, :self.c.shape[1]] = self.c c2[k2-c.shape[0]:, self.c.shape[1]:] = c self.x = np.r_[self.x, x] else: c2[k2-self.c.shape[0]:, :c.shape[1]] = c c2[k2-c.shape[0]:, c.shape[1]:] = self.c self.x = np.r_[x, self.x] self.c = c2 def __call__(self, x, nu=0, extrapolate=None): """ Evaluate the piecewise polynomial or its derivative Parameters ---------- x : array_like Points to evaluate the interpolant at. nu : int, optional Order of derivative to evaluate. Must be non-negative. extrapolate : bool, optional Whether to extrapolate to ouf-of-bounds points based on first and last intervals, or to return NaNs. Returns ------- y : array_like Interpolated values. Shape is determined by replacing the interpolation axis in the original array with the shape of x. Notes ----- Derivatives are evaluated piecewise for each polynomial segment, even if the polynomial is not differentiable at the breakpoints. The polynomial intervals are considered half-open, ``[a, b)``, except for the last interval which is closed ``[a, b]``. """ if extrapolate is None: extrapolate = self.extrapolate x = np.asarray(x) x_shape, x_ndim = x.shape, x.ndim x = np.ascontiguousarray(x.ravel(), dtype=np.float_) out = np.empty((len(x), prod(self.c.shape[2:])), dtype=self.c.dtype) self._ensure_c_contiguous() self._evaluate(x, nu, extrapolate, out) out = out.reshape(x_shape + self.c.shape[2:]) if self.axis != 0: # transpose to move the calculated values to the interpolation axis l = list(range(out.ndim)) l = l[x_ndim:x_ndim+self.axis] + l[:x_ndim] + l[x_ndim+self.axis:] out = out.transpose(l) return out class PPoly(_PPolyBase): """ Piecewise polynomial in terms of coefficients and breakpoints The polynomial in the ith interval is ``x[i] <= xp < x[i+1]``:: S = sum(c[m, i] * (xp - x[i])**(k-m) for m in range(k+1)) where ``k`` is the degree of the polynomial. This representation is the local power basis. Parameters ---------- c : ndarray, shape (k, m, ...) Polynomial coefficients, order `k` and `m` intervals x : ndarray, shape (m+1,) Polynomial breakpoints. These must be sorted in increasing order. extrapolate : bool, optional Whether to extrapolate to ouf-of-bounds points based on first and last intervals, or to return NaNs. Default: True. axis : int, optional Interpolation axis. Default is zero. Attributes ---------- x : ndarray Breakpoints. c : ndarray Coefficients of the polynomials. They are reshaped to a 3-dimensional array with the last dimension representing the trailing dimensions of the original coefficient array. axis : int Interpolation axis. Methods ------- __call__ derivative antiderivative integrate roots extend from_spline from_bernstein_basis construct_fast See also -------- BPoly : piecewise polynomials in the Bernstein basis Notes ----- High-order polynomials in the power basis can be numerically unstable. Precision problems can start to appear for orders larger than 20-30. """ def _evaluate(self, x, nu, extrapolate, out): _ppoly.evaluate(self.c.reshape(self.c.shape[0], self.c.shape[1], -1), self.x, x, nu, bool(extrapolate), out) def derivative(self, nu=1): """ Construct a new piecewise polynomial representing the derivative. Parameters ---------- nu : int, optional Order of derivative to evaluate. (Default: 1) If negative, the antiderivative is returned. Returns ------- pp : PPoly Piecewise polynomial of order k2 = k - n representing the derivative of this polynomial. Notes ----- Derivatives are evaluated piecewise for each polynomial segment, even if the polynomial is not differentiable at the breakpoints. The polynomial intervals are considered half-open, ``[a, b)``, except for the last interval which is closed ``[a, b]``. """ if nu < 0: return self.antiderivative(-nu) # reduce order if nu == 0: c2 = self.c.copy() else: c2 = self.c[:-nu,:].copy() if c2.shape[0] == 0: # derivative of order 0 is zero c2 = np.zeros((1,) + c2.shape[1:], dtype=c2.dtype) # multiply by the correct rising factorials factor = spec.poch(np.arange(c2.shape[0], 0, -1), nu) c2 *= factor[(slice(None),) + (None,)*(c2.ndim-1)] # construct a compatible polynomial return self.construct_fast(c2, self.x, self.extrapolate, self.axis) def antiderivative(self, nu=1): """ Construct a new piecewise polynomial representing the antiderivative. Antiderivativative is also the indefinite integral of the function, and derivative is its inverse operation. Parameters ---------- nu : int, optional Order of antiderivative to evaluate. (Default: 1) If negative, the derivative is returned. Returns ------- pp : PPoly Piecewise polynomial of order k2 = k + n representing the antiderivative of this polynomial. Notes ----- The antiderivative returned by this function is continuous and continuously differentiable to order n-1, up to floating point rounding error. """ if nu <= 0: return self.derivative(-nu) c = np.zeros((self.c.shape[0] + nu, self.c.shape[1]) + self.c.shape[2:], dtype=self.c.dtype) c[:-nu] = self.c # divide by the correct rising factorials factor = spec.poch(np.arange(self.c.shape[0], 0, -1), nu) c[:-nu] /= factor[(slice(None),) + (None,)*(c.ndim-1)] # fix continuity of added degrees of freedom self._ensure_c_contiguous() _ppoly.fix_continuity(c.reshape(c.shape[0], c.shape[1], -1), self.x, nu - 1) # construct a compatible polynomial return self.construct_fast(c, self.x, self.extrapolate, self.axis) def integrate(self, a, b, extrapolate=None): """ Compute a definite integral over a piecewise polynomial. Parameters ---------- a : float Lower integration bound b : float Upper integration bound extrapolate : bool, optional Whether to extrapolate to ouf-of-bounds points based on first and last intervals, or to return NaNs. Returns ------- ig : array_like Definite integral of the piecewise polynomial over [a, b] """ if extrapolate is None: extrapolate = self.extrapolate # Swap integration bounds if needed sign = 1 if b < a: a, b = b, a sign = -1 # Compute the integral range_int = np.empty((prod(self.c.shape[2:]),), dtype=self.c.dtype) self._ensure_c_contiguous() _ppoly.integrate(self.c.reshape(self.c.shape[0], self.c.shape[1], -1), self.x, a, b, bool(extrapolate), out=range_int) # Return range_int *= sign return range_int.reshape(self.c.shape[2:]) def roots(self, discontinuity=True, extrapolate=None): """ Find real roots of the piecewise polynomial. Parameters ---------- discontinuity : bool, optional Whether to report sign changes across discontinuities at breakpoints as roots. extrapolate : bool, optional Whether to return roots from the polynomial extrapolated based on first and last intervals. Returns ------- roots : ndarray Roots of the polynomial(s). If the PPoly object describes multiple polynomials, the return value is an object array whose each element is an ndarray containing the roots. Notes ----- This routine works only on real-valued polynomials. If the piecewise polynomial contains sections that are identically zero, the root list will contain the start point of the corresponding interval, followed by a ``nan`` value. If the polynomial is discontinuous across a breakpoint, and there is a sign change across the breakpoint, this is reported if the `discont` parameter is True. Examples -------- Finding roots of ``[x**2 - 1, (x - 1)**2]`` defined on intervals ``[-2, 1], [1, 2]``: >>> from scipy.interpolate import PPoly >>> pp = PPoly(np.array([[1, 0, -1], [1, 0, 0]]).T, [-2, 1, 2]) >>> pp.roots() array([-1., 1.]) """ if extrapolate is None: extrapolate = self.extrapolate self._ensure_c_contiguous() if np.issubdtype(self.c.dtype, np.complexfloating): raise ValueError("Root finding is only for " "real-valued polynomials") r = _ppoly.real_roots(self.c.reshape(self.c.shape[0], self.c.shape[1], -1), self.x, bool(discontinuity), bool(extrapolate)) if self.c.ndim == 2: return r[0] else: r2 = np.empty(prod(self.c.shape[2:]), dtype=object) # this for-loop is equivalent to ``r2[...] = r``, but that's broken # in numpy 1.6.0 for ii, root in enumerate(r): r2[ii] = root return r2.reshape(self.c.shape[2:]) @classmethod def from_spline(cls, tck, extrapolate=None): """ Construct a piecewise polynomial from a spline Parameters ---------- tck A spline, as returned by `splrep` extrapolate : bool, optional Whether to extrapolate to ouf-of-bounds points based on first and last intervals, or to return NaNs. Default: True. """ t, c, k = tck cvals = np.empty((k + 1, len(t)-1), dtype=c.dtype) for m in xrange(k, -1, -1): y = fitpack.splev(t[:-1], tck, der=m) cvals[k - m, :] = y/spec.gamma(m+1) return cls.construct_fast(cvals, t, extrapolate) @classmethod def from_bernstein_basis(cls, bp, extrapolate=None): """ Construct a piecewise polynomial in the power basis from a polynomial in Bernstein basis. Parameters ---------- bp : BPoly A Bernstein basis polynomial, as created by BPoly extrapolate : bool, optional Whether to extrapolate to ouf-of-bounds points based on first and last intervals, or to return NaNs. Default: True. """ dx = np.diff(bp.x) k = bp.c.shape[0] - 1 # polynomial order rest = (None,)*(bp.c.ndim-2) c = np.zeros_like(bp.c) for a in range(k+1): factor = (-1)**(a) * comb(k, a) * bp.c[a] for s in range(a, k+1): val = comb(k-a, s-a) * (-1)**s c[k-s] += factor * val / dx[(slice(None),)+rest]**s if extrapolate is None: extrapolate = bp.extrapolate return cls.construct_fast(c, bp.x, extrapolate, bp.axis) class BPoly(_PPolyBase): """ Piecewise polynomial in terms of coefficients and breakpoints The polynomial in the ``i``-th interval ``x[i] <= xp < x[i+1]`` is written in the Bernstein polynomial basis:: S = sum(c[a, i] * b(a, k; x) for a in range(k+1)) where ``k`` is the degree of the polynomial, and:: b(a, k; x) = comb(k, a) * t**k * (1 - t)**(k - a) with ``t = (x - x[i]) / (x[i+1] - x[i])``. Parameters ---------- c : ndarray, shape (k, m, ...) Polynomial coefficients, order `k` and `m` intervals x : ndarray, shape (m+1,) Polynomial breakpoints. These must be sorted in increasing order. extrapolate : bool, optional Whether to extrapolate to ouf-of-bounds points based on first and last intervals, or to return NaNs. Default: True. axis : int, optional Interpolation axis. Default is zero. Attributes ---------- x : ndarray Breakpoints. c : ndarray Coefficients of the polynomials. They are reshaped to a 3-dimensional array with the last dimension representing the trailing dimensions of the original coefficient array. axis : int Interpolation axis. Methods ------- __call__ extend derivative antiderivative integrate construct_fast from_power_basis from_derivatives See also -------- PPoly : piecewise polynomials in the power basis Notes ----- Properties of Bernstein polynomials are well documented in the literature. Here's a non-exhaustive list: .. [1] http://en.wikipedia.org/wiki/Bernstein_polynomial .. [2] Kenneth I. Joy, Bernstein polynomials, http://www.idav.ucdavis.edu/education/CAGDNotes/Bernstein-Polynomials.pdf .. [3] E. H. Doha, A. H. Bhrawy, and M. A. Saker, Boundary Value Problems, vol 2011, article ID 829546, doi:10.1155/2011/829543 Examples -------- >>> x = [0, 1] >>> c = [[1], [2], [3]] >>> bp = BPoly(c, x) This creates a 2nd order polynomial .. math:: B(x) = 1 \\times b_{0, 2}(x) + 2 \\times b_{1, 2}(x) + 3 \\times b_{2, 2}(x) \\\\ = 1 \\times (1-x)^2 + 2 \\times 2 x (1 - x) + 3 \\times x^2 """ def _evaluate(self, x, nu, extrapolate, out): _ppoly.evaluate_bernstein( self.c.reshape(self.c.shape[0], self.c.shape[1], -1), self.x, x, nu, bool(extrapolate), out) def derivative(self, nu=1): """ Construct a new piecewise polynomial representing the derivative. Parameters ---------- nu : int, optional Order of derivative to evaluate. (Default: 1) If negative, the antiderivative is returned. Returns ------- bp : BPoly Piecewise polynomial of order k2 = k - nu representing the derivative of this polynomial. """ if nu < 0: return self.antiderivative(-nu) if nu > 1: bp = self for k in range(nu): bp = bp.derivative() return bp # reduce order if nu == 0: c2 = self.c.copy() else: # For a polynomial # B(x) = \sum_{a=0}^{k} c_a b_{a, k}(x), # we use the fact that # b'_{a, k} = k ( b_{a-1, k-1} - b_{a, k-1} ), # which leads to # B'(x) = \sum_{a=0}^{k-1} (c_{a+1} - c_a) b_{a, k-1} # # finally, for an interval [y, y + dy] with dy != 1, # we need to correct for an extra power of dy rest = (None,)*(self.c.ndim-2) k = self.c.shape[0] - 1 dx = np.diff(self.x)[(None, slice(None))+rest] c2 = k * np.diff(self.c, axis=0) / dx if c2.shape[0] == 0: # derivative of order 0 is zero c2 = np.zeros((1,) + c2.shape[1:], dtype=c2.dtype) # construct a compatible polynomial return self.construct_fast(c2, self.x, self.extrapolate, self.axis) def antiderivative(self, nu=1): """ Construct a new piecewise polynomial representing the antiderivative. Parameters ---------- nu : int, optional Order of derivative to evaluate. (Default: 1) If negative, the derivative is returned. Returns ------- bp : BPoly Piecewise polynomial of order k2 = k + nu representing the antiderivative of this polynomial. """ if nu <= 0: return self.derivative(-nu) if nu > 1: bp = self for k in range(nu): bp = bp.antiderivative() return bp # Construct the indefinite integrals on individual intervals c, x = self.c, self.x k = c.shape[0] c2 = np.zeros((k+1,) + c.shape[1:], dtype=c.dtype) c2[1:, ...] = np.cumsum(c, axis=0) / k delta = x[1:] - x[:-1] c2 *= delta[(None, slice(None)) + (None,)*(c.ndim-2)] # Now fix continuity: on the very first interval, take the integration # constant to be zero; on an interval [x_j, x_{j+1}) with j>0, # the integration constant is then equal to the jump of the `bp` at x_j. # The latter is given by the coefficient of B_{n+1, n+1} # *on the previous interval* (other B. polynomials are zero at the breakpoint) # Finally, use the fact that BPs form a partition of unity. c2[:,1:] += np.cumsum(c2[k,:], axis=0)[:-1] return self.construct_fast(c2, x, self.extrapolate, axis=self.axis) def integrate(self, a, b, extrapolate=None): """ Compute a definite integral over a piecewise polynomial. Parameters ---------- a : float Lower integration bound b : float Upper integration bound extrapolate : bool, optional Whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. Defaults to ``self.extrapolate``. Returns ------- array_like Definite integral of the piecewise polynomial over [a, b] """ # XXX: can probably use instead the fact that # \int_0^{1} B_{j, n}(x) \dx = 1/(n+1) ib = self.antiderivative() if extrapolate is not None: ib.extrapolate = extrapolate return ib(b) - ib(a) def extend(self, c, x, right=True): k = max(self.c.shape[0], c.shape[0]) self.c = self._raise_degree(self.c, k - self.c.shape[0]) c = self._raise_degree(c, k - c.shape[0]) return _PPolyBase.extend(self, c, x, right) extend.__doc__ = _PPolyBase.extend.__doc__ @classmethod def from_power_basis(cls, pp, extrapolate=None): """ Construct a piecewise polynomial in Bernstein basis from a power basis polynomial. Parameters ---------- pp : PPoly A piecewise polynomial in the power basis extrapolate : bool, optional Whether to extrapolate to ouf-of-bounds points based on first and last intervals, or to return NaNs. Default: True. """ dx = np.diff(pp.x) k = pp.c.shape[0] - 1 # polynomial order rest = (None,)*(pp.c.ndim-2) c = np.zeros_like(pp.c) for a in range(k+1): factor = pp.c[a] / comb(k, k-a) * dx[(slice(None),)+rest]**(k-a) for j in range(k-a, k+1): c[j] += factor * comb(j, k-a) if extrapolate is None: extrapolate = pp.extrapolate return cls.construct_fast(c, pp.x, extrapolate, pp.axis) @classmethod def from_derivatives(cls, xi, yi, orders=None, extrapolate=None): """Construct a piecewise polynomial in the Bernstein basis, compatible with the specified values and derivatives at breakpoints. Parameters ---------- xi : array_like sorted 1D array of x-coordinates yi : array_like or list of array_likes ``yi[i][j]`` is the ``j``-th derivative known at ``xi[i]`` orders : None or int or array_like of ints. Default: None. Specifies the degree of local polynomials. If not None, some derivatives are ignored. extrapolate : bool, optional Whether to extrapolate to ouf-of-bounds points based on first and last intervals, or to return NaNs. Default: True. Notes ----- If ``k`` derivatives are specified at a breakpoint ``x``, the constructed polynomial is exactly ``k`` times continuously differentiable at ``x``, unless the ``order`` is provided explicitly. In the latter case, the smoothness of the polynomial at the breakpoint is controlled by the ``order``. Deduces the number of derivatives to match at each end from ``order`` and the number of derivatives available. If possible it uses the same number of derivatives from each end; if the number is odd it tries to take the extra one from y2. In any case if not enough derivatives are available at one end or another it draws enough to make up the total from the other end. If the order is too high and not enough derivatives are available, an exception is raised. Examples -------- >>> BPoly.from_derivatives([0, 1], [[1, 2], [3, 4]]) Creates a polynomial `f(x)` of degree 3, defined on `[0, 1]` such that `f(0) = 1, df/dx(0) = 2, f(1) = 3, df/dx(1) = 4` >>> BPoly.from_derivatives([0, 1, 2], [[0, 1], [0], [2]]) Creates a piecewise polynomial `f(x)`, such that `f(0) = f(1) = 0`, `f(2) = 2`, and `df/dx(0) = 1`. Based on the number of derivatives provided, the order of the local polynomials is 2 on `[0, 1]` and 1 on `[1, 2]`. Notice that no restriction is imposed on the derivatives at `x = 1` and `x = 2`. Indeed, the explicit form of the polynomial is:: f(x) = | x * (1 - x), 0 <= x < 1 | 2 * (x - 1), 1 <= x <= 2 So that f'(1-0) = -1 and f'(1+0) = 2 """ xi = np.asarray(xi) if len(xi) != len(yi): raise ValueError("xi and yi need to have the same length") if np.any(xi[1:] - xi[:1] <= 0): raise ValueError("x coordinates are not in increasing order") # number of intervals m = len(xi) - 1 # global poly order is k-1, local orders are <=k and can vary try: k = max(len(yi[i]) + len(yi[i+1]) for i in range(m)) except TypeError: raise ValueError("Using a 1D array for y? Please .reshape(-1, 1).") if orders is None: orders = [None] * m else: if isinstance(orders, integer_types): orders = [orders] * m k = max(k, max(orders)) if any(o <= 0 for o in orders): raise ValueError("Orders must be positive.") c = [] for i in range(m): y1, y2 = yi[i], yi[i+1] if orders[i] is None: n1, n2 = len(y1), len(y2) else: n = orders[i]+1 n1 = min(n//2, len(y1)) n2 = min(n - n1, len(y2)) n1 = min(n - n2, len(y2)) if n1+n2 != n: raise ValueError("Point %g has %d derivatives, point %g" " has %d derivatives, but order %d requested" % (xi[i], len(y1), xi[i+1], len(y2), orders[i])) if not (n1 <= len(y1) and n2 <= len(y2)): raise ValueError("`order` input incompatible with" " length y1 or y2.") b = BPoly._construct_from_derivatives(xi[i], xi[i+1], y1[:n1], y2[:n2]) if len(b) < k: b = BPoly._raise_degree(b, k - len(b)) c.append(b) c = np.asarray(c) return cls(c.swapaxes(0, 1), xi, extrapolate) @staticmethod def _construct_from_derivatives(xa, xb, ya, yb): """Compute the coefficients of a polynomial in the Bernstein basis given the values and derivatives at the edges. Return the coefficients of a polynomial in the Bernstein basis defined on `[xa, xb]` and having the values and derivatives at the endpoints ``xa`` and ``xb`` as specified by ``ya`` and ``yb``. The polynomial constructed is of the minimal possible degree, i.e., if the lengths of ``ya`` and ``yb`` are ``na`` and ``nb``, the degree of the polynomial is ``na + nb - 1``. Parameters ---------- xa : float Left-hand end point of the interval xb : float Right-hand end point of the interval ya : array_like Derivatives at ``xa``. ``ya[0]`` is the value of the function, and ``ya[i]`` for ``i > 0`` is the value of the ``i``-th derivative. yb : array_like Derivatives at ``xb``. Returns ------- array coefficient array of a polynomial having specified derivatives Notes ----- This uses several facts from life of Bernstein basis functions. First of all, .. math:: b'_{a, n} = n (b_{a-1, n-1} - b_{a, n-1}) If B(x) is a linear combination of the form .. math:: B(x) = \sum_{a=0}^{n} c_a b_{a, n}, then :math: B'(x) = n \sum_{a=0}^{n-1} (c_{a+1} - c_{a}) b_{a, n-1}. Iterating the latter one, one finds for the q-th derivative .. math:: B^{q}(x) = n!/(n-q)! \sum_{a=0}^{n-q} Q_a b_{a, n-q}, with .. math:: Q_a = \sum_{j=0}^{q} (-)^{j+q} comb(q, j) c_{j+a} This way, only `a=0` contributes to :math: `B^{q}(x = xa)`, and `c_q` are found one by one by iterating `q = 0, ..., na`. At `x = xb` it's the same with `a = n - q`. """ ya, yb = np.asarray(ya), np.asarray(yb) if ya.shape[1:] != yb.shape[1:]: raise ValueError('ya and yb have incompatible dimensions.') dta, dtb = ya.dtype, yb.dtype if (np.issubdtype(dta, np.complexfloating) or np.issubdtype(dtb, np.complexfloating)): dt = np.complex_ else: dt = np.float_ na, nb = len(ya), len(yb) n = na + nb c = np.empty((na+nb,) + ya.shape[1:], dtype=dt) # compute coefficients of a polynomial degree na+nb-1 # walk left-to-right for q in range(0, na): c[q] = ya[q] / spec.poch(n - q, q) * (xb - xa)**q for j in range(0, q): c[q] -= (-1)**(j+q) * comb(q, j) * c[j] # now walk right-to-left for q in range(0, nb): c[-q-1] = yb[q] / spec.poch(n - q, q) * (-1)**q * (xb - xa)**q for j in range(0, q): c[-q-1] -= (-1)**(j+1) * comb(q, j+1) * c[-q+j] return c @staticmethod def _raise_degree(c, d): """Raise a degree of a polynomial in the Bernstein basis. Given the coefficients of a polynomial degree `k`, return (the coefficients of) the equivalent polynomial of degree `k+d`. Parameters ---------- c : array_like coefficient array, 1D d : integer Returns ------- array coefficient array, 1D array of length `c.shape[0] + d` Notes ----- This uses the fact that a Bernstein polynomial `b_{a, k}` can be identically represented as a linear combination of polynomials of a higher degree `k+d`: .. math:: b_{a, k} = comb(k, a) \sum_{j=0}^{d} b_{a+j, k+d} \ comb(d, j) / comb(k+d, a+j) """ if d == 0: return c k = c.shape[0] - 1 out = np.zeros((c.shape[0] + d,) + c.shape[1:], dtype=c.dtype) for a in range(c.shape[0]): f = c[a] * comb(k, a) for j in range(d+1): out[a+j] += f * comb(d, j) / comb(k+d, a+j) return out class RegularGridInterpolator(object): """ Interpolation on a regular grid in arbitrary dimensions The data must be defined on a regular grid; the grid spacing however may be uneven. Linear and nearest-neighbour interpolation are supported. After setting up the interpolator object, the interpolation method (*linear* or *nearest*) may be chosen at each evaluation. Parameters ---------- points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, ) The points defining the regular grid in n dimensions. values : array_like, shape (m1, ..., mn, ...) The data on the regular grid in n dimensions. method : str, optional The method of interpolation to perform. Supported are "linear" and "nearest". This parameter will become the default for the object's ``__call__`` method. Default is "linear". bounds_error : bool, optional If True, when interpolated values are requested outside of the domain of the input data, a ValueError is raised. If False, then `fill_value` is used. fill_value : number, optional If provided, the value to use for points outside of the interpolation domain. If None, values outside the domain are extrapolated. Methods ------- __call__ Notes ----- Contrary to LinearNDInterpolator and NearestNDInterpolator, this class avoids expensive triangulation of the input data by taking advantage of the regular grid structure. .. versionadded:: 0.14 Examples -------- Evaluate a simple example function on the points of a 3D grid: >>> from scipy.interpolate import RegularGridInterpolator >>> def f(x,y,z): ... return 2 * x**3 + 3 * y**2 - z >>> x = np.linspace(1, 4, 11) >>> y = np.linspace(4, 7, 22) >>> z = np.linspace(7, 9, 33) >>> data = f(*np.meshgrid(x, y, z, indexing='ij', sparse=True)) ``data`` is now a 3D array with ``data[i,j,k] = f(x[i], y[j], z[k])``. Next, define an interpolating function from this data: >>> my_interpolating_function = RegularGridInterpolator((x, y, z), data) Evaluate the interpolating function at the two points ``(x,y,z) = (2.1, 6.2, 8.3)`` and ``(3.3, 5.2, 7.1)``: >>> pts = np.array([[2.1, 6.2, 8.3], [3.3, 5.2, 7.1]]) >>> my_interpolating_function(pts) array([ 125.80469388, 146.30069388]) which is indeed a close approximation to ``[f(2.1, 6.2, 8.3), f(3.3, 5.2, 7.1)]``. See also -------- NearestNDInterpolator : Nearest neighbour interpolation on unstructured data in N dimensions LinearNDInterpolator : Piecewise linear interpolant on unstructured data in N dimensions References ---------- .. [1] Python package *regulargrid* by Johannes Buchner, see https://pypi.python.org/pypi/regulargrid/ .. [2] Trilinear interpolation. (2013, January 17). In Wikipedia, The Free Encyclopedia. Retrieved 27 Feb 2013 01:28. http://en.wikipedia.org/w/index.php?title=Trilinear_interpolation&oldid=533448871 .. [3] Weiser, Alan, and Sergio E. Zarantonello. "A note on piecewise linear and multilinear table interpolation in many dimensions." MATH. COMPUT. 50.181 (1988): 189-196. http://www.ams.org/journals/mcom/1988-50-181/S0025-5718-1988-0917826-0/S0025-5718-1988-0917826-0.pdf """ # this class is based on code originally programmed by Johannes Buchner, # see https://github.com/JohannesBuchner/regulargrid def __init__(self, points, values, method="linear", bounds_error=True, fill_value=np.nan): if method not in ["linear", "nearest"]: raise ValueError("Method '%s' is not defined" % method) self.method = method self.bounds_error = bounds_error if not hasattr(values, 'ndim'): # allow reasonable duck-typed values values = np.asarray(values) if len(points) > values.ndim: raise ValueError("There are %d point arrays, but values has %d " "dimensions" % (len(points), values.ndim)) if hasattr(values, 'dtype') and hasattr(values, 'astype'): if not np.issubdtype(values.dtype, np.inexact): values = values.astype(float) self.fill_value = fill_value if fill_value is not None: fill_value_dtype = np.asarray(fill_value).dtype if (hasattr(values, 'dtype') and not np.can_cast(fill_value_dtype, values.dtype, casting='same_kind')): raise ValueError("fill_value must be either 'None' or " "of a type compatible with values") for i, p in enumerate(points): if not np.all(np.diff(p) > 0.): raise ValueError("The points in dimension %d must be strictly " "ascending" % i) if not np.asarray(p).ndim == 1: raise ValueError("The points in dimension %d must be " "1-dimensional" % i) if not values.shape[i] == len(p): raise ValueError("There are %d points and %d values in " "dimension %d" % (len(p), values.shape[i], i)) self.grid = tuple([np.asarray(p) for p in points]) self.values = values def __call__(self, xi, method=None): """ Interpolation at coordinates Parameters ---------- xi : ndarray of shape (..., ndim) The coordinates to sample the gridded data at method : str The method of interpolation to perform. Supported are "linear" and "nearest". """ method = self.method if method is None else method if method not in ["linear", "nearest"]: raise ValueError("Method '%s' is not defined" % method) ndim = len(self.grid) xi = _ndim_coords_from_arrays(xi, ndim=ndim) if xi.shape[-1] != len(self.grid): raise ValueError("The requested sample points xi have dimension " "%d, but this RegularGridInterpolator has " "dimension %d" % (xi.shape[1], ndim)) xi_shape = xi.shape xi = xi.reshape(-1, xi_shape[-1]) if self.bounds_error: for i, p in enumerate(xi.T): if not np.logical_and(np.all(self.grid[i][0] <= p), np.all(p <= self.grid[i][-1])): raise ValueError("One of the requested xi is out of bounds " "in dimension %d" % i) indices, norm_distances, out_of_bounds = self._find_indices(xi.T) if method == "linear": result = self._evaluate_linear(indices, norm_distances, out_of_bounds) elif method == "nearest": result = self._evaluate_nearest(indices, norm_distances, out_of_bounds) if not self.bounds_error and self.fill_value is not None: result[out_of_bounds] = self.fill_value return result.reshape(xi_shape[:-1] + self.values.shape[ndim:]) def _evaluate_linear(self, indices, norm_distances, out_of_bounds): # slice for broadcasting over trailing dimensions in self.values vslice = (slice(None),) + (None,)*(self.values.ndim - len(indices)) # find relevant values # each i and i+1 represents a edge edges = itertools.product(*[[i, i + 1] for i in indices]) values = 0. for edge_indices in edges: weight = 1. for ei, i, yi in zip(edge_indices, indices, norm_distances): weight *= np.where(ei == i, 1 - yi, yi) values += np.asarray(self.values[edge_indices]) * weight[vslice] return values def _evaluate_nearest(self, indices, norm_distances, out_of_bounds): idx_res = [] for i, yi in zip(indices, norm_distances): idx_res.append(np.where(yi <= .5, i, i + 1)) return self.values[idx_res] def _find_indices(self, xi): # find relevant edges between which xi are situated indices = [] # compute distance to lower edge in unity units norm_distances = [] # check for out of bounds xi out_of_bounds = np.zeros((xi.shape[1]), dtype=bool) # iterate through dimensions for x, grid in zip(xi, self.grid): i = np.searchsorted(grid, x) - 1 i[i < 0] = 0 i[i > grid.size - 2] = grid.size - 2 indices.append(i) norm_distances.append((x - grid[i]) / (grid[i + 1] - grid[i])) if not self.bounds_error: out_of_bounds += x < grid[0] out_of_bounds += x > grid[-1] return indices, norm_distances, out_of_bounds def interpn(points, values, xi, method="linear", bounds_error=True, fill_value=np.nan): """ Multidimensional interpolation on regular grids. Parameters ---------- points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, ) The points defining the regular grid in n dimensions. values : array_like, shape (m1, ..., mn, ...) The data on the regular grid in n dimensions. xi : ndarray of shape (..., ndim) The coordinates to sample the gridded data at method : str, optional The method of interpolation to perform. Supported are "linear" and "nearest", and "splinef2d". "splinef2d" is only supported for 2-dimensional data. bounds_error : bool, optional If True, when interpolated values are requested outside of the domain of the input data, a ValueError is raised. If False, then `fill_value` is used. fill_value : number, optional If provided, the value to use for points outside of the interpolation domain. If None, values outside the domain are extrapolated. Extrapolation is not supported by method "splinef2d". Returns ------- values_x : ndarray, shape xi.shape[:-1] + values.shape[ndim:] Interpolated values at input coordinates. Notes ----- .. versionadded:: 0.14 See also -------- NearestNDInterpolator : Nearest neighbour interpolation on unstructured data in N dimensions LinearNDInterpolator : Piecewise linear interpolant on unstructured data in N dimensions RegularGridInterpolator : Linear and nearest-neighbor Interpolation on a regular grid in arbitrary dimensions RectBivariateSpline : Bivariate spline approximation over a rectangular mesh """ # sanity check 'method' kwarg if method not in ["linear", "nearest", "splinef2d"]: raise ValueError("interpn only understands the methods 'linear', " "'nearest', and 'splinef2d'. You provided %s." % method) if not hasattr(values, 'ndim'): values = np.asarray(values) ndim = values.ndim if ndim > 2 and method == "splinef2d": raise ValueError("The method spline2fd can only be used for " "2-dimensional input data") if not bounds_error and fill_value is None and method == "splinef2d": raise ValueError("The method spline2fd does not support extrapolation.") # sanity check consistency of input dimensions if len(points) > ndim: raise ValueError("There are %d point arrays, but values has %d " "dimensions" % (len(points), ndim)) if len(points) != ndim and method == 'splinef2d': raise ValueError("The method spline2fd can only be used for " "scalar data with one point per coordinate") # sanity check input grid for i, p in enumerate(points): if not np.all(np.diff(p) > 0.): raise ValueError("The points in dimension %d must be strictly " "ascending" % i) if not np.asarray(p).ndim == 1: raise ValueError("The points in dimension %d must be " "1-dimensional" % i) if not values.shape[i] == len(p): raise ValueError("There are %d points and %d values in " "dimension %d" % (len(p), values.shape[i], i)) grid = tuple([np.asarray(p) for p in points]) # sanity check requested xi xi = _ndim_coords_from_arrays(xi, ndim=len(grid)) if xi.shape[-1] != len(grid): raise ValueError("The requested sample points xi have dimension " "%d, but this RegularGridInterpolator has " "dimension %d" % (xi.shape[1], len(grid))) for i, p in enumerate(xi.T): if bounds_error and not np.logical_and(np.all(grid[i][0] <= p), np.all(p <= grid[i][-1])): raise ValueError("One of the requested xi is out of bounds " "in dimension %d" % i) # perform interpolation if method == "linear": interp = RegularGridInterpolator(points, values, method="linear", bounds_error=bounds_error, fill_value=fill_value) return interp(xi) elif method == "nearest": interp = RegularGridInterpolator(points, values, method="nearest", bounds_error=bounds_error, fill_value=fill_value) return interp(xi) elif method == "splinef2d": xi_shape = xi.shape xi = xi.reshape(-1, xi.shape[-1]) # RectBivariateSpline doesn't support fill_value; we need to wrap here idx_valid = np.all((grid[0][0] <= xi[:, 0], xi[:, 0] <= grid[0][-1], grid[1][0] <= xi[:, 1], xi[:, 1] <= grid[1][-1]), axis=0) result = np.empty_like(xi[:, 0]) # make a copy of values for RectBivariateSpline interp = RectBivariateSpline(points[0], points[1], values[:]) result[idx_valid] = interp.ev(xi[idx_valid, 0], xi[idx_valid, 1]) result[np.logical_not(idx_valid)] = fill_value return result.reshape(xi_shape[:-1]) # backward compatibility wrapper class ppform(PPoly): """ Deprecated piecewise polynomial class. New code should use the `PPoly` class instead. """ def __init__(self, coeffs, breaks, fill=0.0, sort=False): warnings.warn("ppform is deprecated -- use PPoly instead", category=DeprecationWarning) if sort: breaks = np.sort(breaks) else: breaks = np.asarray(breaks) PPoly.__init__(self, coeffs, breaks) self.coeffs = self.c self.breaks = self.x self.K = self.coeffs.shape[0] self.fill = fill self.a = self.breaks[0] self.b = self.breaks[-1] def __call__(self, x): return PPoly.__call__(self, x, 0, False) def _evaluate(self, x, nu, extrapolate, out): PPoly._evaluate(self, x, nu, extrapolate, out) out[~((x >= self.a) & (x <= self.b))] = self.fill return out @classmethod def fromspline(cls, xk, cvals, order, fill=0.0): # Note: this spline representation is incompatible with FITPACK N = len(xk)-1 sivals = np.empty((order+1, N), dtype=float) for m in xrange(order, -1, -1): fact = spec.gamma(m+1) res = _fitpack._bspleval(xk[:-1], xk, cvals, order, m) res /= fact sivals[order-m, :] = res return cls(sivals, xk, fill=fill) def _dot0(a, b): """Similar to numpy.dot, but sum over last axis of a and 1st axis of b""" if b.ndim <= 2: return dot(a, b) else: axes = list(range(b.ndim)) axes.insert(-1, 0) axes.pop(0) return dot(a, b.transpose(axes)) def _find_smoothest(xk, yk, order, conds=None, B=None): # construct Bmatrix, and Jmatrix # e = J*c # minimize norm(e,2) given B*c=yk # if desired B can be given # conds is ignored N = len(xk)-1 K = order if B is None: B = _fitpack._bsplmat(order, xk) J = _fitpack._bspldismat(order, xk) u, s, vh = scipy.linalg.svd(B) ind = K-1 V2 = vh[-ind:,:].T V1 = vh[:-ind,:].T A = dot(J.T,J) tmp = dot(V2.T,A) Q = dot(tmp,V2) p = scipy.linalg.solve(Q, tmp) tmp = dot(V2,p) tmp = np.eye(N+K) - tmp tmp = dot(tmp,V1) tmp = dot(tmp,np.diag(1.0/s)) tmp = dot(tmp,u.T) return _dot0(tmp, yk) def _setdiag(a, k, v): if not a.ndim == 2: raise ValueError("Input array should be 2-D.") M,N = a.shape if k > 0: start = k num = N - k else: num = M + k start = abs(k)*N end = start + num*(N+1)-1 a.flat[start:end:(N+1)] = v # Return the spline that minimizes the dis-continuity of the # "order-th" derivative; for order >= 2. def _find_smoothest2(xk, yk): N = len(xk) - 1 Np1 = N + 1 # find pseudo-inverse of B directly. Bd = np.empty((Np1, N)) for k in range(-N,N): if (k < 0): l = np.arange(-k, Np1) v = (l+k+1) if ((k+1) % 2): v = -v else: l = np.arange(k,N) v = N - l if ((k % 2)): v = -v _setdiag(Bd, k, v) Bd /= (Np1) V2 = np.ones((Np1,)) V2[1::2] = -1 V2 /= math.sqrt(Np1) dk = np.diff(xk) b = 2*np.diff(yk, axis=0)/dk J = np.zeros((N-1,N+1)) idk = 1.0/dk _setdiag(J,0,idk[:-1]) _setdiag(J,1,-idk[1:]-idk[:-1]) _setdiag(J,2,idk[1:]) A = dot(J.T,J) val = dot(V2,dot(A,V2)) res1 = dot(np.outer(V2,V2)/val,A) mk = dot(np.eye(Np1)-res1, _dot0(Bd,b)) return mk def _get_spline2_Bb(xk, yk, kind, conds): Np1 = len(xk) dk = xk[1:]-xk[:-1] if kind == 'not-a-knot': # use banded-solver nlu = (1,1) B = ones((3,Np1)) alpha = 2*(yk[1:]-yk[:-1])/dk zrs = np.zeros((1,)+yk.shape[1:]) row = (Np1-1)//2 b = np.concatenate((alpha[:row],zrs,alpha[row:]),axis=0) B[0,row+2:] = 0 B[2,:(row-1)] = 0 B[0,row+1] = dk[row-1] B[1,row] = -dk[row]-dk[row-1] B[2,row-1] = dk[row] return B, b, None, nlu else: raise NotImplementedError("quadratic %s is not available" % kind) def _get_spline3_Bb(xk, yk, kind, conds): # internal function to compute different tri-diagonal system # depending on the kind of spline requested. # conds is only used for 'second' and 'first' Np1 = len(xk) if kind in ['natural', 'second']: if kind == 'natural': m0, mN = 0.0, 0.0 else: m0, mN = conds # the matrix to invert is (N-1,N-1) # use banded solver beta = 2*(xk[2:]-xk[:-2]) alpha = xk[1:]-xk[:-1] nlu = (1,1) B = np.empty((3,Np1-2)) B[0,1:] = alpha[2:] B[1,:] = beta B[2,:-1] = alpha[1:-1] dyk = yk[1:]-yk[:-1] b = (dyk[1:]/alpha[1:] - dyk[:-1]/alpha[:-1]) b *= 6 b[0] -= m0 b[-1] -= mN def append_func(mk): # put m0 and mN into the correct shape for # concatenation ma = array(m0,copy=0,ndmin=yk.ndim) mb = array(mN,copy=0,ndmin=yk.ndim) if ma.shape[1:] != yk.shape[1:]: ma = ma*(ones(yk.shape[1:])[np.newaxis,...]) if mb.shape[1:] != yk.shape[1:]: mb = mb*(ones(yk.shape[1:])[np.newaxis,...]) mk = np.concatenate((ma,mk),axis=0) mk = np.concatenate((mk,mb),axis=0) return mk return B, b, append_func, nlu elif kind in ['clamped', 'endslope', 'first', 'not-a-knot', 'runout', 'parabolic']: if kind == 'endslope': # match slope of lagrange interpolating polynomial of # order 3 at end-points. x0,x1,x2,x3 = xk[:4] sl_0 = (1./(x0-x1)+1./(x0-x2)+1./(x0-x3))*yk[0] sl_0 += (x0-x2)*(x0-x3)/((x1-x0)*(x1-x2)*(x1-x3))*yk[1] sl_0 += (x0-x1)*(x0-x3)/((x2-x0)*(x2-x1)*(x3-x2))*yk[2] sl_0 += (x0-x1)*(x0-x2)/((x3-x0)*(x3-x1)*(x3-x2))*yk[3] xN3,xN2,xN1,xN0 = xk[-4:] sl_N = (1./(xN0-xN1)+1./(xN0-xN2)+1./(xN0-xN3))*yk[-1] sl_N += (xN0-xN2)*(xN0-xN3)/((xN1-xN0)*(xN1-xN2)*(xN1-xN3))*yk[-2] sl_N += (xN0-xN1)*(xN0-xN3)/((xN2-xN0)*(xN2-xN1)*(xN3-xN2))*yk[-3] sl_N += (xN0-xN1)*(xN0-xN2)/((xN3-xN0)*(xN3-xN1)*(xN3-xN2))*yk[-4] elif kind == 'clamped': sl_0, sl_N = 0.0, 0.0 elif kind == 'first': sl_0, sl_N = conds # Now set up the (N+1)x(N+1) system of equations beta = np.r_[0,2*(xk[2:]-xk[:-2]),0] alpha = xk[1:]-xk[:-1] gamma = np.r_[0,alpha[1:]] B = np.diag(alpha,k=-1) + np.diag(beta) + np.diag(gamma,k=1) d1 = alpha[0] dN = alpha[-1] if kind == 'not-a-knot': d2 = alpha[1] dN1 = alpha[-2] B[0,:3] = [d2,-d1-d2,d1] B[-1,-3:] = [dN,-dN1-dN,dN1] elif kind == 'runout': B[0,:3] = [1,-2,1] B[-1,-3:] = [1,-2,1] elif kind == 'parabolic': B[0,:2] = [1,-1] B[-1,-2:] = [-1,1] elif kind == 'periodic': raise NotImplementedError elif kind == 'symmetric': raise NotImplementedError else: B[0,:2] = [2*d1,d1] B[-1,-2:] = [dN,2*dN] # Set up RHS (b) b = np.empty((Np1,)+yk.shape[1:]) dyk = (yk[1:]-yk[:-1])*1.0 if kind in ['not-a-knot', 'runout', 'parabolic']: b[0] = b[-1] = 0.0 elif kind == 'periodic': raise NotImplementedError elif kind == 'symmetric': raise NotImplementedError else: b[0] = (dyk[0]/d1 - sl_0) b[-1] = -(dyk[-1]/dN - sl_N) b[1:-1,...] = (dyk[1:]/alpha[1:]-dyk[:-1]/alpha[:-1]) b *= 6.0 return B, b, None, None else: raise ValueError("%s not supported" % kind) # conds is a tuple of an array and a vector # giving the left-hand and the right-hand side # of the additional equations to add to B def _find_user(xk, yk, order, conds, B): lh = conds[0] rh = conds[1] B = np.concatenate((B, lh), axis=0) w = np.concatenate((yk, rh), axis=0) M, N = B.shape if (M > N): raise ValueError("over-specification of conditions") elif (M < N): return _find_smoothest(xk, yk, order, None, B) else: return scipy.linalg.solve(B, w) # If conds is None, then use the not_a_knot condition # at K-1 farthest separated points in the interval def _find_not_a_knot(xk, yk, order, conds, B): raise NotImplementedError return _find_user(xk, yk, order, conds, B) # If conds is None, then ensure zero-valued second # derivative at K-1 farthest separated points def _find_natural(xk, yk, order, conds, B): raise NotImplementedError return _find_user(xk, yk, order, conds, B) # If conds is None, then ensure zero-valued first # derivative at K-1 farthest separated points def _find_clamped(xk, yk, order, conds, B): raise NotImplementedError return _find_user(xk, yk, order, conds, B) def _find_fixed(xk, yk, order, conds, B): raise NotImplementedError return _find_user(xk, yk, order, conds, B) # If conds is None, then use coefficient periodicity # If conds is 'function' then use function periodicity def _find_periodic(xk, yk, order, conds, B): raise NotImplementedError return _find_user(xk, yk, order, conds, B) # Doesn't use conds def _find_symmetric(xk, yk, order, conds, B): raise NotImplementedError return _find_user(xk, yk, order, conds, B) # conds is a dictionary with multiple values def _find_mixed(xk, yk, order, conds, B): raise NotImplementedError return _find_user(xk, yk, order, conds, B) def splmake(xk, yk, order=3, kind='smoothest', conds=None): """ Return a representation of a spline given data-points at internal knots Parameters ---------- xk : array_like The input array of x values of rank 1 yk : array_like The input array of y values of rank N. `yk` can be an N-d array to represent more than one curve, through the same `xk` points. The first dimension is assumed to be the interpolating dimension and is the same length of `xk`. order : int, optional Order of the spline kind : str, optional Can be 'smoothest', 'not_a_knot', 'fixed', 'clamped', 'natural', 'periodic', 'symmetric', 'user', 'mixed' and it is ignored if order < 2 conds : optional Conds Returns ------- splmake : tuple Return a (`xk`, `cvals`, `k`) representation of a spline given data-points where the (internal) knots are at the data-points. """ yk = np.asanyarray(yk) order = int(order) if order < 0: raise ValueError("order must not be negative") if order == 0: return xk, yk[:-1], order elif order == 1: return xk, yk, order try: func = eval('_find_%s' % kind) except: raise NotImplementedError # the constraint matrix B = _fitpack._bsplmat(order, xk) coefs = func(xk, yk, order, conds, B) return xk, coefs, order def spleval(xck, xnew, deriv=0): """ Evaluate a fixed spline represented by the given tuple at the new x-values The `xj` values are the interior knot points. The approximation region is `xj[0]` to `xj[-1]`. If N+1 is the length of `xj`, then `cvals` should have length N+k where `k` is the order of the spline. Parameters ---------- (xj, cvals, k) : tuple Parameters that define the fixed spline xj : array_like Interior knot points cvals : array_like Curvature k : int Order of the spline xnew : array_like Locations to calculate spline deriv : int Deriv Returns ------- spleval : ndarray If `cvals` represents more than one curve (`cvals.ndim` > 1) and/or `xnew` is N-d, then the result is `xnew.shape` + `cvals.shape[1:]` providing the interpolation of multiple curves. Notes ----- Internally, an additional `k`-1 knot points are added on either side of the spline. """ (xj,cvals,k) = xck oldshape = np.shape(xnew) xx = np.ravel(xnew) sh = cvals.shape[1:] res = np.empty(xx.shape + sh, dtype=cvals.dtype) for index in np.ndindex(*sh): sl = (slice(None),)+index if issubclass(cvals.dtype.type, np.complexfloating): res[sl].real = _fitpack._bspleval(xx,xj,cvals.real[sl],k,deriv) res[sl].imag = _fitpack._bspleval(xx,xj,cvals.imag[sl],k,deriv) else: res[sl] = _fitpack._bspleval(xx,xj,cvals[sl],k,deriv) res.shape = oldshape + sh return res def spltopp(xk, cvals, k): """Return a piece-wise polynomial object from a fixed-spline tuple. """ return ppform.fromspline(xk, cvals, k) def spline(xk, yk, xnew, order=3, kind='smoothest', conds=None): """ Interpolate a curve at new points using a spline fit Parameters ---------- xk, yk : array_like The x and y values that define the curve. xnew : array_like The x values where spline should estimate the y values. order : int Default is 3. kind : string One of {'smoothest'} conds : Don't know Don't know Returns ------- spline : ndarray An array of y values; the spline evaluated at the positions `xnew`. """ return spleval(splmake(xk,yk,order=order,kind=kind,conds=conds),xnew)
mit
silbertmonaphia/ml
run.py
1
4732
#! /usr/bin/env python # encoding:utf-8 import numpy as np import random from scipy.io import arff from sklearn.cross_validation import StratifiedKFold # balanced better! from sklearn.cross_validation import train_test_split # not balanced from sklearn import metrics from sklearn.svm import SVC from sklearn.naive_bayes import MultinomialNB from sklearn.tree import DecisionTreeClassifier from selflearning import SelfLearningModel from cotraining import CoTrainingClassifier import matplotlib.pyplot as plt def loadData(filepath): # feature[[],[]] X = [] # tag['pos','neg'] y = [] # load arff file with open(filepath, 'rb') as f: data, meta = arff.loadarff(f) for line in data: if line[-1] == 'pos': y.append(1) else: y.append(0) line = list(line) # pop the tag out of line line.pop() X.append(line) X = np.array(X) y = np.array(y) return X, y def cross_validation(X, y): skf1 = StratifiedKFold(y, n_folds=4,shuffle=True) for train_index, test_index in skf1: X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] skf2 = StratifiedKFold(y_train, n_folds=75,shuffle=True) for unlabeled_index, labeled_index in skf2: X_unlabeled, X_labeled = X[unlabeled_index], X[labeled_index] y_unlabeled, y_labeled = y[unlabeled_index], y[labeled_index] break # X_labeled=18 y_labeled=18 X_unlabeled=1332 X_test=450 y_test=450 yield X_labeled, y_labeled, X_unlabeled, X_test, y_test def evaluation(y_test, predict, accuracyonly=True): accuracy = metrics.accuracy_score(y_test, predict) if not accuracyonly: # can print out precision recall and f1 print metrics.classification_report(y_test, predict) return accuracy def test_baseline(X_labeled, y_labeled, X_test, y_test): clf_SVM = SVC(kernel='linear', probability=True) # clf_SVM = MultinomialNB() print '\nstart testing baseline :/' print 'svm' clf_SVM.fit(X_labeled, y_labeled) predict = clf_SVM.predict(X_test) accuracy_bl_svm = evaluation(y_test, predict) return accuracy_bl_svm def test_selftraing(X_labeled, y_labeled, X_unlabeled, X_test, y_test): # SSL-SelfTraining print '\nstart testing SSL-SelfTraining :D' # svm has to turn on probability parameter clf_SVM = SVC(kernel='linear', probability=True) # clf_SVM = MultinomialNB() ssl_slm_svm = SelfLearningModel(clf_SVM) ssl_slm_svm.fit(X_labeled, y_labeled, X_unlabeled) predict = ssl_slm_svm.predict(X_test) accuracy_sf_svm = evaluation(y_test, predict) return accuracy_sf_svm def test_cotraining(X_labeled, y_labeled, X_unlabeled, X_test, y_test): # SSL-Co-Training print '\nstart testing SSL-CoTraining :)' clf_SVM = SVC(kernel='linear', probability=True) # clf_SVM = MultinomialNB() # an object is a class with status,it has memories print 'svm' ssl_ctc_svm = CoTrainingClassifier(clf_SVM) ssl_ctc_svm.fit(X_labeled, y_labeled, X_unlabeled) predict_clf1 = ssl_ctc_svm.predict(X_test) accuracy_co_svm = evaluation(y_test, predict_clf1) return accuracy_co_svm if __name__ == '__main__': # the number of experitments experitments = 4 # the classifiers that we use clfs = ['svm'] # load arff file as X,y ndarray like X, y = loadData('./text/JDMilk.arff') # labeled 1%,unlabeled 74%,test 25% cv_generator = cross_validation(X, y) clf_num = len(clfs) accuracy_bl = np.zeros((0, clf_num)) accuracy_sf = np.zeros((0, clf_num)) accuracy_co = np.zeros((0, clf_num)) # Cross validation for 10 times,and compute the average of accuracy for i in range(experitments): print '=' * 10, str(i), 'time' X_labeled, y_labeled, X_unlabeled, X_test, y_test = cv_generator.next() accuracy_bl = np.vstack((accuracy_bl, np.asarray(test_baseline(X_labeled, y_labeled, X_test, y_test)))) accuracy_sf = np.vstack((accuracy_sf, np.asarray(test_selftraing(X_labeled, y_labeled, X_unlabeled, X_test, y_test)))) accuracy_co = np.vstack((accuracy_co, np.asarray(test_cotraining(X_labeled, y_labeled, X_unlabeled, X_test, y_test)))) print '\n.... final static average ....\n' for i, clf in enumerate(clfs): print clf print 'baseline: ', sum(accuracy_bl[:, i]) / float(len(accuracy_bl[:, i])) print 'selftraining: ', sum(accuracy_sf[:, i]) / float(len(accuracy_sf[:, i])) print 'cotraining:', sum(accuracy_co[:, i]) / float(len(accuracy_co[:, i]))
gpl-3.0
weka511/astro
jacobi3d.py
1
1442
# Copyright (C) 2016 Greenweaves Software Pty Ltd # This is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This software 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 software. If not, see <http://www.gnu.org/licenses/> from mpl_toolkits.mplot3d import Axes3D import numpy as np, matplotlib.pyplot as plt, math as m, jacobi,matplotlib.colors as clrs def plot_3d(limit=2,eps=0.001,minZ=-3.9,maxZ=-2.84,steps=1000): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') xlist = np.linspace(-limit, limit+eps, steps) ylist = np.linspace(-limit, limit+eps, steps) X,Y = np.meshgrid(xlist, ylist) Z = -jacobi.jacobi(X,Y) Z[Z<minZ]= np.nan Z[Z>maxZ]= np.nan norm = clrs.Normalize(vmin = minZ, vmax = maxZ, clip = False) surf=ax.plot_surface(X, Y, Z,cmap=plt.cm.jet,norm=norm) ax.set_xlim(-limit,limit) ax.set_ylim(-limit,limit) fig.colorbar(surf, shrink=0.5, aspect=5) if __name__=='__main__': plot_3d(limit=1)
lgpl-3.0
michaeljohnbennett/zipline
zipline/modelling/engine.py
7
15401
""" Compute Engine for FFC API """ from abc import ( ABCMeta, abstractmethod, ) from operator import and_ from six import ( iteritems, itervalues, with_metaclass, ) from six.moves import ( reduce, zip_longest, ) from numpy import ( add, empty_like, ) from pandas import ( DataFrame, date_range, MultiIndex, ) from zipline.lib.adjusted_array import ensure_ndarray from zipline.errors import NoFurtherDataError from zipline.modelling.classifier import Classifier from zipline.modelling.factor import Factor from zipline.modelling.filter import Filter from zipline.modelling.graph import TermGraph class FFCEngine(with_metaclass(ABCMeta)): @abstractmethod def factor_matrix(self, terms, start_date, end_date): """ Compute values for `terms` between `start_date` and `end_date`. Returns a DataFrame with a MultiIndex of (date, asset) pairs on the index. On each date, we return a row for each asset that passed all instances of `Filter` in `terms, and the columns of the returned frame will be the keys in `terms` whose values are instances of `Factor`. Parameters ---------- terms : dict Map from str -> zipline.modelling.term.Term. start_date : datetime The first date of the matrix. end_date : datetime The last date of the matrix. Returns ------- matrix : pd.DataFrame A matrix of factors """ raise NotImplementedError("factor_matrix") class NoOpFFCEngine(FFCEngine): """ FFCEngine that doesn't do anything. """ def factor_matrix(self, terms, start_date, end_date): return DataFrame( index=MultiIndex.from_product( [date_range(start=start_date, end=end_date, freq='D'), ()], ), columns=sorted(terms.keys()) ) class SimpleFFCEngine(object): """ FFC Engine class that computes each term independently. Parameters ---------- loader : FFCLoader A loader to use to retrieve raw data for atomic terms. calendar : DatetimeIndex Array of dates to consider as trading days when computing a range between a fixed start and end. asset_finder : zipline.assets.AssetFinder An AssetFinder instance. We depend on the AssetFinder to determine which assets are in the top-level universe at any point in time. """ __slots__ = [ '_loader', '_calendar', '_finder', '__weakref__', ] def __init__(self, loader, calendar, asset_finder): self._loader = loader self._calendar = calendar self._finder = asset_finder def factor_matrix(self, terms, start_date, end_date): """ Compute a factor matrix. Parameters ---------- terms : dict[str -> zipline.modelling.term.Term] Dict mapping term names to instances. The supplied names are used as column names in our output frame. start_date : pd.Timestamp Start date of the computed matrix. end_date : pd.Timestamp End date of the computed matrix. The algorithm implemented here can be broken down into the following stages: 0. Build a dependency graph of all terms in `terms`. Topologically sort the graph to determine an order in which we can compute the terms. 1. Ask our AssetFinder for a "lifetimes matrix", which should contain, for each date between start_date and end_date, a boolean value for each known asset indicating whether the asset existed on that date. 2. Compute each term in the dependency order determined in (0), caching the results in a a dictionary to that they can be fed into future terms. 3. For each date, determine the number of assets passing **all** filters. The sum, N, of all these values is the total number of rows in our output frame, so we pre-allocate an output array of length N for each factor in `terms`. 4. Fill in the arrays allocated in (3) by copying computed values from our output cache into the corresponding rows. 5. Stick the values computed in (4) into a DataFrame and return it. Step 0 is performed by `zipline.modelling.graph.TermGraph`. Step 1 is performed in `self.build_lifetimes_matrix`. Step 2 is performed in `self.compute_chunk`. Steps 3, 4, and 5 are performed in self._format_factor_matrix. See Also -------- FFCEngine.factor_matrix """ if end_date <= start_date: raise ValueError( "start_date must be before end_date \n" "start_date=%s, end_date=%s" % (start_date, end_date) ) graph = TermGraph(terms) max_extra_rows = graph.max_extra_rows lifetimes = self.build_lifetimes_matrix( start_date, end_date, max_extra_rows, ) raw_outputs = self.compute_chunk(graph, lifetimes, {}) lifetimes_between_dates = lifetimes[max_extra_rows:] dates = lifetimes_between_dates.index.values assets = lifetimes_between_dates.columns.values # We only need filters and factors to compute the final output matrix. filters, factors = {}, {} for name, term in iteritems(terms): if isinstance(term, Filter): filters[name] = raw_outputs[name] elif isinstance(term, Factor): factors[name] = raw_outputs[name] elif isinstance(term, Classifier): continue else: raise ValueError("Unknown term type: %s" % term) # Treat base_mask as an implicit filter. # TODO: Is there a clean way to make this actually just be a filter? filters['base'] = lifetimes_between_dates.values return self._format_factor_matrix(dates, assets, filters, factors) def build_lifetimes_matrix(self, start_date, end_date, extra_rows): """ Compute a lifetimes matrix from our AssetFinder, then drop columns that didn't exist at all during the query dates. Parameters ---------- start_date : pd.Timestamp Base start date for the matrix. end_date : pd.Timestamp End date for the matrix. extra_rows : int Number of rows prior to `start_date` to include. Extra rows are needed by terms like moving averages that require a trailing window of data to compute. Returns ------- lifetimes : pd.DataFrame Frame of dtype `bool` containing dates from `extra_rows` days before `start_date`, continuing through to `end_date`. The returned frame contains as columns all assets in our AssetFinder that existed for at least one day between `start_date` and `end_date`. """ calendar = self._calendar finder = self._finder start_idx, end_idx = self._calendar.slice_locs(start_date, end_date) if start_idx < extra_rows: raise NoFurtherDataError( msg="Insufficient data to compute FFC Matrix: " "start date was %s, " "earliest known date was %s, " "and %d extra rows were requested." % ( start_date, calendar[0], extra_rows, ), ) # Build lifetimes matrix reaching back to `extra_rows` days before # `start_date.` lifetimes = finder.lifetimes( calendar[start_idx - extra_rows:end_idx] ) assert lifetimes.index[extra_rows] == start_date assert lifetimes.index[-1] == end_date if not lifetimes.columns.unique: columns = lifetimes.columns duplicated = columns[columns.duplicated()].unique() raise AssertionError("Duplicated sids: %d" % duplicated) # Filter out columns that didn't exist between the requested start and # end dates. existed = lifetimes.iloc[extra_rows:].any() return lifetimes.loc[:, existed] def _inputs_for_term(self, term, workspace, extra_rows): """ Compute inputs for the given term. This is mostly complicated by the fact that for each input we store as many rows as will be necessary to serve any term requiring that input. Thus if Factor A needs 5 extra rows of price, and Factor B needs 3 extra rows of price, we need to remove 2 leading rows from our stored prices before passing them to Factor B. """ term_extra_rows = term.extra_input_rows if term.windowed: return [ workspace[input_].traverse( term.window_length, offset=extra_rows[input_] - term_extra_rows ) for input_ in term.inputs ] else: return [ ensure_ndarray( workspace[input_][ extra_rows[input_] - term_extra_rows: ], ) for input_ in term.inputs ] def compute_chunk(self, graph, base_mask, initial_workspace): """ Compute the FFC terms in the graph for the requested start and end dates. Parameters ---------- graph : zipline.modelling.graph.TermGraph Returns ------- results : dict Dictionary mapping requested results to outputs. """ loader = self._loader extra_rows = graph.extra_rows max_extra_rows = graph.max_extra_rows workspace = {} if initial_workspace is not None: workspace.update(initial_workspace) for term in graph.ordered(): # Subclasses are allowed to pre-populate computed values for terms, # and in the future we may pre-compute atomic terms coming from the # same dataset. In both cases, it's possible that we already have # an entry for this term. if term in workspace: continue base_mask_for_term = base_mask.iloc[ max_extra_rows - extra_rows[term]: ] if term.atomic: # FUTURE OPTIMIZATION: Scan the resolution order for terms in # the same dataset and load them here as well. to_load = [term] loaded = loader.load_adjusted_array( to_load, base_mask_for_term, ) for loaded_term, adj_array in zip_longest(to_load, loaded): workspace[loaded_term] = adj_array else: if term.windowed: compute = term.compute_from_windows else: compute = term.compute_from_arrays workspace[term] = compute( self._inputs_for_term(term, workspace, extra_rows), base_mask_for_term, ) assert(workspace[term].shape == base_mask_for_term.shape) out = {} for name, term in iteritems(graph.outputs): # Truncate off extra rows from outputs. out[name] = workspace[term][extra_rows[term]:] return out def _format_factor_matrix(self, dates, assets, filters, factors): """ Convert raw computed filters/factors into a DataFrame for public APIs. Parameters ---------- dates : np.array[datetime64] Row index for arrays in `filters` and `factors.` assets : np.array[int64] Column index for arrays in `filters` and `factors.` filters : dict Dict mapping filter names -> computed filters. factors : dict Dict mapping factor names -> computed factors. Returns ------- factor_matrix : pd.DataFrame The indices of `factor_matrix` are as follows: index : two-tiered MultiIndex of (date, asset). For each date, we return a row for each asset that passed all filters on that date. columns : keys from `factor_data` Each date/asset/factor triple contains the computed value of the given factor on the given date for the given asset. """ # FUTURE OPTIMIZATION: Cythonize all of this. # Boolean mask of values that passed all filters. unioned = reduce(and_, itervalues(filters)) # Parallel arrays of (x,y) coords for (date, asset) pairs that passed # all filters. Each entry here will correspond to a row in our output # frame. nonzero_xs, nonzero_ys = unioned.nonzero() # Raw arrays storing (date, asset) pairs. # These will form the index of our output frame. raw_dates_index = empty_like(nonzero_xs, dtype='datetime64[ns]') raw_assets_index = empty_like(nonzero_xs, dtype=int) # Mapping from column_name -> array. # This will be the `data` arg to our output frame. columns = { name: empty_like(nonzero_xs, dtype=factor.dtype) for name, factor in iteritems(factors) } # We're going to iterate over `iteritems(columns)` a whole bunch of # times down below. It's faster to construct iterate over a tuple of # pairs. columns_iter = tuple(iteritems(columns)) # This is tricky. # unioned.sum(axis=1) gives us an array of the same size as `dates` # containing, for each date, the number of assets that passed our # filters on that date. # Running this through add.accumulate gives us an array containing, for # each date, the running total of the number of assets that passed our # filters on or before that date. # This means that (bounds[i - 1], bounds[i]) gives us the indices of # the first and last rows in our output frame for each date in `dates`. bounds = add.accumulate(unioned.sum(axis=1)) day_start = 0 for day_idx, day_end in enumerate(bounds): day_bounds = slice(day_start, day_end) column_indices = nonzero_ys[day_bounds] raw_dates_index[day_bounds] = dates[day_idx] raw_assets_index[day_bounds] = assets[column_indices] for name, colarray in columns_iter: colarray[day_bounds] = factors[name][day_idx, column_indices] # Upper bound of current row becomes lower bound for next row. day_start = day_end return DataFrame( data=columns, index=MultiIndex.from_arrays( [ raw_dates_index, # FUTURE OPTIMIZATION: # Avoid duplicate lookups by grouping and only looking up # each unique sid once. self._finder.retrieve_all(raw_assets_index), ], ) ).tz_localize('UTC', level=0)
apache-2.0
pkruskal/scikit-learn
sklearn/linear_model/ransac.py
191
14261
# coding: utf-8 # Author: Johannes Schönberger # # License: BSD 3 clause import numpy as np from ..base import BaseEstimator, MetaEstimatorMixin, RegressorMixin, clone from ..utils import check_random_state, check_array, check_consistent_length from ..utils.random import sample_without_replacement from ..utils.validation import check_is_fitted from .base import LinearRegression _EPSILON = np.spacing(1) def _dynamic_max_trials(n_inliers, n_samples, min_samples, probability): """Determine number trials such that at least one outlier-free subset is sampled for the given inlier/outlier ratio. Parameters ---------- n_inliers : int Number of inliers in the data. n_samples : int Total number of samples in the data. min_samples : int Minimum number of samples chosen randomly from original data. probability : float Probability (confidence) that one outlier-free sample is generated. Returns ------- trials : int Number of trials. """ inlier_ratio = n_inliers / float(n_samples) nom = max(_EPSILON, 1 - probability) denom = max(_EPSILON, 1 - inlier_ratio ** min_samples) if nom == 1: return 0 if denom == 1: return float('inf') return abs(float(np.ceil(np.log(nom) / np.log(denom)))) class RANSACRegressor(BaseEstimator, MetaEstimatorMixin, RegressorMixin): """RANSAC (RANdom SAmple Consensus) algorithm. RANSAC is an iterative algorithm for the robust estimation of parameters from a subset of inliers from the complete data set. More information can be found in the general documentation of linear models. A detailed description of the algorithm can be found in the documentation of the ``linear_model`` sub-package. Read more in the :ref:`User Guide <RansacRegression>`. Parameters ---------- base_estimator : object, optional Base estimator object which implements the following methods: * `fit(X, y)`: Fit model to given training data and target values. * `score(X, y)`: Returns the mean accuracy on the given test data, which is used for the stop criterion defined by `stop_score`. Additionally, the score is used to decide which of two equally large consensus sets is chosen as the better one. If `base_estimator` is None, then ``base_estimator=sklearn.linear_model.LinearRegression()`` is used for target values of dtype float. Note that the current implementation only supports regression estimators. min_samples : int (>= 1) or float ([0, 1]), optional Minimum number of samples chosen randomly from original data. Treated as an absolute number of samples for `min_samples >= 1`, treated as a relative number `ceil(min_samples * X.shape[0]`) for `min_samples < 1`. This is typically chosen as the minimal number of samples necessary to estimate the given `base_estimator`. By default a ``sklearn.linear_model.LinearRegression()`` estimator is assumed and `min_samples` is chosen as ``X.shape[1] + 1``. residual_threshold : float, optional Maximum residual for a data sample to be classified as an inlier. By default the threshold is chosen as the MAD (median absolute deviation) of the target values `y`. is_data_valid : callable, optional This function is called with the randomly selected data before the model is fitted to it: `is_data_valid(X, y)`. If its return value is False the current randomly chosen sub-sample is skipped. is_model_valid : callable, optional This function is called with the estimated model and the randomly selected data: `is_model_valid(model, X, y)`. If its return value is False the current randomly chosen sub-sample is skipped. Rejecting samples with this function is computationally costlier than with `is_data_valid`. `is_model_valid` should therefore only be used if the estimated model is needed for making the rejection decision. max_trials : int, optional Maximum number of iterations for random sample selection. stop_n_inliers : int, optional Stop iteration if at least this number of inliers are found. stop_score : float, optional Stop iteration if score is greater equal than this threshold. stop_probability : float in range [0, 1], optional RANSAC iteration stops if at least one outlier-free set of the training data is sampled in RANSAC. This requires to generate at least N samples (iterations):: N >= log(1 - probability) / log(1 - e**m) where the probability (confidence) is typically set to high value such as 0.99 (the default) and e is the current fraction of inliers w.r.t. the total number of samples. residual_metric : callable, optional Metric to reduce the dimensionality of the residuals to 1 for multi-dimensional target values ``y.shape[1] > 1``. By default the sum of absolute differences is used:: lambda dy: np.sum(np.abs(dy), axis=1) random_state : integer or numpy.RandomState, optional The generator used to initialize the centers. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator. Attributes ---------- estimator_ : object Best fitted model (copy of the `base_estimator` object). n_trials_ : int Number of random selection trials until one of the stop criteria is met. It is always ``<= max_trials``. inlier_mask_ : bool array of shape [n_samples] Boolean mask of inliers classified as ``True``. References ---------- .. [1] http://en.wikipedia.org/wiki/RANSAC .. [2] http://www.cs.columbia.edu/~belhumeur/courses/compPhoto/ransac.pdf .. [3] http://www.bmva.org/bmvc/2009/Papers/Paper355/Paper355.pdf """ def __init__(self, base_estimator=None, min_samples=None, residual_threshold=None, is_data_valid=None, is_model_valid=None, max_trials=100, stop_n_inliers=np.inf, stop_score=np.inf, stop_probability=0.99, residual_metric=None, random_state=None): self.base_estimator = base_estimator self.min_samples = min_samples self.residual_threshold = residual_threshold self.is_data_valid = is_data_valid self.is_model_valid = is_model_valid self.max_trials = max_trials self.stop_n_inliers = stop_n_inliers self.stop_score = stop_score self.stop_probability = stop_probability self.residual_metric = residual_metric self.random_state = random_state def fit(self, X, y): """Fit estimator using RANSAC algorithm. Parameters ---------- X : array-like or sparse matrix, shape [n_samples, n_features] Training data. y : array-like, shape = [n_samples] or [n_samples, n_targets] Target values. Raises ------ ValueError If no valid consensus set could be found. This occurs if `is_data_valid` and `is_model_valid` return False for all `max_trials` randomly chosen sub-samples. """ X = check_array(X, accept_sparse='csr') y = check_array(y, ensure_2d=False) check_consistent_length(X, y) if self.base_estimator is not None: base_estimator = clone(self.base_estimator) else: base_estimator = LinearRegression() if self.min_samples is None: # assume linear model by default min_samples = X.shape[1] + 1 elif 0 < self.min_samples < 1: min_samples = np.ceil(self.min_samples * X.shape[0]) elif self.min_samples >= 1: if self.min_samples % 1 != 0: raise ValueError("Absolute number of samples must be an " "integer value.") min_samples = self.min_samples else: raise ValueError("Value for `min_samples` must be scalar and " "positive.") if min_samples > X.shape[0]: raise ValueError("`min_samples` may not be larger than number " "of samples ``X.shape[0]``.") if self.stop_probability < 0 or self.stop_probability > 1: raise ValueError("`stop_probability` must be in range [0, 1].") if self.residual_threshold is None: # MAD (median absolute deviation) residual_threshold = np.median(np.abs(y - np.median(y))) else: residual_threshold = self.residual_threshold if self.residual_metric is None: residual_metric = lambda dy: np.sum(np.abs(dy), axis=1) else: residual_metric = self.residual_metric random_state = check_random_state(self.random_state) try: # Not all estimator accept a random_state base_estimator.set_params(random_state=random_state) except ValueError: pass n_inliers_best = 0 score_best = np.inf inlier_mask_best = None X_inlier_best = None y_inlier_best = None # number of data samples n_samples = X.shape[0] sample_idxs = np.arange(n_samples) n_samples, _ = X.shape for self.n_trials_ in range(1, self.max_trials + 1): # choose random sample set subset_idxs = sample_without_replacement(n_samples, min_samples, random_state=random_state) X_subset = X[subset_idxs] y_subset = y[subset_idxs] # check if random sample set is valid if (self.is_data_valid is not None and not self.is_data_valid(X_subset, y_subset)): continue # fit model for current random sample set base_estimator.fit(X_subset, y_subset) # check if estimated model is valid if (self.is_model_valid is not None and not self.is_model_valid(base_estimator, X_subset, y_subset)): continue # residuals of all data for current random sample model y_pred = base_estimator.predict(X) diff = y_pred - y if diff.ndim == 1: diff = diff.reshape(-1, 1) residuals_subset = residual_metric(diff) # classify data into inliers and outliers inlier_mask_subset = residuals_subset < residual_threshold n_inliers_subset = np.sum(inlier_mask_subset) # less inliers -> skip current random sample if n_inliers_subset < n_inliers_best: continue if n_inliers_subset == 0: raise ValueError("No inliers found, possible cause is " "setting residual_threshold ({0}) too low.".format( self.residual_threshold)) # extract inlier data set inlier_idxs_subset = sample_idxs[inlier_mask_subset] X_inlier_subset = X[inlier_idxs_subset] y_inlier_subset = y[inlier_idxs_subset] # score of inlier data set score_subset = base_estimator.score(X_inlier_subset, y_inlier_subset) # same number of inliers but worse score -> skip current random # sample if (n_inliers_subset == n_inliers_best and score_subset < score_best): continue # save current random sample as best sample n_inliers_best = n_inliers_subset score_best = score_subset inlier_mask_best = inlier_mask_subset X_inlier_best = X_inlier_subset y_inlier_best = y_inlier_subset # break if sufficient number of inliers or score is reached if (n_inliers_best >= self.stop_n_inliers or score_best >= self.stop_score or self.n_trials_ >= _dynamic_max_trials(n_inliers_best, n_samples, min_samples, self.stop_probability)): break # if none of the iterations met the required criteria if inlier_mask_best is None: raise ValueError( "RANSAC could not find valid consensus set, because" " either the `residual_threshold` rejected all the samples or" " `is_data_valid` and `is_model_valid` returned False for all" " `max_trials` randomly ""chosen sub-samples. Consider " "relaxing the ""constraints.") # estimate final model using all inliers base_estimator.fit(X_inlier_best, y_inlier_best) self.estimator_ = base_estimator self.inlier_mask_ = inlier_mask_best return self def predict(self, X): """Predict using the estimated model. This is a wrapper for `estimator_.predict(X)`. Parameters ---------- X : numpy array of shape [n_samples, n_features] Returns ------- y : array, shape = [n_samples] or [n_samples, n_targets] Returns predicted values. """ check_is_fitted(self, 'estimator_') return self.estimator_.predict(X) def score(self, X, y): """Returns the score of the prediction. This is a wrapper for `estimator_.score(X, y)`. Parameters ---------- X : numpy array or sparse matrix of shape [n_samples, n_features] Training data. y : array, shape = [n_samples] or [n_samples, n_targets] Target values. Returns ------- z : float Score of the prediction. """ check_is_fitted(self, 'estimator_') return self.estimator_.score(X, y)
bsd-3-clause
isrohutamahopetechnik/mavlink
pymavlink/tools/mavgraph.py
18
9628
#!/usr/bin/env python ''' graph a MAVLink log file Andrew Tridgell August 2011 ''' import sys, struct, time, os, datetime import math, re import matplotlib from math import * from pymavlink.mavextra import * # cope with rename of raw_input in python3 try: input = raw_input except NameError: pass colourmap = { 'apm' : { 'MANUAL' : (1.0, 0, 0), 'AUTO' : ( 0, 1.0, 0), 'LOITER' : ( 0, 0, 1.0), 'FBWA' : (1.0, 0.5, 0), 'RTL' : ( 1, 0, 0.5), 'STABILIZE' : (0.5, 1.0, 0), 'LAND' : ( 0, 1.0, 0.5), 'STEERING' : (0.5, 0, 1.0), 'HOLD' : ( 0, 0.5, 1.0), 'ALT_HOLD' : (1.0, 0.5, 0.5), 'CIRCLE' : (0.5, 1.0, 0.5), 'POSITION' : (1.0, 0.0, 1.0), 'GUIDED' : (0.5, 0.5, 1.0), 'ACRO' : (1.0, 1.0, 0), 'CRUISE' : ( 0, 1.0, 1.0) }, 'px4' : { 'MANUAL' : (1.0, 0, 0), 'SEATBELT' : ( 0.5, 0.5, 0), 'EASY' : ( 0, 1.0, 0), 'AUTO' : ( 0, 0, 1.0), 'UNKNOWN' : ( 1.0, 1.0, 1.0) } } edge_colour = (0.1, 0.1, 0.1) lowest_x = None highest_x = None def plotit(x, y, fields, colors=[]): '''plot a set of graphs using date for x axis''' global lowest_x, highest_x pylab.ion() fig = pylab.figure(num=1, figsize=(12,6)) ax1 = fig.gca() ax2 = None xrange = 0.0 for i in range(0, len(fields)): if len(x[i]) == 0: continue if lowest_x is None or x[i][0] < lowest_x: lowest_x = x[i][0] if highest_x is None or x[i][-1] > highest_x: highest_x = x[i][-1] if highest_x is None or lowest_x is None: return xrange = highest_x - lowest_x xrange *= 24 * 60 * 60 formatter = matplotlib.dates.DateFormatter('%H:%M:%S') interval = 1 intervals = [ 1, 2, 5, 10, 15, 30, 60, 120, 240, 300, 600, 900, 1800, 3600, 7200, 5*3600, 10*3600, 24*3600 ] for interval in intervals: if xrange / interval < 15: break locator = matplotlib.dates.SecondLocator(interval=interval) if not args.xaxis: ax1.xaxis.set_major_locator(locator) ax1.xaxis.set_major_formatter(formatter) empty = True ax1_labels = [] ax2_labels = [] for i in range(0, len(fields)): if len(x[i]) == 0: print("Failed to find any values for field %s" % fields[i]) continue if i < len(colors): color = colors[i] else: color = 'red' (tz, tzdst) = time.tzname if axes[i] == 2: if ax2 == None: ax2 = ax1.twinx() ax = ax2 if not args.xaxis: ax2.xaxis.set_major_locator(locator) ax2.xaxis.set_major_formatter(formatter) label = fields[i] if label.endswith(":2"): label = label[:-2] ax2_labels.append(label) else: ax1_labels.append(fields[i]) ax = ax1 if args.xaxis: if args.marker is not None: marker = args.marker else: marker = '+' if args.linestyle is not None: linestyle = args.linestyle else: linestyle = 'None' ax.plot(x[i], y[i], color=color, label=fields[i], linestyle=linestyle, marker=marker) else: if args.marker is not None: marker = args.marker else: marker = 'None' if args.linestyle is not None: linestyle = args.linestyle else: linestyle = '-' ax.plot_date(x[i], y[i], color=color, label=fields[i], linestyle=linestyle, marker=marker, tz=None) empty = False if args.flightmode is not None: for i in range(len(modes)-1): c = colourmap[args.flightmode].get(modes[i][1], edge_colour) ax1.axvspan(modes[i][0], modes[i+1][0], fc=c, ec=edge_colour, alpha=0.1) c = colourmap[args.flightmode].get(modes[-1][1], edge_colour) ax1.axvspan(modes[-1][0], ax1.get_xlim()[1], fc=c, ec=edge_colour, alpha=0.1) if ax1_labels != []: ax1.legend(ax1_labels,loc=args.legend) if ax2_labels != []: ax2.legend(ax2_labels,loc=args.legend2) if empty: print("No data to graph") return from argparse import ArgumentParser parser = ArgumentParser(description=__doc__) parser.add_argument("--no-timestamps", dest="notimestamps", action='store_true', help="Log doesn't have timestamps") parser.add_argument("--planner", action='store_true', help="use planner file format") parser.add_argument("--condition", default=None, help="select packets by a condition") parser.add_argument("--labels", default=None, help="comma separated field labels") parser.add_argument("--legend", default='upper left', help="default legend position") parser.add_argument("--legend2", default='upper right', help="default legend2 position") parser.add_argument("--marker", default=None, help="point marker") parser.add_argument("--linestyle", default=None, help="line style") parser.add_argument("--xaxis", default=None, help="X axis expression") parser.add_argument("--multi", action='store_true', help="multiple files with same colours") parser.add_argument("--zero-time-base", action='store_true', help="use Z time base for DF logs") parser.add_argument("--flightmode", default=None, help="Choose the plot background according to the active flight mode of the specified type, e.g. --flightmode=apm for ArduPilot or --flightmode=px4 for PX4 stack logs. Cannot be specified with --xaxis.") parser.add_argument("--dialect", default="ardupilotmega", help="MAVLink dialect") parser.add_argument("--output", default=None, help="provide an output format") parser.add_argument("logs_fields", metavar="<LOG or FIELD>", nargs="+") args = parser.parse_args() from pymavlink import mavutil if args.flightmode is not None and args.xaxis: print("Cannot request flightmode backgrounds with an x-axis expression") sys.exit(1) if args.flightmode is not None and args.flightmode not in colourmap: print("Unknown flight controller '%s' in specification of --flightmode" % args.flightmode) sys.exit(1) if args.output is not None: matplotlib.use('Agg') import pylab filenames = [] fields = [] for f in args.logs_fields: if os.path.exists(f): filenames.append(f) else: fields.append(f) msg_types = set() multiplier = [] field_types = [] colors = [ 'red', 'green', 'blue', 'orange', 'olive', 'black', 'grey', 'yellow', 'brown', 'darkcyan', 'cornflowerblue', 'darkmagenta', 'deeppink', 'darkred'] # work out msg types we are interested in x = [] y = [] modes = [] axes = [] first_only = [] re_caps = re.compile('[A-Z_][A-Z0-9_]+') for f in fields: caps = set(re.findall(re_caps, f)) msg_types = msg_types.union(caps) field_types.append(caps) y.append([]) x.append([]) axes.append(1) first_only.append(False) def add_data(t, msg, vars, flightmode): '''add some data''' mtype = msg.get_type() if args.flightmode is not None and (len(modes) == 0 or modes[-1][1] != flightmode): modes.append((t, flightmode)) if mtype not in msg_types: return for i in range(0, len(fields)): if mtype not in field_types[i]: continue f = fields[i] if f.endswith(":2"): axes[i] = 2 f = f[:-2] if f.endswith(":1"): first_only[i] = True f = f[:-2] v = mavutil.evaluate_expression(f, vars) if v is None: continue if args.xaxis is None: xv = t else: xv = mavutil.evaluate_expression(args.xaxis, vars) if xv is None: continue y[i].append(v) x[i].append(xv) def process_file(filename): '''process one file''' print("Processing %s" % filename) mlog = mavutil.mavlink_connection(filename, notimestamps=args.notimestamps, zero_time_base=args.zero_time_base, dialect=args.dialect) vars = {} while True: msg = mlog.recv_match(args.condition) if msg is None: break tdays = matplotlib.dates.date2num(datetime.datetime.fromtimestamp(msg._timestamp)) add_data(tdays, msg, mlog.messages, mlog.flightmode) if len(filenames) == 0: print("No files to process") sys.exit(1) if args.labels is not None: labels = args.labels.split(',') if len(labels) != len(fields)*len(filenames): print("Number of labels (%u) must match number of fields (%u)" % ( len(labels), len(fields)*len(filenames))) sys.exit(1) else: labels = None for fi in range(0, len(filenames)): f = filenames[fi] process_file(f) for i in range(0, len(x)): if first_only[i] and fi != 0: x[i] = [] y[i] = [] if labels: lab = labels[fi*len(fields):(fi+1)*len(fields)] else: lab = fields[:] if args.multi: col = colors[:] else: col = colors[fi*len(fields):] plotit(x, y, lab, colors=col) for i in range(0, len(x)): x[i] = [] y[i] = [] if args.output is None: pylab.show() pylab.draw() input('press enter to exit....') else: pylab.legend(loc=2,prop={'size':8}) pylab.savefig(args.output, bbox_inches='tight', dpi=200)
lgpl-3.0
elivre/arfe
e2018/SCRIPTS/010-rede2018_candidaturas.py
1
16410
#!/usr/bin/env python # coding: utf-8 # # 010-candidaturas # In[ ]: ano_eleicao = '2018' dbschema = f'rede{ano_eleicao}' table_candidaturas = f"{dbschema}.candidaturas_{ano_eleicao}" table_consulta_cand = f"tse{ano_eleicao}.consulta_cand_{ano_eleicao}" table_despesas_candidatos = f"tse{ano_eleicao}.despesas_contratadas_candidatos_{ano_eleicao}" table_receitas_candidatos = f"tse{ano_eleicao}.receitas_candidatos_{ano_eleicao}" table_votacao_candidato_munzona = f"tse{ano_eleicao}.votacao_candidato_munzona_{ano_eleicao}" # In[2]: import os import sys sys.path.append('../') import mod_tse as mtse home = os.environ["HOME"] # ## TABELA CANDIDATURAS # In[3]: query_create_table_candidaturas = F""" drop table if exists {table_candidaturas} cascade; -- Atributos obtidos da tabela do TSE consulta_cand create table {table_candidaturas} ( ano_eleicao varchar, cd_tipo_eleicao varchar, cd_eleicao varchar, nr_turno varchar, tp_abrangencia varchar, sg_uf varchar, sg_ue varchar, nm_ue varchar, -------------------------------------- ds_cargo varchar, sq_candidato varchar, nr_candidato varchar, nm_candidato varchar, nm_urna_candidato varchar, nr_cpf_candidato varchar, ds_situacao_candidatura varchar, ds_detalhe_situacao_cand varchar, tp_agremiacao varchar, nr_partido varchar, sg_partido varchar, nm_partido varchar, nm_coligacao varchar, ds_composicao_coligacao varchar, ds_nacionalidade varchar, sg_uf_nascimento varchar, nm_municipio_nascimento varchar, dt_nascimento varchar, nr_idade_data_posse varchar, ds_genero varchar, ds_grau_instrucao varchar, ds_estado_civil varchar, ds_cor_raca varchar, cd_ocupacao varchar, ds_ocupacao varchar, nr_despesa_max_campanha numeric(18,2), ds_sit_tot_turno varchar, st_reeleicao varchar, st_declarar_bens varchar, --------------------------------------------- candidato_id varchar, candidato_label varchar, candidato_titular_apto varchar, candidatura_id varchar, candidatura_nome varchar, candidatura_label varchar, --------------------------------------------- total_votos_turno_1 numeric, total_votos_turno_2 numeric, total_votos numeric, --------------------------------------------- nr_cnpj_prestador_conta varchar, declarou_receita varchar, receita_total numeric(18,2), declarou_despesa varchar, despesa_total numeric(18,2), custo_voto numeric(18,2), tse_id varchar ); CREATE INDEX ON {table_candidaturas} (candidato_id); CREATE INDEX ON {table_candidaturas} (candidatura_id); CREATE INDEX ON {table_candidaturas} (nm_candidato); CREATE INDEX ON {table_candidaturas} (candidato_label); CREATE INDEX ON {table_candidaturas} (candidatura_label); CREATE INDEX ON {table_candidaturas} (nm_urna_candidato); CREATE INDEX IF NOT EXISTS sq_candidato_idx ON {table_candidaturas} ( sq_candidato ); """ mtse.execute_query(query_create_table_candidaturas) # ## Insere os dados de consulta_cand # In[4]: def query_insert_candidaturas(cd_tipo_eleicao, nr_turno): query = f""" INSERT INTO {table_candidaturas} (SELECT ano_eleicao as ano_eleicao, cd_tipo_eleicao as cd_tipo_eleicao, cd_eleicao as cd_eleicao, nr_turno as nr_turno, tp_abrangencia as tp_abrangencia, sg_uf as sg_uf, sg_ue as sg_ue, nm_ue as nm_ue, ds_cargo as ds_cargo, sq_candidato as sq_candidato, nr_candidato as nr_candidato, upper(nm_candidato) as nm_candidato, nm_urna_candidato as nm_urna_candidato, nr_cpf_candidato as nr_cpf_candidato, ds_situacao_candidatura as ds_situacao_candidatura, ds_detalhe_situacao_cand as ds_detalhe_situacao_cand, tp_agremiacao as tp_agremiacao, nr_partido as nr_partido, sg_partido as sg_partido, nm_partido as nm_partido, nm_coligacao as nm_coligacao, ds_composicao_coligacao as ds_composicao_coligacao, ds_nacionalidade as ds_nacionalidade, sg_uf_nascimento as sg_uf_nascimento, nm_municipio_nascimento as nm_municipio_nascimento, dt_nascimento as dt_nascimento, nr_idade_data_posse as nr_idade_data_posse, ds_genero as ds_genero, ds_grau_instrucao as ds_grau_instrucao, ds_estado_civil as ds_estado_civil, ds_cor_raca as ds_cor_raca, cd_ocupacao as cd_ocupacao, ds_ocupacao as ds_ocupacao, nr_despesa_max_campanha::numeric(18,2) as nr_despesa_max_campanha, ds_sit_tot_turno as ds_sit_tot_turno, st_reeleicao as st_reeleicao, st_declarar_bens as st_declarar_bens, --------------------------------------------- get_candidato_id(nr_cpf_candidato) as candidato_id, get_candidato_label(nm_urna_candidato,ds_cargo,sg_uf,sg_partido) as candidato_label, public.eh_candidato_titular_apto(ds_cargo,ds_situacao_candidatura) as candidato_titular_apto, get_candidatura_id(sg_uf,nr_candidato) as candidatura_id, '' as candidatura_nome, '' as candidatura_label, -------------------------------------------- 0 as total_votos_turno_1, 0 as total_votos_turno_2, 0 as total_votos, -------------------------------------------- '' as nr_cnpj_prestador_conta, 'N' as declarou_receita, 0 as receita_total, 'N' as declarou_despesa, 0 as despesa_total, 0 as custo_voto, get_tse_id(sq_candidato) as tse_id from {table_consulta_cand} as c where c.cd_tipo_eleicao = '{cd_tipo_eleicao}' and c.nr_turno = '{nr_turno}' and get_candidato_id(c.nr_cpf_candidato)||ds_cargo not in (select candidato_id||ds_cargo from {table_candidaturas}) ) ; """ mtse.execute_query(query) # In[5]: query_insert_candidaturas('2','2') # In[6]: query_insert_candidaturas('2','1') # ### ATUALIZA DADOS 2. TURNO # In[7]: q = f""" update {table_candidaturas} c set ds_sit_tot_turno = cc.ds_sit_tot_turno, nr_turno = '2' from ( select nr_turno,sq_candidato, ds_sit_tot_turno from {table_consulta_cand} where nr_turno = '2' ) as cc where c.sq_candidato = cc.sq_candidato ; update {table_candidaturas} c set ds_sit_tot_turno = 'NÃO ELEITO' where ds_sit_tot_turno = '#NULO#' """ mtse.execute_query(q) # ### GERA TOTAL RECEITAS A PARTIR DA DECLARAÇÃO DE RECEITAS # In[8]: query_update_cnpj_a_partir_receitas = f""" with receitas_candidatos as ( SELECT sq_candidato, nr_cnpj_prestador_conta, round(sum(vr_receita),2) as receita_total, get_tse_id(sq_candidato) as tse_id FROM {table_receitas_candidatos} group by sq_candidato, nr_cnpj_prestador_conta, tse_id ) update {table_candidaturas} as c set nr_cnpj_prestador_conta = r.nr_cnpj_prestador_conta, declarou_receita = 'S', receita_total = r.receita_total from receitas_candidatos as r where c.tse_id = r.tse_id ; """ mtse.execute_query(query_update_cnpj_a_partir_receitas) # ### GERA TOTAL DESPESAS A PARTIR DA DECLARAÇÃO DE DESPESAS # In[9]: query_update_cnpj_a_partir_despesas = f""" with despesas_candidatos as ( SELECT sq_candidato, nr_cnpj_prestador_conta, round(sum(vr_despesa_contratada),2) as despesa_total, get_tse_id(sq_candidato) as tse_id FROM {table_despesas_candidatos} group by sq_candidato, nr_cnpj_prestador_conta, tse_id ) update {table_candidaturas} as c set nr_cnpj_prestador_conta = d.nr_cnpj_prestador_conta, declarou_despesa = 'S', despesa_total = d.despesa_total from despesas_candidatos as d where c.tse_id = d.tse_id ; """ mtse.execute_query(query_update_cnpj_a_partir_despesas) # ### Gera total votos turno 1 # In[10]: query_atualiza_total_votos_turno_1 = f""" with votos_turno_1 as ( select get_tse_id(sq_candidato) as tse_id, sum(qt_votos_nominais::numeric) as total_votos from {table_votacao_candidato_munzona} where nr_turno = '1' group by tse_id ) update {table_candidaturas} as c set total_votos_turno_1 = v1.total_votos, total_votos = v1.total_votos from votos_turno_1 as v1 where c.tse_id = v1.tse_id ; """ mtse.execute_query(query_atualiza_total_votos_turno_1) # ### Gera total votos turno 2 # In[11]: query_atualiza_total_votos_turno_2 = f""" with votos_turno_2 as ( select get_tse_id(sq_candidato) as tse_id, sum(qt_votos_nominais::numeric) as total_votos from {table_votacao_candidato_munzona} as v2 where nr_turno = '2' group by tse_id ) update {table_candidaturas} as c set total_votos_turno_2 = v2.total_votos, total_votos = v2.total_votos from votos_turno_2 as v2 where c.tse_id = v2.tse_id ; """ mtse.execute_query(query_atualiza_total_votos_turno_2) # ### Cálculo Custo do Voto # In[12]: query_calcula_custo_voto = f""" update {table_candidaturas} set custo_voto = case when total_votos > 0 then round(receita_total / total_votos,2) else 0 end """ mtse.execute_query(query_calcula_custo_voto) # ### Verifica Candidatos com mais de um registro # In[13]: mtse.pandas_query(f""" select candidato_id, q from (select candidato_id, count(*) as q from {table_candidaturas} group by candidato_id) t where q>1 order by q desc ; """ ) # ## Muda o id do registro mais antigo de candidato com mais de um registro # ### exclui candidato_id mais antigo quando dois registros para o mesmo candidato # def exclui_duplo_id(): # p=mtse.pandas_query(f""" # select candidato_id, tse_id from {table_candidaturas} # where candidato_id in( # select candidato_id # from (select candidato_id, count(*) as q from {table_candidaturas} # group by candidato_id) t # where q>1 # ) # order by candidato_id, tse_id # ; # """ # ) # p2=p[['candidato_id','tse_id']] # n = p2['candidato_id'].size # l=[] # for i in range(0,n,2): # l.append(p2.iloc[i]['tse_id']) # l= "'"+"', '".join(l)+"'" # # mtse.execute_query(f""" # update {table_candidaturas} # set candidato_id = # case # when candidato_id = 'CD000000000-4' then 'CD'||tse_id # else candidato_id||'-I' # end # where tse_id in ({l}) # """ # ) # return(n) # # while True: # n=exclui_duplo_id() # if n==0: # break # ### Verifica o resultado # In[14]: mtse.pandas_query(f""" select candidato_id, tse_id from {table_candidaturas} where candidato_id in( select candidato_id from (select candidato_id, count(*) as q from {table_candidaturas} group by candidato_id) t where q>1 ) order by candidato_id, tse_id ; """ ) # In[15]: mtse.pandas_query(f""" select nr_cpf_candidato, candidato_id, tse_id from {table_candidaturas} where nr_cpf_candidato in( select nr_cpf_candidato from (select nr_cpf_candidato, count(*) as q from {table_candidaturas} group by nr_cpf_candidato) t where q>1 ) order by candidato_id, tse_id ; """ ) # ### ESTABELECE NOME E LABEL PARA TODOS OS CANDIDATOS DA MESMA CANDIDATURA (candidatura_id) # In[16]: query_update_candidatura_nome_label = f""" with titulares as ( select * from {table_candidaturas} c where eh_candidato_titular(ds_cargo) = 'S' ) update {table_candidaturas} as c set candidatura_label = get_candidatura_label(t.nm_urna_candidato , t.ds_cargo , t.sg_uf , t.sg_partido ), candidatura_nome = get_candidatura_nome(t.nm_candidato, t.ds_cargo, t.sg_uf, t.sg_partido) from titulares as t where c.candidatura_id = t.candidatura_id ; """ mtse.execute_query(query_update_candidatura_nome_label) # In[ ]: # In[17]: mtse.pandas_query(f""" --select candidato_titular_apto, candidatura_id, q from {table_candidaturas} --where candidato_titular_apto||candidatura_id in( select c, q from (select candidato_titular_apto||candidatura_id c , count(*) as q from {table_candidaturas} where candidato_titular_apto = 'S' group by candidato_titular_apto||candidatura_id ) t where q>1 -- ) -- order by candidato_id, tse_id ; """ ) # In[18]: mtse.pandas_query(f""" select candidatura_id, tse_id from {table_candidaturas} where candidatura_id in( select candidatura_id from ( select candidatura_id, count(*) as q from {table_candidaturas} --where candidato_titular_apto = 'S' group by candidatura_id ) t where q>1 ) order by candidatura_id, tse_id ; """ ) # In[19]: import pandas as pd df_candidaturas_2018=mtse.pandas_query(f""" select sg_uf, ds_cargo, count(*) as qtd from {table_candidaturas} group by sg_uf, ds_cargo order by sg_uf, ds_cargo """) #df_candidaturas_2018.to_excel('df_candidaturas_2018.xlsx') df_candidaturas_2018[['sg_uf','ds_cargo']] # In[20]: import datetime print(datetime.datetime.now()) # In[ ]:
mit
sumspr/scikit-learn
sklearn/datasets/tests/test_20news.py
280
3045
"""Test the 20news downloader, if the data is available.""" import numpy as np import scipy.sparse as sp from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_true from sklearn.utils.testing import SkipTest from sklearn import datasets def test_20news(): try: data = datasets.fetch_20newsgroups( subset='all', download_if_missing=False, shuffle=False) except IOError: raise SkipTest("Download 20 newsgroups to run this test") # Extract a reduced dataset data2cats = datasets.fetch_20newsgroups( subset='all', categories=data.target_names[-1:-3:-1], shuffle=False) # Check that the ordering of the target_names is the same # as the ordering in the full dataset assert_equal(data2cats.target_names, data.target_names[-2:]) # Assert that we have only 0 and 1 as labels assert_equal(np.unique(data2cats.target).tolist(), [0, 1]) # Check that the number of filenames is consistent with data/target assert_equal(len(data2cats.filenames), len(data2cats.target)) assert_equal(len(data2cats.filenames), len(data2cats.data)) # Check that the first entry of the reduced dataset corresponds to # the first entry of the corresponding category in the full dataset entry1 = data2cats.data[0] category = data2cats.target_names[data2cats.target[0]] label = data.target_names.index(category) entry2 = data.data[np.where(data.target == label)[0][0]] assert_equal(entry1, entry2) def test_20news_length_consistency(): """Checks the length consistencies within the bunch This is a non-regression test for a bug present in 0.16.1. """ try: data = datasets.fetch_20newsgroups( subset='all', download_if_missing=False, shuffle=False) except IOError: raise SkipTest("Download 20 newsgroups to run this test") # Extract the full dataset data = datasets.fetch_20newsgroups(subset='all') assert_equal(len(data['data']), len(data.data)) assert_equal(len(data['target']), len(data.target)) assert_equal(len(data['filenames']), len(data.filenames)) def test_20news_vectorized(): # This test is slow. raise SkipTest("Test too slow.") bunch = datasets.fetch_20newsgroups_vectorized(subset="train") assert_true(sp.isspmatrix_csr(bunch.data)) assert_equal(bunch.data.shape, (11314, 107428)) assert_equal(bunch.target.shape[0], 11314) assert_equal(bunch.data.dtype, np.float64) bunch = datasets.fetch_20newsgroups_vectorized(subset="test") assert_true(sp.isspmatrix_csr(bunch.data)) assert_equal(bunch.data.shape, (7532, 107428)) assert_equal(bunch.target.shape[0], 7532) assert_equal(bunch.data.dtype, np.float64) bunch = datasets.fetch_20newsgroups_vectorized(subset="all") assert_true(sp.isspmatrix_csr(bunch.data)) assert_equal(bunch.data.shape, (11314 + 7532, 107428)) assert_equal(bunch.target.shape[0], 11314 + 7532) assert_equal(bunch.data.dtype, np.float64)
bsd-3-clause
pan-webis-de/glad
evaluation.py
3
3982
# -*- coding: utf-8 -*- import argparse import csv import warnings import sklearn.metrics def calculateAnswers(truth_dict, answers_dict, misclass_file=None): correct = 0 incorrect = 0 unanswered = 0 if misclass_file is not None: misclass = open(misclass_file, "w") for problem in answers_dict.keys(): truth = truth_dict[problem] answer = answers_dict[problem] if truth == "Y" and float(answer) > 0.5: correct += 1 elif truth == "N" and float(answer) < 0.5: correct += 1 elif float(answer) == 0.5: unanswered += 1 else: incorrect += 1 if misclass_file is not None: misclass.write(problem + "\n") return correct, incorrect, unanswered def calculateScore(correct, unanswered, numberOfProblems, truth_dict, answers_dict): score = (1 / numberOfProblems) * (correct + (unanswered * (correct / numberOfProblems))) l_true = [] l_answers = [] for problem in answers_dict.keys(): truth = truth_dict[problem] answer = answers_dict[problem] if truth == "Y": l_true.append(1) elif truth == "N": l_true.append(0) l_answers.append(float(answer)) aucScore = sklearn.metrics.roc_auc_score(l_true, l_answers) return round(score, 3), round(aucScore, 3) def _read_file_to_dict(path): """ Load the problems and the corresponding labels from the *.txt file. :param path: The full path to the file to read :return: The dictionary with the problem names as keys and the true class labels as values """ label_dict = {} with open(path, 'r', encoding='utf-8-sig') as truth_file: truth = csv.reader(truth_file, delimiter=' ') for problem in truth: label_dict[problem[0]] = problem[1] return label_dict def main(truth_file, answers_file, misclass_file=None): truth_dict = _read_file_to_dict(truth_file) answers_dict = _read_file_to_dict(answers_file) if truth_dict.keys() != answers_dict.keys(): warnings.warn("Apparently there are different problem instances in the truth file and the answers file!") if misclass_file is not None: correct, incorrect, unanswered = calculateAnswers(truth_dict, answers_dict, misclass_file) else: correct, incorrect, unanswered = calculateAnswers(truth_dict, answers_dict) number_of_problems = correct + incorrect + unanswered score, aucScore = calculateScore(correct, unanswered, number_of_problems, truth_dict, answers_dict) combined_score = score * aucScore print(u"The number of problems: {0:d}".format(number_of_problems)) print(u"The number of correct answers: {0:d}".format(correct)) print(u"The number of incorrect answers: {0:d}".format(incorrect)) print(u"The number of unanswered problems: {0:d}".format(unanswered)) print(u"The c@1 score: {0:f}".format(score)) print(u"The AUC: {0:f}".format(aucScore)) print(u"The combined score of c@1*AUC: {0:f}".format(combined_score)) return combined_score if __name__ == "__main__": parser = argparse.ArgumentParser(description="Calculate the PAN scores.") parser.add_argument("-a", "--answers", default="./answers.txt", metavar='PATH', dest='answers_file', help="Use a specified file to get the answers. (Default: ./answers,txt)") parser.add_argument("-t", "--truth", default="./truth.txt", metavar='PATH', dest='truth_file', help="Use a specified file to get the truth labels. (Default: ./truth,txt)") parser.add_argument("-m", "--misclassified", default="./misclassified.txt", metavar='PATH', dest='misclass_file', help="Use a specified file to write misclassified instances. (Default: ./misclassified.txt)") args = parser.parse_args() main(args.truth_file, args.answers_file, args.misclass_file)
gpl-2.0
TimoRoth/oggm
oggm/shop/cru.py
2
16453
import logging import warnings # External libs import numpy as np import pandas as pd import xarray as xr from scipy import stats # Optional libs try: import salem except ImportError: pass # Locals from oggm import cfg from oggm import utils from oggm import entity_task from oggm.exceptions import MassBalanceCalibrationError, InvalidParamsError # Module logger log = logging.getLogger(__name__) CRU_SERVER = ('https://crudata.uea.ac.uk/cru/data/hrg/cru_ts_4.04/' 'cruts.2004151855.v4.04/') CRU_BASE = 'cru_ts4.04.1901.2019.{}.dat.nc' CRU_CL = ('https://cluster.klima.uni-bremen.de/~oggm/climate/cru/' 'cru_cl2.nc.zip') def set_cru_url(url): """If you want to use a different server for CRU (for testing, etc).""" global CRU_SERVER CRU_SERVER = url @utils.locked_func def get_cru_cl_file(): """Returns the path to the unpacked CRU CL file.""" return utils.file_extractor(utils.file_downloader(CRU_CL)) @utils.locked_func def get_cru_file(var=None): """Returns a path to the desired CRU baseline climate file. If the file is not present, download it. Parameters ---------- var : str 'tmp' for temperature 'pre' for precipitation Returns ------- str path to the CRU file """ # Be sure input makes sense if var not in ['tmp', 'pre']: raise InvalidParamsError('CRU variable {} does not exist!'.format(var)) # Download cru_filename = CRU_BASE.format(var) cru_url = CRU_SERVER + '{}/'.format(var) + cru_filename + '.gz' return utils.file_extractor(utils.file_downloader(cru_url)) @entity_task(log, writes=['climate_historical']) def process_cru_data(gdir, tmp_file=None, pre_file=None, y0=None, y1=None, output_filesuffix=None): """Processes and writes the CRU baseline climate data for this glacier. Interpolates the CRU TS data to the high-resolution CL2 climatologies (provided with OGGM) and writes everything to a NetCDF file. Parameters ---------- gdir : :py:class:`oggm.GlacierDirectory` the glacier directory to process tmp_file : str path to the CRU temperature file (defaults to the current OGGM chosen CRU version) pre_file : str path to the CRU precip file (defaults to the current OGGM chosen CRU version) y0 : int the starting year of the timeseries to write. The default is to take the entire time period available in the file, but with this kwarg you can shorten it (to save space or to crop bad data) y1 : int the starting year of the timeseries to write. The default is to take the entire time period available in the file, but with this kwarg you can shorten it (to save space or to crop bad data) output_filesuffix : str this add a suffix to the output file (useful to avoid overwriting previous experiments) """ if cfg.PATHS.get('climate_file', None): warnings.warn("You seem to have set a custom climate file for this " "run, but are using the default CRU climate " "file instead.") if cfg.PARAMS['baseline_climate'] != 'CRU': raise InvalidParamsError("cfg.PARAMS['baseline_climate'] should be " "set to CRU") # read the climatology ncclim = salem.GeoNetcdf(get_cru_cl_file()) # and the TS data if tmp_file is None: tmp_file = get_cru_file('tmp') if pre_file is None: pre_file = get_cru_file('pre') nc_ts_tmp = salem.GeoNetcdf(tmp_file, monthbegin=True) nc_ts_pre = salem.GeoNetcdf(pre_file, monthbegin=True) # set temporal subset for the ts data (hydro years) sm = cfg.PARAMS['hydro_month_' + gdir.hemisphere] em = sm - 1 if (sm > 1) else 12 yrs = nc_ts_pre.time.year y0 = yrs[0] if y0 is None else y0 y1 = yrs[-1] if y1 is None else y1 nc_ts_tmp.set_period(t0='{}-{:02d}-01'.format(y0, sm), t1='{}-{:02d}-01'.format(y1, em)) nc_ts_pre.set_period(t0='{}-{:02d}-01'.format(y0, sm), t1='{}-{:02d}-01'.format(y1, em)) time = nc_ts_pre.time ny, r = divmod(len(time), 12) assert r == 0 lon = gdir.cenlon lat = gdir.cenlat # This is guaranteed to work because I prepared the file (I hope) ncclim.set_subset(corners=((lon, lat), (lon, lat)), margin=1) # get climatology data loc_hgt = ncclim.get_vardata('elev') loc_tmp = ncclim.get_vardata('temp') loc_pre = ncclim.get_vardata('prcp') loc_lon = ncclim.get_vardata('lon') loc_lat = ncclim.get_vardata('lat') # see if the center is ok if not np.isfinite(loc_hgt[1, 1]): # take another candidate where finite isok = np.isfinite(loc_hgt) # wait: some areas are entirely NaNs, make the subset larger _margin = 1 while not np.any(isok): _margin += 1 ncclim.set_subset(corners=((lon, lat), (lon, lat)), margin=_margin) loc_hgt = ncclim.get_vardata('elev') isok = np.isfinite(loc_hgt) if _margin > 1: log.debug('(%s) I had to look up for far climate pixels: %s', gdir.rgi_id, _margin) # Take the first candidate (doesn't matter which) lon, lat = ncclim.grid.ll_coordinates lon = lon[isok][0] lat = lat[isok][0] # Resubset ncclim.set_subset() ncclim.set_subset(corners=((lon, lat), (lon, lat)), margin=1) loc_hgt = ncclim.get_vardata('elev') loc_tmp = ncclim.get_vardata('temp') loc_pre = ncclim.get_vardata('prcp') loc_lon = ncclim.get_vardata('lon') loc_lat = ncclim.get_vardata('lat') assert np.isfinite(loc_hgt[1, 1]) isok = np.isfinite(loc_hgt) hgt_f = loc_hgt[isok].flatten() assert len(hgt_f) > 0. # Should we compute the gradient? use_grad = cfg.PARAMS['temp_use_local_gradient'] ts_grad = None if use_grad and len(hgt_f) >= 5: ts_grad = np.zeros(12) * np.NaN for i in range(12): loc_tmp_mth = loc_tmp[i, ...][isok].flatten() slope, _, _, p_val, _ = stats.linregress(hgt_f, loc_tmp_mth) ts_grad[i] = slope if (p_val < 0.01) else np.NaN # convert to a timeseries and hydrological years ts_grad = ts_grad.tolist() ts_grad = ts_grad[em:] + ts_grad[0:em] ts_grad = np.asarray(ts_grad * ny) # maybe this will throw out of bounds warnings nc_ts_tmp.set_subset(corners=((lon, lat), (lon, lat)), margin=1) nc_ts_pre.set_subset(corners=((lon, lat), (lon, lat)), margin=1) # compute monthly anomalies # of temp ts_tmp = nc_ts_tmp.get_vardata('tmp', as_xarray=True) ts_tmp_avg = ts_tmp.sel(time=slice('1961-01-01', '1990-12-01')) ts_tmp_avg = ts_tmp_avg.groupby('time.month').mean(dim='time') ts_tmp = ts_tmp.groupby('time.month') - ts_tmp_avg # of precip ts_pre = nc_ts_pre.get_vardata('pre', as_xarray=True) ts_pre_avg = ts_pre.sel(time=slice('1961-01-01', '1990-12-01')) ts_pre_avg = ts_pre_avg.groupby('time.month').mean(dim='time') ts_pre_ano = ts_pre.groupby('time.month') - ts_pre_avg # scaled anomalies is the default. Standard anomalies above # are used later for where ts_pre_avg == 0 ts_pre = ts_pre.groupby('time.month') / ts_pre_avg # interpolate to HR grid if np.any(~np.isfinite(ts_tmp[:, 1, 1])): # Extreme case, middle pix is not valid # take any valid pix from the 3*3 (and hope there's one) found_it = False for idi in range(2): for idj in range(2): if np.all(np.isfinite(ts_tmp[:, idj, idi])): ts_tmp[:, 1, 1] = ts_tmp[:, idj, idi] ts_pre[:, 1, 1] = ts_pre[:, idj, idi] ts_pre_ano[:, 1, 1] = ts_pre_ano[:, idj, idi] found_it = True if not found_it: msg = '({}) there is no climate data'.format(gdir.rgi_id) raise MassBalanceCalibrationError(msg) elif np.any(~np.isfinite(ts_tmp)): # maybe the side is nan, but we can do nearest ts_tmp = ncclim.grid.map_gridded_data(ts_tmp.values, nc_ts_tmp.grid, interp='nearest') ts_pre = ncclim.grid.map_gridded_data(ts_pre.values, nc_ts_pre.grid, interp='nearest') ts_pre_ano = ncclim.grid.map_gridded_data(ts_pre_ano.values, nc_ts_pre.grid, interp='nearest') else: # We can do bilinear ts_tmp = ncclim.grid.map_gridded_data(ts_tmp.values, nc_ts_tmp.grid, interp='linear') ts_pre = ncclim.grid.map_gridded_data(ts_pre.values, nc_ts_pre.grid, interp='linear') ts_pre_ano = ncclim.grid.map_gridded_data(ts_pre_ano.values, nc_ts_pre.grid, interp='linear') # take the center pixel and add it to the CRU CL clim # for temp loc_tmp = xr.DataArray(loc_tmp[:, 1, 1], dims=['month'], coords={'month': ts_tmp_avg.month}) ts_tmp = xr.DataArray(ts_tmp[:, 1, 1], dims=['time'], coords={'time': time}) ts_tmp = ts_tmp.groupby('time.month') + loc_tmp # for prcp loc_pre = xr.DataArray(loc_pre[:, 1, 1], dims=['month'], coords={'month': ts_pre_avg.month}) ts_pre = xr.DataArray(ts_pre[:, 1, 1], dims=['time'], coords={'time': time}) ts_pre_ano = xr.DataArray(ts_pre_ano[:, 1, 1], dims=['time'], coords={'time': time}) # scaled anomalies ts_pre = ts_pre.groupby('time.month') * loc_pre # standard anomalies ts_pre_ano = ts_pre_ano.groupby('time.month') + loc_pre # Correct infinite values with standard anomalies ts_pre.values = np.where(np.isfinite(ts_pre.values), ts_pre.values, ts_pre_ano.values) # The last step might create negative values (unlikely). Clip them ts_pre.values = utils.clip_min(ts_pre.values, 0) # done loc_hgt = loc_hgt[1, 1] loc_lon = loc_lon[1] loc_lat = loc_lat[1] assert np.isfinite(loc_hgt) assert np.all(np.isfinite(ts_pre.values)) assert np.all(np.isfinite(ts_tmp.values)) gdir.write_monthly_climate_file(time, ts_pre.values, ts_tmp.values, loc_hgt, loc_lon, loc_lat, filesuffix=output_filesuffix, gradient=ts_grad, source=nc_ts_tmp._nc.title[:10]) ncclim._nc.close() nc_ts_tmp._nc.close() nc_ts_pre._nc.close() @entity_task(log, writes=['climate_historical']) def process_dummy_cru_file(gdir, sigma_temp=2, sigma_prcp=0.5, seed=None, y0=None, y1=None, output_filesuffix=None): """Create a simple baseline climate file for this glacier - for testing! This simply reproduces the climatology with a little randomness in it. TODO: extend the functionality by allowing a monthly varying sigma Parameters ---------- gdir : GlacierDirectory the glacier directory sigma_temp : float the standard deviation of the random timeseries (set to 0 for constant ts) sigma_prcp : float the standard deviation of the random timeseries (set to 0 for constant ts) seed : int the RandomState seed y0 : int the starting year of the timeseries to write. The default is to take the entire time period available in the file, but with this kwarg you can shorten it (to save space or to crop bad data) y1 : int the starting year of the timeseries to write. The default is to take the entire time period available in the file, but with this kwarg you can shorten it (to save space or to crop bad data) output_filesuffix : str this add a suffix to the output file (useful to avoid overwriting previous experiments) """ # read the climatology clfile = get_cru_cl_file() ncclim = salem.GeoNetcdf(clfile) # set temporal subset for the ts data (hydro years) sm = cfg.PARAMS['hydro_month_' + gdir.hemisphere] em = sm - 1 if (sm > 1) else 12 y0 = 1901 if y0 is None else y0 y1 = 2018 if y1 is None else y1 time = pd.date_range(start='{}-{:02d}-01'.format(y0, sm), end='{}-{:02d}-01'.format(y1, em), freq='MS') ny, r = divmod(len(time), 12) assert r == 0 lon = gdir.cenlon lat = gdir.cenlat # This is guaranteed to work because I prepared the file (I hope) ncclim.set_subset(corners=((lon, lat), (lon, lat)), margin=1) # get climatology data loc_hgt = ncclim.get_vardata('elev') loc_tmp = ncclim.get_vardata('temp') loc_pre = ncclim.get_vardata('prcp') loc_lon = ncclim.get_vardata('lon') loc_lat = ncclim.get_vardata('lat') # see if the center is ok if not np.isfinite(loc_hgt[1, 1]): # take another candidate where finite isok = np.isfinite(loc_hgt) # wait: some areas are entirely NaNs, make the subset larger _margin = 1 while not np.any(isok): _margin += 1 ncclim.set_subset(corners=((lon, lat), (lon, lat)), margin=_margin) loc_hgt = ncclim.get_vardata('elev') isok = np.isfinite(loc_hgt) if _margin > 1: log.debug('(%s) I had to look up for far climate pixels: %s', gdir.rgi_id, _margin) # Take the first candidate (doesn't matter which) lon, lat = ncclim.grid.ll_coordinates lon = lon[isok][0] lat = lat[isok][0] # Resubset ncclim.set_subset() ncclim.set_subset(corners=((lon, lat), (lon, lat)), margin=1) loc_hgt = ncclim.get_vardata('elev') loc_tmp = ncclim.get_vardata('temp') loc_pre = ncclim.get_vardata('prcp') loc_lon = ncclim.get_vardata('lon') loc_lat = ncclim.get_vardata('lat') assert np.isfinite(loc_hgt[1, 1]) isok = np.isfinite(loc_hgt) hgt_f = loc_hgt[isok].flatten() assert len(hgt_f) > 0. # Should we compute the gradient? use_grad = cfg.PARAMS['temp_use_local_gradient'] ts_grad = None if use_grad and len(hgt_f) >= 5: ts_grad = np.zeros(12) * np.NaN for i in range(12): loc_tmp_mth = loc_tmp[i, ...][isok].flatten() slope, _, _, p_val, _ = stats.linregress(hgt_f, loc_tmp_mth) ts_grad[i] = slope if (p_val < 0.01) else np.NaN # convert to a timeseries and hydrological years ts_grad = ts_grad.tolist() ts_grad = ts_grad[em:] + ts_grad[0:em] ts_grad = np.asarray(ts_grad * ny) # Make DataArrays rng = np.random.RandomState(seed) loc_tmp = xr.DataArray(loc_tmp[:, 1, 1], dims=['month'], coords={'month': np.arange(1, 13)}) ts_tmp = rng.randn(len(time)) * sigma_temp ts_tmp = xr.DataArray(ts_tmp, dims=['time'], coords={'time': time}) loc_pre = xr.DataArray(loc_pre[:, 1, 1], dims=['month'], coords={'month': np.arange(1, 13)}) ts_pre = utils.clip_min(rng.randn(len(time)) * sigma_prcp + 1, 0) ts_pre = xr.DataArray(ts_pre, dims=['time'], coords={'time': time}) # Create the time series ts_tmp = ts_tmp.groupby('time.month') + loc_tmp ts_pre = ts_pre.groupby('time.month') * loc_pre # done loc_hgt = loc_hgt[1, 1] loc_lon = loc_lon[1] loc_lat = loc_lat[1] assert np.isfinite(loc_hgt) gdir.write_monthly_climate_file(time, ts_pre.values, ts_tmp.values, loc_hgt, loc_lon, loc_lat, gradient=ts_grad, filesuffix=output_filesuffix, source='CRU CL2 and some randomness') ncclim._nc.close()
bsd-3-clause
mbalasso/mynumpy
numpy/linalg/linalg.py
8
62911
"""Lite version of scipy.linalg. Notes ----- This module is a lite version of the linalg.py module in SciPy which contains high-level Python interface to the LAPACK library. The lite version only accesses the following LAPACK functions: dgesv, zgesv, dgeev, zgeev, dgesdd, zgesdd, dgelsd, zgelsd, dsyevd, zheevd, dgetrf, zgetrf, dpotrf, zpotrf, dgeqrf, zgeqrf, zungqr, dorgqr. """ __all__ = ['matrix_power', 'solve', 'tensorsolve', 'tensorinv', 'inv', 'cholesky', 'eigvals', 'eigvalsh', 'pinv', 'slogdet', 'det', 'svd', 'eig', 'eigh','lstsq', 'norm', 'qr', 'cond', 'matrix_rank', 'LinAlgError'] from numpy.core import array, asarray, zeros, empty, transpose, \ intc, single, double, csingle, cdouble, inexact, complexfloating, \ newaxis, ravel, all, Inf, dot, add, multiply, identity, sqrt, \ maximum, flatnonzero, diagonal, arange, fastCopyAndTranspose, sum, \ isfinite, size, finfo, absolute, log, exp from numpy.lib import triu from numpy.linalg import lapack_lite from numpy.matrixlib.defmatrix import matrix_power from numpy.compat import asbytes # For Python2/3 compatibility _N = asbytes('N') _V = asbytes('V') _A = asbytes('A') _S = asbytes('S') _L = asbytes('L') fortran_int = intc # Error object class LinAlgError(Exception): """ Generic Python-exception-derived object raised by linalg functions. General purpose exception class, derived from Python's exception.Exception class, programmatically raised in linalg functions when a Linear Algebra-related condition would prevent further correct execution of the function. Parameters ---------- None Examples -------- >>> from numpy import linalg as LA >>> LA.inv(np.zeros((2,2))) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "...linalg.py", line 350, in inv return wrap(solve(a, identity(a.shape[0], dtype=a.dtype))) File "...linalg.py", line 249, in solve raise LinAlgError('Singular matrix') numpy.linalg.LinAlgError: Singular matrix """ pass def _makearray(a): new = asarray(a) wrap = getattr(a, "__array_prepare__", new.__array_wrap__) return new, wrap def isComplexType(t): return issubclass(t, complexfloating) _real_types_map = {single : single, double : double, csingle : single, cdouble : double} _complex_types_map = {single : csingle, double : cdouble, csingle : csingle, cdouble : cdouble} def _realType(t, default=double): return _real_types_map.get(t, default) def _complexType(t, default=cdouble): return _complex_types_map.get(t, default) def _linalgRealType(t): """Cast the type t to either double or cdouble.""" return double _complex_types_map = {single : csingle, double : cdouble, csingle : csingle, cdouble : cdouble} def _commonType(*arrays): # in lite version, use higher precision (always double or cdouble) result_type = single is_complex = False for a in arrays: if issubclass(a.dtype.type, inexact): if isComplexType(a.dtype.type): is_complex = True rt = _realType(a.dtype.type, default=None) if rt is None: # unsupported inexact scalar raise TypeError("array type %s is unsupported in linalg" % (a.dtype.name,)) else: rt = double if rt is double: result_type = double if is_complex: t = cdouble result_type = _complex_types_map[result_type] else: t = double return t, result_type # _fastCopyAndTranpose assumes the input is 2D (as all the calls in here are). _fastCT = fastCopyAndTranspose def _to_native_byte_order(*arrays): ret = [] for arr in arrays: if arr.dtype.byteorder not in ('=', '|'): ret.append(asarray(arr, dtype=arr.dtype.newbyteorder('='))) else: ret.append(arr) if len(ret) == 1: return ret[0] else: return ret def _fastCopyAndTranspose(type, *arrays): cast_arrays = () for a in arrays: if a.dtype.type is type: cast_arrays = cast_arrays + (_fastCT(a),) else: cast_arrays = cast_arrays + (_fastCT(a.astype(type)),) if len(cast_arrays) == 1: return cast_arrays[0] else: return cast_arrays def _assertRank2(*arrays): for a in arrays: if len(a.shape) != 2: raise LinAlgError('%d-dimensional array given. Array must be ' 'two-dimensional' % len(a.shape)) def _assertSquareness(*arrays): for a in arrays: if max(a.shape) != min(a.shape): raise LinAlgError('Array must be square') def _assertFinite(*arrays): for a in arrays: if not (isfinite(a).all()): raise LinAlgError("Array must not contain infs or NaNs") def _assertNonEmpty(*arrays): for a in arrays: if size(a) == 0: raise LinAlgError("Arrays cannot be empty") # Linear equations def tensorsolve(a, b, axes=None): """ Solve the tensor equation ``a x = b`` for x. It is assumed that all indices of `x` are summed over in the product, together with the rightmost indices of `a`, as is done in, for example, ``tensordot(a, x, axes=len(b.shape))``. Parameters ---------- a : array_like Coefficient tensor, of shape ``b.shape + Q``. `Q`, a tuple, equals the shape of that sub-tensor of `a` consisting of the appropriate number of its rightmost indices, and must be such that ``prod(Q) == prod(b.shape)`` (in which sense `a` is said to be 'square'). b : array_like Right-hand tensor, which can be of any shape. axes : tuple of ints, optional Axes in `a` to reorder to the right, before inversion. If None (default), no reordering is done. Returns ------- x : ndarray, shape Q Raises ------ LinAlgError If `a` is singular or not 'square' (in the above sense). See Also -------- tensordot, tensorinv, einsum Examples -------- >>> a = np.eye(2*3*4) >>> a.shape = (2*3, 4, 2, 3, 4) >>> b = np.random.randn(2*3, 4) >>> x = np.linalg.tensorsolve(a, b) >>> x.shape (2, 3, 4) >>> np.allclose(np.tensordot(a, x, axes=3), b) True """ a,wrap = _makearray(a) b = asarray(b) an = a.ndim if axes is not None: allaxes = range(0, an) for k in axes: allaxes.remove(k) allaxes.insert(an, k) a = a.transpose(allaxes) oldshape = a.shape[-(an-b.ndim):] prod = 1 for k in oldshape: prod *= k a = a.reshape(-1, prod) b = b.ravel() res = wrap(solve(a, b)) res.shape = oldshape return res def solve(a, b): """ Solve a linear matrix equation, or system of linear scalar equations. Computes the "exact" solution, `x`, of the well-determined, i.e., full rank, linear matrix equation `ax = b`. Parameters ---------- a : (M, M) array_like Coefficient matrix. b : {(M,), (M, N)}, array_like Ordinate or "dependent variable" values. Returns ------- x : {(M,), (M, N)} ndarray Solution to the system a x = b. Returned shape is identical to `b`. Raises ------ LinAlgError If `a` is singular or not square. Notes ----- `solve` is a wrapper for the LAPACK routines `dgesv`_ and `zgesv`_, the former being used if `a` is real-valued, the latter if it is complex-valued. The solution to the system of linear equations is computed using an LU decomposition [1]_ with partial pivoting and row interchanges. .. _dgesv: http://www.netlib.org/lapack/double/dgesv.f .. _zgesv: http://www.netlib.org/lapack/complex16/zgesv.f `a` must be square and of full-rank, i.e., all rows (or, equivalently, columns) must be linearly independent; if either is not true, use `lstsq` for the least-squares best "solution" of the system/equation. References ---------- .. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando, FL, Academic Press, Inc., 1980, pg. 22. Examples -------- Solve the system of equations ``3 * x0 + x1 = 9`` and ``x0 + 2 * x1 = 8``: >>> a = np.array([[3,1], [1,2]]) >>> b = np.array([9,8]) >>> x = np.linalg.solve(a, b) >>> x array([ 2., 3.]) Check that the solution is correct: >>> (np.dot(a, x) == b).all() True """ a, _ = _makearray(a) b, wrap = _makearray(b) one_eq = len(b.shape) == 1 if one_eq: b = b[:, newaxis] _assertRank2(a, b) _assertSquareness(a) n_eq = a.shape[0] n_rhs = b.shape[1] if n_eq != b.shape[0]: raise LinAlgError('Incompatible dimensions') t, result_t = _commonType(a, b) # lapack_routine = _findLapackRoutine('gesv', t) if isComplexType(t): lapack_routine = lapack_lite.zgesv else: lapack_routine = lapack_lite.dgesv a, b = _fastCopyAndTranspose(t, a, b) a, b = _to_native_byte_order(a, b) pivots = zeros(n_eq, fortran_int) results = lapack_routine(n_eq, n_rhs, a, n_eq, pivots, b, n_eq, 0) if results['info'] > 0: raise LinAlgError('Singular matrix') if one_eq: return wrap(b.ravel().astype(result_t)) else: return wrap(b.transpose().astype(result_t)) def tensorinv(a, ind=2): """ Compute the 'inverse' of an N-dimensional array. The result is an inverse for `a` relative to the tensordot operation ``tensordot(a, b, ind)``, i. e., up to floating-point accuracy, ``tensordot(tensorinv(a), a, ind)`` is the "identity" tensor for the tensordot operation. Parameters ---------- a : array_like Tensor to 'invert'. Its shape must be 'square', i. e., ``prod(a.shape[:ind]) == prod(a.shape[ind:])``. ind : int, optional Number of first indices that are involved in the inverse sum. Must be a positive integer, default is 2. Returns ------- b : ndarray `a`'s tensordot inverse, shape ``a.shape[:ind] + a.shape[ind:]``. Raises ------ LinAlgError If `a` is singular or not 'square' (in the above sense). See Also -------- tensordot, tensorsolve Examples -------- >>> a = np.eye(4*6) >>> a.shape = (4, 6, 8, 3) >>> ainv = np.linalg.tensorinv(a, ind=2) >>> ainv.shape (8, 3, 4, 6) >>> b = np.random.randn(4, 6) >>> np.allclose(np.tensordot(ainv, b), np.linalg.tensorsolve(a, b)) True >>> a = np.eye(4*6) >>> a.shape = (24, 8, 3) >>> ainv = np.linalg.tensorinv(a, ind=1) >>> ainv.shape (8, 3, 24) >>> b = np.random.randn(24) >>> np.allclose(np.tensordot(ainv, b, 1), np.linalg.tensorsolve(a, b)) True """ a = asarray(a) oldshape = a.shape prod = 1 if ind > 0: invshape = oldshape[ind:] + oldshape[:ind] for k in oldshape[ind:]: prod *= k else: raise ValueError("Invalid ind argument.") a = a.reshape(prod, -1) ia = inv(a) return ia.reshape(*invshape) # Matrix inversion def inv(a): """ Compute the (multiplicative) inverse of a matrix. Given a square matrix `a`, return the matrix `ainv` satisfying ``dot(a, ainv) = dot(ainv, a) = eye(a.shape[0])``. Parameters ---------- a : (M, M) array_like Matrix to be inverted. Returns ------- ainv : (M, M) ndarray or matrix (Multiplicative) inverse of the matrix `a`. Raises ------ LinAlgError If `a` is singular or not square. Examples -------- >>> from numpy import linalg as LA >>> a = np.array([[1., 2.], [3., 4.]]) >>> ainv = LA.inv(a) >>> np.allclose(np.dot(a, ainv), np.eye(2)) True >>> np.allclose(np.dot(ainv, a), np.eye(2)) True If a is a matrix object, then the return value is a matrix as well: >>> ainv = LA.inv(np.matrix(a)) >>> ainv matrix([[-2. , 1. ], [ 1.5, -0.5]]) """ a, wrap = _makearray(a) return wrap(solve(a, identity(a.shape[0], dtype=a.dtype))) # Cholesky decomposition def cholesky(a): """ Cholesky decomposition. Return the Cholesky decomposition, `L * L.H`, of the square matrix `a`, where `L` is lower-triangular and .H is the conjugate transpose operator (which is the ordinary transpose if `a` is real-valued). `a` must be Hermitian (symmetric if real-valued) and positive-definite. Only `L` is actually returned. Parameters ---------- a : (M, M) array_like Hermitian (symmetric if all elements are real), positive-definite input matrix. Returns ------- L : {(M, M) ndarray, (M, M) matrix} Lower-triangular Cholesky factor of `a`. Returns a matrix object if `a` is a matrix object. Raises ------ LinAlgError If the decomposition fails, for example, if `a` is not positive-definite. Notes ----- The Cholesky decomposition is often used as a fast way of solving .. math:: A \\mathbf{x} = \\mathbf{b} (when `A` is both Hermitian/symmetric and positive-definite). First, we solve for :math:`\\mathbf{y}` in .. math:: L \\mathbf{y} = \\mathbf{b}, and then for :math:`\\mathbf{x}` in .. math:: L.H \\mathbf{x} = \\mathbf{y}. Examples -------- >>> A = np.array([[1,-2j],[2j,5]]) >>> A array([[ 1.+0.j, 0.-2.j], [ 0.+2.j, 5.+0.j]]) >>> L = np.linalg.cholesky(A) >>> L array([[ 1.+0.j, 0.+0.j], [ 0.+2.j, 1.+0.j]]) >>> np.dot(L, L.T.conj()) # verify that L * L.H = A array([[ 1.+0.j, 0.-2.j], [ 0.+2.j, 5.+0.j]]) >>> A = [[1,-2j],[2j,5]] # what happens if A is only array_like? >>> np.linalg.cholesky(A) # an ndarray object is returned array([[ 1.+0.j, 0.+0.j], [ 0.+2.j, 1.+0.j]]) >>> # But a matrix object is returned if A is a matrix object >>> LA.cholesky(np.matrix(A)) matrix([[ 1.+0.j, 0.+0.j], [ 0.+2.j, 1.+0.j]]) """ a, wrap = _makearray(a) _assertRank2(a) _assertSquareness(a) t, result_t = _commonType(a) a = _fastCopyAndTranspose(t, a) a = _to_native_byte_order(a) m = a.shape[0] n = a.shape[1] if isComplexType(t): lapack_routine = lapack_lite.zpotrf else: lapack_routine = lapack_lite.dpotrf results = lapack_routine(_L, n, a, m, 0) if results['info'] > 0: raise LinAlgError('Matrix is not positive definite - ' 'Cholesky decomposition cannot be computed') s = triu(a, k=0).transpose() if (s.dtype != result_t): s = s.astype(result_t) return wrap(s) # QR decompostion def qr(a, mode='full'): """ Compute the qr factorization of a matrix. Factor the matrix `a` as *qr*, where `q` is orthonormal and `r` is upper-triangular. Parameters ---------- a : array_like Matrix to be factored, of shape (M, N). mode : {'full', 'r', 'economic'}, optional Specifies the values to be returned. 'full' is the default. Economic mode is slightly faster then 'r' mode if only `r` is needed. Returns ------- q : ndarray of float or complex, optional The orthonormal matrix, of shape (M, K). Only returned if ``mode='full'``. r : ndarray of float or complex, optional The upper-triangular matrix, of shape (K, N) with K = min(M, N). Only returned when ``mode='full'`` or ``mode='r'``. a2 : ndarray of float or complex, optional Array of shape (M, N), only returned when ``mode='economic``'. The diagonal and the upper triangle of `a2` contains `r`, while the rest of the matrix is undefined. Raises ------ LinAlgError If factoring fails. Notes ----- This is an interface to the LAPACK routines dgeqrf, zgeqrf, dorgqr, and zungqr. For more information on the qr factorization, see for example: http://en.wikipedia.org/wiki/QR_factorization Subclasses of `ndarray` are preserved, so if `a` is of type `matrix`, all the return values will be matrices too. Examples -------- >>> a = np.random.randn(9, 6) >>> q, r = np.linalg.qr(a) >>> np.allclose(a, np.dot(q, r)) # a does equal qr True >>> r2 = np.linalg.qr(a, mode='r') >>> r3 = np.linalg.qr(a, mode='economic') >>> np.allclose(r, r2) # mode='r' returns the same r as mode='full' True >>> # But only triu parts are guaranteed equal when mode='economic' >>> np.allclose(r, np.triu(r3[:6,:6], k=0)) True Example illustrating a common use of `qr`: solving of least squares problems What are the least-squares-best `m` and `y0` in ``y = y0 + mx`` for the following data: {(0,1), (1,0), (1,2), (2,1)}. (Graph the points and you'll see that it should be y0 = 0, m = 1.) The answer is provided by solving the over-determined matrix equation ``Ax = b``, where:: A = array([[0, 1], [1, 1], [1, 1], [2, 1]]) x = array([[y0], [m]]) b = array([[1], [0], [2], [1]]) If A = qr such that q is orthonormal (which is always possible via Gram-Schmidt), then ``x = inv(r) * (q.T) * b``. (In numpy practice, however, we simply use `lstsq`.) >>> A = np.array([[0, 1], [1, 1], [1, 1], [2, 1]]) >>> A array([[0, 1], [1, 1], [1, 1], [2, 1]]) >>> b = np.array([1, 0, 2, 1]) >>> q, r = LA.qr(A) >>> p = np.dot(q.T, b) >>> np.dot(LA.inv(r), p) array([ 1.1e-16, 1.0e+00]) """ a, wrap = _makearray(a) _assertRank2(a) _assertNonEmpty(a) m, n = a.shape t, result_t = _commonType(a) a = _fastCopyAndTranspose(t, a) a = _to_native_byte_order(a) mn = min(m, n) tau = zeros((mn,), t) if isComplexType(t): lapack_routine = lapack_lite.zgeqrf routine_name = 'zgeqrf' else: lapack_routine = lapack_lite.dgeqrf routine_name = 'dgeqrf' # calculate optimal size of work data 'work' lwork = 1 work = zeros((lwork,), t) results = lapack_routine(m, n, a, m, tau, work, -1, 0) if results['info'] != 0: raise LinAlgError('%s returns %d' % (routine_name, results['info'])) # do qr decomposition lwork = int(abs(work[0])) work = zeros((lwork,), t) results = lapack_routine(m, n, a, m, tau, work, lwork, 0) if results['info'] != 0: raise LinAlgError('%s returns %d' % (routine_name, results['info'])) # economic mode. Isn't actually economic. if mode[0] == 'e': if t != result_t : a = a.astype(result_t) return a.T # generate r r = _fastCopyAndTranspose(result_t, a[:,:mn]) for i in range(mn): r[i,:i].fill(0.0) # 'r'-mode, that is, calculate only r if mode[0] == 'r': return r # from here on: build orthonormal matrix q from a if isComplexType(t): lapack_routine = lapack_lite.zungqr routine_name = 'zungqr' else: lapack_routine = lapack_lite.dorgqr routine_name = 'dorgqr' # determine optimal lwork lwork = 1 work = zeros((lwork,), t) results = lapack_routine(m, mn, mn, a, m, tau, work, -1, 0) if results['info'] != 0: raise LinAlgError('%s returns %d' % (routine_name, results['info'])) # compute q lwork = int(abs(work[0])) work = zeros((lwork,), t) results = lapack_routine(m, mn, mn, a, m, tau, work, lwork, 0) if results['info'] != 0: raise LinAlgError('%s returns %d' % (routine_name, results['info'])) q = _fastCopyAndTranspose(result_t, a[:mn,:]) return wrap(q), wrap(r) # Eigenvalues def eigvals(a): """ Compute the eigenvalues of a general matrix. Main difference between `eigvals` and `eig`: the eigenvectors aren't returned. Parameters ---------- a : (M, M) array_like A complex- or real-valued matrix whose eigenvalues will be computed. Returns ------- w : (M,) ndarray The eigenvalues, each repeated according to its multiplicity. They are not necessarily ordered, nor are they necessarily real for real matrices. Raises ------ LinAlgError If the eigenvalue computation does not converge. See Also -------- eig : eigenvalues and right eigenvectors of general arrays eigvalsh : eigenvalues of symmetric or Hermitian arrays. eigh : eigenvalues and eigenvectors of symmetric/Hermitian arrays. Notes ----- This is a simple interface to the LAPACK routines dgeev and zgeev that sets those routines' flags to return only the eigenvalues of general real and complex arrays, respectively. Examples -------- Illustration, using the fact that the eigenvalues of a diagonal matrix are its diagonal elements, that multiplying a matrix on the left by an orthogonal matrix, `Q`, and on the right by `Q.T` (the transpose of `Q`), preserves the eigenvalues of the "middle" matrix. In other words, if `Q` is orthogonal, then ``Q * A * Q.T`` has the same eigenvalues as ``A``: >>> from numpy import linalg as LA >>> x = np.random.random() >>> Q = np.array([[np.cos(x), -np.sin(x)], [np.sin(x), np.cos(x)]]) >>> LA.norm(Q[0, :]), LA.norm(Q[1, :]), np.dot(Q[0, :],Q[1, :]) (1.0, 1.0, 0.0) Now multiply a diagonal matrix by Q on one side and by Q.T on the other: >>> D = np.diag((-1,1)) >>> LA.eigvals(D) array([-1., 1.]) >>> A = np.dot(Q, D) >>> A = np.dot(A, Q.T) >>> LA.eigvals(A) array([ 1., -1.]) """ a, wrap = _makearray(a) _assertRank2(a) _assertSquareness(a) _assertFinite(a) t, result_t = _commonType(a) real_t = _linalgRealType(t) a = _fastCopyAndTranspose(t, a) a = _to_native_byte_order(a) n = a.shape[0] dummy = zeros((1,), t) if isComplexType(t): lapack_routine = lapack_lite.zgeev w = zeros((n,), t) rwork = zeros((n,), real_t) lwork = 1 work = zeros((lwork,), t) results = lapack_routine(_N, _N, n, a, n, w, dummy, 1, dummy, 1, work, -1, rwork, 0) lwork = int(abs(work[0])) work = zeros((lwork,), t) results = lapack_routine(_N, _N, n, a, n, w, dummy, 1, dummy, 1, work, lwork, rwork, 0) else: lapack_routine = lapack_lite.dgeev wr = zeros((n,), t) wi = zeros((n,), t) lwork = 1 work = zeros((lwork,), t) results = lapack_routine(_N, _N, n, a, n, wr, wi, dummy, 1, dummy, 1, work, -1, 0) lwork = int(work[0]) work = zeros((lwork,), t) results = lapack_routine(_N, _N, n, a, n, wr, wi, dummy, 1, dummy, 1, work, lwork, 0) if all(wi == 0.): w = wr result_t = _realType(result_t) else: w = wr+1j*wi result_t = _complexType(result_t) if results['info'] > 0: raise LinAlgError('Eigenvalues did not converge') return w.astype(result_t) def eigvalsh(a, UPLO='L'): """ Compute the eigenvalues of a Hermitian or real symmetric matrix. Main difference from eigh: the eigenvectors are not computed. Parameters ---------- a : (M, M) array_like A complex- or real-valued matrix whose eigenvalues are to be computed. UPLO : {'L', 'U'}, optional Specifies whether the calculation is done with the lower triangular part of `a` ('L', default) or the upper triangular part ('U'). Returns ------- w : (M,) ndarray The eigenvalues, not necessarily ordered, each repeated according to its multiplicity. Raises ------ LinAlgError If the eigenvalue computation does not converge. See Also -------- eigh : eigenvalues and eigenvectors of symmetric/Hermitian arrays. eigvals : eigenvalues of general real or complex arrays. eig : eigenvalues and right eigenvectors of general real or complex arrays. Notes ----- This is a simple interface to the LAPACK routines dsyevd and zheevd that sets those routines' flags to return only the eigenvalues of real symmetric and complex Hermitian arrays, respectively. Examples -------- >>> from numpy import linalg as LA >>> a = np.array([[1, -2j], [2j, 5]]) >>> LA.eigvalsh(a) array([ 0.17157288+0.j, 5.82842712+0.j]) """ UPLO = asbytes(UPLO) a, wrap = _makearray(a) _assertRank2(a) _assertSquareness(a) t, result_t = _commonType(a) real_t = _linalgRealType(t) a = _fastCopyAndTranspose(t, a) a = _to_native_byte_order(a) n = a.shape[0] liwork = 5*n+3 iwork = zeros((liwork,), fortran_int) if isComplexType(t): lapack_routine = lapack_lite.zheevd w = zeros((n,), real_t) lwork = 1 work = zeros((lwork,), t) lrwork = 1 rwork = zeros((lrwork,), real_t) results = lapack_routine(_N, UPLO, n, a, n, w, work, -1, rwork, -1, iwork, liwork, 0) lwork = int(abs(work[0])) work = zeros((lwork,), t) lrwork = int(rwork[0]) rwork = zeros((lrwork,), real_t) results = lapack_routine(_N, UPLO, n, a, n, w, work, lwork, rwork, lrwork, iwork, liwork, 0) else: lapack_routine = lapack_lite.dsyevd w = zeros((n,), t) lwork = 1 work = zeros((lwork,), t) results = lapack_routine(_N, UPLO, n, a, n, w, work, -1, iwork, liwork, 0) lwork = int(work[0]) work = zeros((lwork,), t) results = lapack_routine(_N, UPLO, n, a, n, w, work, lwork, iwork, liwork, 0) if results['info'] > 0: raise LinAlgError('Eigenvalues did not converge') return w.astype(result_t) def _convertarray(a): t, result_t = _commonType(a) a = _fastCT(a.astype(t)) return a, t, result_t # Eigenvectors def eig(a): """ Compute the eigenvalues and right eigenvectors of a square array. Parameters ---------- a : (M, M) array_like A square array of real or complex elements. Returns ------- w : (M,) ndarray The eigenvalues, each repeated according to its multiplicity. The eigenvalues are not necessarily ordered, nor are they necessarily real for real arrays (though for real arrays complex-valued eigenvalues should occur in conjugate pairs). v : (M, M) ndarray The normalized (unit "length") eigenvectors, such that the column ``v[:,i]`` is the eigenvector corresponding to the eigenvalue ``w[i]``. Raises ------ LinAlgError If the eigenvalue computation does not converge. See Also -------- eigvalsh : eigenvalues of a symmetric or Hermitian (conjugate symmetric) array. eigvals : eigenvalues of a non-symmetric array. Notes ----- This is a simple interface to the LAPACK routines dgeev and zgeev which compute the eigenvalues and eigenvectors of, respectively, general real- and complex-valued square arrays. The number `w` is an eigenvalue of `a` if there exists a vector `v` such that ``dot(a,v) = w * v``. Thus, the arrays `a`, `w`, and `v` satisfy the equations ``dot(a[i,:], v[i]) = w[i] * v[:,i]`` for :math:`i \\in \\{0,...,M-1\\}`. The array `v` of eigenvectors may not be of maximum rank, that is, some of the columns may be linearly dependent, although round-off error may obscure that fact. If the eigenvalues are all different, then theoretically the eigenvectors are linearly independent. Likewise, the (complex-valued) matrix of eigenvectors `v` is unitary if the matrix `a` is normal, i.e., if ``dot(a, a.H) = dot(a.H, a)``, where `a.H` denotes the conjugate transpose of `a`. Finally, it is emphasized that `v` consists of the *right* (as in right-hand side) eigenvectors of `a`. A vector `y` satisfying ``dot(y.T, a) = z * y.T`` for some number `z` is called a *left* eigenvector of `a`, and, in general, the left and right eigenvectors of a matrix are not necessarily the (perhaps conjugate) transposes of each other. References ---------- G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando, FL, Academic Press, Inc., 1980, Various pp. Examples -------- >>> from numpy import linalg as LA (Almost) trivial example with real e-values and e-vectors. >>> w, v = LA.eig(np.diag((1, 2, 3))) >>> w; v array([ 1., 2., 3.]) array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) Real matrix possessing complex e-values and e-vectors; note that the e-values are complex conjugates of each other. >>> w, v = LA.eig(np.array([[1, -1], [1, 1]])) >>> w; v array([ 1. + 1.j, 1. - 1.j]) array([[ 0.70710678+0.j , 0.70710678+0.j ], [ 0.00000000-0.70710678j, 0.00000000+0.70710678j]]) Complex-valued matrix with real e-values (but complex-valued e-vectors); note that a.conj().T = a, i.e., a is Hermitian. >>> a = np.array([[1, 1j], [-1j, 1]]) >>> w, v = LA.eig(a) >>> w; v array([ 2.00000000e+00+0.j, 5.98651912e-36+0.j]) # i.e., {2, 0} array([[ 0.00000000+0.70710678j, 0.70710678+0.j ], [ 0.70710678+0.j , 0.00000000+0.70710678j]]) Be careful about round-off error! >>> a = np.array([[1 + 1e-9, 0], [0, 1 - 1e-9]]) >>> # Theor. e-values are 1 +/- 1e-9 >>> w, v = LA.eig(a) >>> w; v array([ 1., 1.]) array([[ 1., 0.], [ 0., 1.]]) """ a, wrap = _makearray(a) _assertRank2(a) _assertSquareness(a) _assertFinite(a) a, t, result_t = _convertarray(a) # convert to double or cdouble type a = _to_native_byte_order(a) real_t = _linalgRealType(t) n = a.shape[0] dummy = zeros((1,), t) if isComplexType(t): # Complex routines take different arguments lapack_routine = lapack_lite.zgeev w = zeros((n,), t) v = zeros((n, n), t) lwork = 1 work = zeros((lwork,), t) rwork = zeros((2*n,), real_t) results = lapack_routine(_N, _V, n, a, n, w, dummy, 1, v, n, work, -1, rwork, 0) lwork = int(abs(work[0])) work = zeros((lwork,), t) results = lapack_routine(_N, _V, n, a, n, w, dummy, 1, v, n, work, lwork, rwork, 0) else: lapack_routine = lapack_lite.dgeev wr = zeros((n,), t) wi = zeros((n,), t) vr = zeros((n, n), t) lwork = 1 work = zeros((lwork,), t) results = lapack_routine(_N, _V, n, a, n, wr, wi, dummy, 1, vr, n, work, -1, 0) lwork = int(work[0]) work = zeros((lwork,), t) results = lapack_routine(_N, _V, n, a, n, wr, wi, dummy, 1, vr, n, work, lwork, 0) if all(wi == 0.0): w = wr v = vr result_t = _realType(result_t) else: w = wr+1j*wi v = array(vr, w.dtype) ind = flatnonzero(wi != 0.0) # indices of complex e-vals for i in range(len(ind)//2): v[ind[2*i]] = vr[ind[2*i]] + 1j*vr[ind[2*i+1]] v[ind[2*i+1]] = vr[ind[2*i]] - 1j*vr[ind[2*i+1]] result_t = _complexType(result_t) if results['info'] > 0: raise LinAlgError('Eigenvalues did not converge') vt = v.transpose().astype(result_t) return w.astype(result_t), wrap(vt) def eigh(a, UPLO='L'): """ Return the eigenvalues and eigenvectors of a Hermitian or symmetric matrix. Returns two objects, a 1-D array containing the eigenvalues of `a`, and a 2-D square array or matrix (depending on the input type) of the corresponding eigenvectors (in columns). Parameters ---------- a : (M, M) array_like A complex Hermitian or real symmetric matrix. UPLO : {'L', 'U'}, optional Specifies whether the calculation is done with the lower triangular part of `a` ('L', default) or the upper triangular part ('U'). Returns ------- w : (M,) ndarray The eigenvalues, not necessarily ordered. v : {(M, M) ndarray, (M, M) matrix} The column ``v[:, i]`` is the normalized eigenvector corresponding to the eigenvalue ``w[i]``. Will return a matrix object if `a` is a matrix object. Raises ------ LinAlgError If the eigenvalue computation does not converge. See Also -------- eigvalsh : eigenvalues of symmetric or Hermitian arrays. eig : eigenvalues and right eigenvectors for non-symmetric arrays. eigvals : eigenvalues of non-symmetric arrays. Notes ----- This is a simple interface to the LAPACK routines dsyevd and zheevd, which compute the eigenvalues and eigenvectors of real symmetric and complex Hermitian arrays, respectively. The eigenvalues of real symmetric or complex Hermitian matrices are always real. [1]_ The array `v` of (column) eigenvectors is unitary and `a`, `w`, and `v` satisfy the equations ``dot(a, v[:, i]) = w[i] * v[:, i]``. References ---------- .. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando, FL, Academic Press, Inc., 1980, pg. 222. Examples -------- >>> from numpy import linalg as LA >>> a = np.array([[1, -2j], [2j, 5]]) >>> a array([[ 1.+0.j, 0.-2.j], [ 0.+2.j, 5.+0.j]]) >>> w, v = LA.eigh(a) >>> w; v array([ 0.17157288, 5.82842712]) array([[-0.92387953+0.j , -0.38268343+0.j ], [ 0.00000000+0.38268343j, 0.00000000-0.92387953j]]) >>> np.dot(a, v[:, 0]) - w[0] * v[:, 0] # verify 1st e-val/vec pair array([2.77555756e-17 + 0.j, 0. + 1.38777878e-16j]) >>> np.dot(a, v[:, 1]) - w[1] * v[:, 1] # verify 2nd e-val/vec pair array([ 0.+0.j, 0.+0.j]) >>> A = np.matrix(a) # what happens if input is a matrix object >>> A matrix([[ 1.+0.j, 0.-2.j], [ 0.+2.j, 5.+0.j]]) >>> w, v = LA.eigh(A) >>> w; v array([ 0.17157288, 5.82842712]) matrix([[-0.92387953+0.j , -0.38268343+0.j ], [ 0.00000000+0.38268343j, 0.00000000-0.92387953j]]) """ UPLO = asbytes(UPLO) a, wrap = _makearray(a) _assertRank2(a) _assertSquareness(a) t, result_t = _commonType(a) real_t = _linalgRealType(t) a = _fastCopyAndTranspose(t, a) a = _to_native_byte_order(a) n = a.shape[0] liwork = 5*n+3 iwork = zeros((liwork,), fortran_int) if isComplexType(t): lapack_routine = lapack_lite.zheevd w = zeros((n,), real_t) lwork = 1 work = zeros((lwork,), t) lrwork = 1 rwork = zeros((lrwork,), real_t) results = lapack_routine(_V, UPLO, n, a, n, w, work, -1, rwork, -1, iwork, liwork, 0) lwork = int(abs(work[0])) work = zeros((lwork,), t) lrwork = int(rwork[0]) rwork = zeros((lrwork,), real_t) results = lapack_routine(_V, UPLO, n, a, n, w, work, lwork, rwork, lrwork, iwork, liwork, 0) else: lapack_routine = lapack_lite.dsyevd w = zeros((n,), t) lwork = 1 work = zeros((lwork,), t) results = lapack_routine(_V, UPLO, n, a, n, w, work, -1, iwork, liwork, 0) lwork = int(work[0]) work = zeros((lwork,), t) results = lapack_routine(_V, UPLO, n, a, n, w, work, lwork, iwork, liwork, 0) if results['info'] > 0: raise LinAlgError('Eigenvalues did not converge') at = a.transpose().astype(result_t) return w.astype(_realType(result_t)), wrap(at) # Singular value decomposition def svd(a, full_matrices=1, compute_uv=1): """ Singular Value Decomposition. Factors the matrix `a` as ``u * np.diag(s) * v``, where `u` and `v` are unitary and `s` is a 1-d array of `a`'s singular values. Parameters ---------- a : array_like A real or complex matrix of shape (`M`, `N`) . full_matrices : bool, optional If True (default), `u` and `v` have the shapes (`M`, `M`) and (`N`, `N`), respectively. Otherwise, the shapes are (`M`, `K`) and (`K`, `N`), respectively, where `K` = min(`M`, `N`). compute_uv : bool, optional Whether or not to compute `u` and `v` in addition to `s`. True by default. Returns ------- u : ndarray Unitary matrix. The shape of `u` is (`M`, `M`) or (`M`, `K`) depending on value of ``full_matrices``. s : ndarray The singular values, sorted so that ``s[i] >= s[i+1]``. `s` is a 1-d array of length min(`M`, `N`). v : ndarray Unitary matrix of shape (`N`, `N`) or (`K`, `N`), depending on ``full_matrices``. Raises ------ LinAlgError If SVD computation does not converge. Notes ----- The SVD is commonly written as ``a = U S V.H``. The `v` returned by this function is ``V.H`` and ``u = U``. If ``U`` is a unitary matrix, it means that it satisfies ``U.H = inv(U)``. The rows of `v` are the eigenvectors of ``a.H a``. The columns of `u` are the eigenvectors of ``a a.H``. For row ``i`` in `v` and column ``i`` in `u`, the corresponding eigenvalue is ``s[i]**2``. If `a` is a `matrix` object (as opposed to an `ndarray`), then so are all the return values. Examples -------- >>> a = np.random.randn(9, 6) + 1j*np.random.randn(9, 6) Reconstruction based on full SVD: >>> U, s, V = np.linalg.svd(a, full_matrices=True) >>> U.shape, V.shape, s.shape ((9, 6), (6, 6), (6,)) >>> S = np.zeros((9, 6), dtype=complex) >>> S[:6, :6] = np.diag(s) >>> np.allclose(a, np.dot(U, np.dot(S, V))) True Reconstruction based on reduced SVD: >>> U, s, V = np.linalg.svd(a, full_matrices=False) >>> U.shape, V.shape, s.shape ((9, 6), (6, 6), (6,)) >>> S = np.diag(s) >>> np.allclose(a, np.dot(U, np.dot(S, V))) True """ a, wrap = _makearray(a) _assertRank2(a) _assertNonEmpty(a) m, n = a.shape t, result_t = _commonType(a) real_t = _linalgRealType(t) a = _fastCopyAndTranspose(t, a) a = _to_native_byte_order(a) s = zeros((min(n, m),), real_t) if compute_uv: if full_matrices: nu = m nvt = n option = _A else: nu = min(n, m) nvt = min(n, m) option = _S u = zeros((nu, m), t) vt = zeros((n, nvt), t) else: option = _N nu = 1 nvt = 1 u = empty((1, 1), t) vt = empty((1, 1), t) iwork = zeros((8*min(m, n),), fortran_int) if isComplexType(t): lapack_routine = lapack_lite.zgesdd lrwork = min(m,n)*max(5*min(m,n)+7, 2*max(m,n)+2*min(m,n)+1) rwork = zeros((lrwork,), real_t) lwork = 1 work = zeros((lwork,), t) results = lapack_routine(option, m, n, a, m, s, u, m, vt, nvt, work, -1, rwork, iwork, 0) lwork = int(abs(work[0])) work = zeros((lwork,), t) results = lapack_routine(option, m, n, a, m, s, u, m, vt, nvt, work, lwork, rwork, iwork, 0) else: lapack_routine = lapack_lite.dgesdd lwork = 1 work = zeros((lwork,), t) results = lapack_routine(option, m, n, a, m, s, u, m, vt, nvt, work, -1, iwork, 0) lwork = int(work[0]) work = zeros((lwork,), t) results = lapack_routine(option, m, n, a, m, s, u, m, vt, nvt, work, lwork, iwork, 0) if results['info'] > 0: raise LinAlgError('SVD did not converge') s = s.astype(_realType(result_t)) if compute_uv: u = u.transpose().astype(result_t) vt = vt.transpose().astype(result_t) return wrap(u), s, wrap(vt) else: return s def cond(x, p=None): """ Compute the condition number of a matrix. This function is capable of returning the condition number using one of seven different norms, depending on the value of `p` (see Parameters below). Parameters ---------- x : (M, N) array_like The matrix whose condition number is sought. p : {None, 1, -1, 2, -2, inf, -inf, 'fro'}, optional Order of the norm: ===== ============================ p norm for matrices ===== ============================ None 2-norm, computed directly using the ``SVD`` 'fro' Frobenius norm inf max(sum(abs(x), axis=1)) -inf min(sum(abs(x), axis=1)) 1 max(sum(abs(x), axis=0)) -1 min(sum(abs(x), axis=0)) 2 2-norm (largest sing. value) -2 smallest singular value ===== ============================ inf means the numpy.inf object, and the Frobenius norm is the root-of-sum-of-squares norm. Returns ------- c : {float, inf} The condition number of the matrix. May be infinite. See Also -------- numpy.linalg.norm Notes ----- The condition number of `x` is defined as the norm of `x` times the norm of the inverse of `x` [1]_; the norm can be the usual L2-norm (root-of-sum-of-squares) or one of a number of other matrix norms. References ---------- .. [1] G. Strang, *Linear Algebra and Its Applications*, Orlando, FL, Academic Press, Inc., 1980, pg. 285. Examples -------- >>> from numpy import linalg as LA >>> a = np.array([[1, 0, -1], [0, 1, 0], [1, 0, 1]]) >>> a array([[ 1, 0, -1], [ 0, 1, 0], [ 1, 0, 1]]) >>> LA.cond(a) 1.4142135623730951 >>> LA.cond(a, 'fro') 3.1622776601683795 >>> LA.cond(a, np.inf) 2.0 >>> LA.cond(a, -np.inf) 1.0 >>> LA.cond(a, 1) 2.0 >>> LA.cond(a, -1) 1.0 >>> LA.cond(a, 2) 1.4142135623730951 >>> LA.cond(a, -2) 0.70710678118654746 >>> min(LA.svd(a, compute_uv=0))*min(LA.svd(LA.inv(a), compute_uv=0)) 0.70710678118654746 """ x = asarray(x) # in case we have a matrix if p is None: s = svd(x,compute_uv=False) return s[0]/s[-1] else: return norm(x,p)*norm(inv(x),p) def matrix_rank(M, tol=None): """ Return matrix rank of array using SVD method Rank of the array is the number of SVD singular values of the array that are greater than `tol`. Parameters ---------- M : {(M,), (M, N)} array_like array of <=2 dimensions tol : {None, float}, optional threshold below which SVD values are considered zero. If `tol` is None, and ``S`` is an array with singular values for `M`, and ``eps`` is the epsilon value for datatype of ``S``, then `tol` is set to ``S.max() * max(M.shape) * eps``. Notes ----- The default threshold to detect rank deficiency is a test on the magnitude of the singular values of `M`. By default, we identify singular values less than ``S.max() * max(M.shape) * eps`` as indicating rank deficiency (with the symbols defined above). This is the algorithm MATLAB uses [1]. It also appears in *Numerical recipes* in the discussion of SVD solutions for linear least squares [2]. This default threshold is designed to detect rank deficiency accounting for the numerical errors of the SVD computation. Imagine that there is a column in `M` that is an exact (in floating point) linear combination of other columns in `M`. Computing the SVD on `M` will not produce a singular value exactly equal to 0 in general: any difference of the smallest SVD value from 0 will be caused by numerical imprecision in the calculation of the SVD. Our threshold for small SVD values takes this numerical imprecision into account, and the default threshold will detect such numerical rank deficiency. The threshold may declare a matrix `M` rank deficient even if the linear combination of some columns of `M` is not exactly equal to another column of `M` but only numerically very close to another column of `M`. We chose our default threshold because it is in wide use. Other thresholds are possible. For example, elsewhere in the 2007 edition of *Numerical recipes* there is an alternative threshold of ``S.max() * np.finfo(M.dtype).eps / 2. * np.sqrt(m + n + 1.)``. The authors describe this threshold as being based on "expected roundoff error" (p 71). The thresholds above deal with floating point roundoff error in the calculation of the SVD. However, you may have more information about the sources of error in `M` that would make you consider other tolerance values to detect *effective* rank deficiency. The most useful measure of the tolerance depends on the operations you intend to use on your matrix. For example, if your data come from uncertain measurements with uncertainties greater than floating point epsilon, choosing a tolerance near that uncertainty may be preferable. The tolerance may be absolute if the uncertainties are absolute rather than relative. References ---------- .. [1] MATLAB reference documention, "Rank" http://www.mathworks.com/help/techdoc/ref/rank.html .. [2] W. H. Press, S. A. Teukolsky, W. T. Vetterling and B. P. Flannery, "Numerical Recipes (3rd edition)", Cambridge University Press, 2007, page 795. Examples -------- >>> from numpy.linalg import matrix_rank >>> matrix_rank(np.eye(4)) # Full rank matrix 4 >>> I=np.eye(4); I[-1,-1] = 0. # rank deficient matrix >>> matrix_rank(I) 3 >>> matrix_rank(np.ones((4,))) # 1 dimension - rank 1 unless all 0 1 >>> matrix_rank(np.zeros((4,))) 0 """ M = asarray(M) if M.ndim > 2: raise TypeError('array should have 2 or fewer dimensions') if M.ndim < 2: return int(not all(M==0)) S = svd(M, compute_uv=False) if tol is None: tol = S.max() * max(M.shape) * finfo(S.dtype).eps return sum(S > tol) # Generalized inverse def pinv(a, rcond=1e-15 ): """ Compute the (Moore-Penrose) pseudo-inverse of a matrix. Calculate the generalized inverse of a matrix using its singular-value decomposition (SVD) and including all *large* singular values. Parameters ---------- a : (M, N) array_like Matrix to be pseudo-inverted. rcond : float Cutoff for small singular values. Singular values smaller (in modulus) than `rcond` * largest_singular_value (again, in modulus) are set to zero. Returns ------- B : (N, M) ndarray The pseudo-inverse of `a`. If `a` is a `matrix` instance, then so is `B`. Raises ------ LinAlgError If the SVD computation does not converge. Notes ----- The pseudo-inverse of a matrix A, denoted :math:`A^+`, is defined as: "the matrix that 'solves' [the least-squares problem] :math:`Ax = b`," i.e., if :math:`\\bar{x}` is said solution, then :math:`A^+` is that matrix such that :math:`\\bar{x} = A^+b`. It can be shown that if :math:`Q_1 \\Sigma Q_2^T = A` is the singular value decomposition of A, then :math:`A^+ = Q_2 \\Sigma^+ Q_1^T`, where :math:`Q_{1,2}` are orthogonal matrices, :math:`\\Sigma` is a diagonal matrix consisting of A's so-called singular values, (followed, typically, by zeros), and then :math:`\\Sigma^+` is simply the diagonal matrix consisting of the reciprocals of A's singular values (again, followed by zeros). [1]_ References ---------- .. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando, FL, Academic Press, Inc., 1980, pp. 139-142. Examples -------- The following example checks that ``a * a+ * a == a`` and ``a+ * a * a+ == a+``: >>> a = np.random.randn(9, 6) >>> B = np.linalg.pinv(a) >>> np.allclose(a, np.dot(a, np.dot(B, a))) True >>> np.allclose(B, np.dot(B, np.dot(a, B))) True """ a, wrap = _makearray(a) _assertNonEmpty(a) a = a.conjugate() u, s, vt = svd(a, 0) m = u.shape[0] n = vt.shape[1] cutoff = rcond*maximum.reduce(s) for i in range(min(n, m)): if s[i] > cutoff: s[i] = 1./s[i] else: s[i] = 0.; res = dot(transpose(vt), multiply(s[:, newaxis],transpose(u))) return wrap(res) # Determinant def slogdet(a): """ Compute the sign and (natural) logarithm of the determinant of an array. If an array has a very small or very large determinant, than a call to `det` may overflow or underflow. This routine is more robust against such issues, because it computes the logarithm of the determinant rather than the determinant itself. Parameters ---------- a : array_like Input array, has to be a square 2-D array. Returns ------- sign : float or complex A number representing the sign of the determinant. For a real matrix, this is 1, 0, or -1. For a complex matrix, this is a complex number with absolute value 1 (i.e., it is on the unit circle), or else 0. logdet : float The natural log of the absolute value of the determinant. If the determinant is zero, then `sign` will be 0 and `logdet` will be -Inf. In all cases, the determinant is equal to ``sign * np.exp(logdet)``. See Also -------- det Notes ----- The determinant is computed via LU factorization using the LAPACK routine z/dgetrf. .. versionadded:: 1.6.0. Examples -------- The determinant of a 2-D array ``[[a, b], [c, d]]`` is ``ad - bc``: >>> a = np.array([[1, 2], [3, 4]]) >>> (sign, logdet) = np.linalg.slogdet(a) >>> (sign, logdet) (-1, 0.69314718055994529) >>> sign * np.exp(logdet) -2.0 This routine succeeds where ordinary `det` does not: >>> np.linalg.det(np.eye(500) * 0.1) 0.0 >>> np.linalg.slogdet(np.eye(500) * 0.1) (1, -1151.2925464970228) """ a = asarray(a) _assertRank2(a) _assertSquareness(a) t, result_t = _commonType(a) a = _fastCopyAndTranspose(t, a) a = _to_native_byte_order(a) n = a.shape[0] if isComplexType(t): lapack_routine = lapack_lite.zgetrf else: lapack_routine = lapack_lite.dgetrf pivots = zeros((n,), fortran_int) results = lapack_routine(n, n, a, n, pivots, 0) info = results['info'] if (info < 0): raise TypeError("Illegal input to Fortran routine") elif (info > 0): return (t(0.0), _realType(t)(-Inf)) sign = 1. - 2. * (add.reduce(pivots != arange(1, n + 1)) % 2) d = diagonal(a) absd = absolute(d) sign *= multiply.reduce(d / absd) log(absd, absd) logdet = add.reduce(absd, axis=-1) return sign, logdet def det(a): """ Compute the determinant of an array. Parameters ---------- a : (M, M) array_like Input array. Returns ------- det : float Determinant of `a`. See Also -------- slogdet : Another way to representing the determinant, more suitable for large matrices where underflow/overflow may occur. Notes ----- The determinant is computed via LU factorization using the LAPACK routine z/dgetrf. Examples -------- The determinant of a 2-D array [[a, b], [c, d]] is ad - bc: >>> a = np.array([[1, 2], [3, 4]]) >>> np.linalg.det(a) -2.0 """ sign, logdet = slogdet(a) return sign * exp(logdet) # Linear Least Squares def lstsq(a, b, rcond=-1): """ Return the least-squares solution to a linear matrix equation. Solves the equation `a x = b` by computing a vector `x` that minimizes the Euclidean 2-norm `|| b - a x ||^2`. The equation may be under-, well-, or over- determined (i.e., the number of linearly independent rows of `a` can be less than, equal to, or greater than its number of linearly independent columns). If `a` is square and of full rank, then `x` (but for round-off error) is the "exact" solution of the equation. Parameters ---------- a : (M, N) array_like "Coefficient" matrix. b : {(M,), (M, K)} array_like Ordinate or "dependent variable" values. If `b` is two-dimensional, the least-squares solution is calculated for each of the `K` columns of `b`. rcond : float, optional Cut-off ratio for small singular values of `a`. Singular values are set to zero if they are smaller than `rcond` times the largest singular value of `a`. Returns ------- x : {(M,), (M, K)} ndarray Least-squares solution. The shape of `x` depends on the shape of `b`. residuals : {(), (1,), (K,)} ndarray Sums of residuals; squared Euclidean 2-norm for each column in ``b - a*x``. If the rank of `a` is < N or > M, this is an empty array. If `b` is 1-dimensional, this is a (1,) shape array. Otherwise the shape is (K,). rank : int Rank of matrix `a`. s : (min(M, N),) ndarray Singular values of `a`. Raises ------ LinAlgError If computation does not converge. Notes ----- If `b` is a matrix, then all array results are returned as matrices. Examples -------- Fit a line, ``y = mx + c``, through some noisy data-points: >>> x = np.array([0, 1, 2, 3]) >>> y = np.array([-1, 0.2, 0.9, 2.1]) By examining the coefficients, we see that the line should have a gradient of roughly 1 and cut the y-axis at, more or less, -1. We can rewrite the line equation as ``y = Ap``, where ``A = [[x 1]]`` and ``p = [[m], [c]]``. Now use `lstsq` to solve for `p`: >>> A = np.vstack([x, np.ones(len(x))]).T >>> A array([[ 0., 1.], [ 1., 1.], [ 2., 1.], [ 3., 1.]]) >>> m, c = np.linalg.lstsq(A, y)[0] >>> print m, c 1.0 -0.95 Plot the data along with the fitted line: >>> import matplotlib.pyplot as plt >>> plt.plot(x, y, 'o', label='Original data', markersize=10) >>> plt.plot(x, m*x + c, 'r', label='Fitted line') >>> plt.legend() >>> plt.show() """ import math a, _ = _makearray(a) b, wrap = _makearray(b) is_1d = len(b.shape) == 1 if is_1d: b = b[:, newaxis] _assertRank2(a, b) m = a.shape[0] n = a.shape[1] n_rhs = b.shape[1] ldb = max(n, m) if m != b.shape[0]: raise LinAlgError('Incompatible dimensions') t, result_t = _commonType(a, b) result_real_t = _realType(result_t) real_t = _linalgRealType(t) bstar = zeros((ldb, n_rhs), t) bstar[:b.shape[0],:n_rhs] = b.copy() a, bstar = _fastCopyAndTranspose(t, a, bstar) a, bstar = _to_native_byte_order(a, bstar) s = zeros((min(m, n),), real_t) nlvl = max( 0, int( math.log( float(min(m, n))/2. ) ) + 1 ) iwork = zeros((3*min(m, n)*nlvl+11*min(m, n),), fortran_int) if isComplexType(t): lapack_routine = lapack_lite.zgelsd lwork = 1 rwork = zeros((lwork,), real_t) work = zeros((lwork,), t) results = lapack_routine(m, n, n_rhs, a, m, bstar, ldb, s, rcond, 0, work, -1, rwork, iwork, 0) lwork = int(abs(work[0])) rwork = zeros((lwork,), real_t) a_real = zeros((m, n), real_t) bstar_real = zeros((ldb, n_rhs,), real_t) results = lapack_lite.dgelsd(m, n, n_rhs, a_real, m, bstar_real, ldb, s, rcond, 0, rwork, -1, iwork, 0) lrwork = int(rwork[0]) work = zeros((lwork,), t) rwork = zeros((lrwork,), real_t) results = lapack_routine(m, n, n_rhs, a, m, bstar, ldb, s, rcond, 0, work, lwork, rwork, iwork, 0) else: lapack_routine = lapack_lite.dgelsd lwork = 1 work = zeros((lwork,), t) results = lapack_routine(m, n, n_rhs, a, m, bstar, ldb, s, rcond, 0, work, -1, iwork, 0) lwork = int(work[0]) work = zeros((lwork,), t) results = lapack_routine(m, n, n_rhs, a, m, bstar, ldb, s, rcond, 0, work, lwork, iwork, 0) if results['info'] > 0: raise LinAlgError('SVD did not converge in Linear Least Squares') resids = array([], result_real_t) if is_1d: x = array(ravel(bstar)[:n], dtype=result_t, copy=True) if results['rank'] == n and m > n: if isComplexType(t): resids = array([sum(abs(ravel(bstar)[n:])**2)], dtype=result_real_t) else: resids = array([sum((ravel(bstar)[n:])**2)], dtype=result_real_t) else: x = array(transpose(bstar)[:n,:], dtype=result_t, copy=True) if results['rank'] == n and m > n: if isComplexType(t): resids = sum(abs(transpose(bstar)[n:,:])**2, axis=0).astype( result_real_t) else: resids = sum((transpose(bstar)[n:,:])**2, axis=0).astype( result_real_t) st = s[:min(n, m)].copy().astype(result_real_t) return wrap(x), wrap(resids), results['rank'], st def norm(x, ord=None): """ Matrix or vector norm. This function is able to return one of seven different matrix norms, or one of an infinite number of vector norms (described below), depending on the value of the ``ord`` parameter. Parameters ---------- x : {(M,), (M, N)} array_like Input array. ord : {non-zero int, inf, -inf, 'fro'}, optional Order of the norm (see table under ``Notes``). inf means numpy's `inf` object. Returns ------- n : float Norm of the matrix or vector. Notes ----- For values of ``ord <= 0``, the result is, strictly speaking, not a mathematical 'norm', but it may still be useful for various numerical purposes. The following norms can be calculated: ===== ============================ ========================== ord norm for matrices norm for vectors ===== ============================ ========================== None Frobenius norm 2-norm 'fro' Frobenius norm -- inf max(sum(abs(x), axis=1)) max(abs(x)) -inf min(sum(abs(x), axis=1)) min(abs(x)) 0 -- sum(x != 0) 1 max(sum(abs(x), axis=0)) as below -1 min(sum(abs(x), axis=0)) as below 2 2-norm (largest sing. value) as below -2 smallest singular value as below other -- sum(abs(x)**ord)**(1./ord) ===== ============================ ========================== The Frobenius norm is given by [1]_: :math:`||A||_F = [\\sum_{i,j} abs(a_{i,j})^2]^{1/2}` References ---------- .. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*, Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15 Examples -------- >>> from numpy import linalg as LA >>> a = np.arange(9) - 4 >>> a array([-4, -3, -2, -1, 0, 1, 2, 3, 4]) >>> b = a.reshape((3, 3)) >>> b array([[-4, -3, -2], [-1, 0, 1], [ 2, 3, 4]]) >>> LA.norm(a) 7.745966692414834 >>> LA.norm(b) 7.745966692414834 >>> LA.norm(b, 'fro') 7.745966692414834 >>> LA.norm(a, np.inf) 4 >>> LA.norm(b, np.inf) 9 >>> LA.norm(a, -np.inf) 0 >>> LA.norm(b, -np.inf) 2 >>> LA.norm(a, 1) 20 >>> LA.norm(b, 1) 7 >>> LA.norm(a, -1) -4.6566128774142013e-010 >>> LA.norm(b, -1) 6 >>> LA.norm(a, 2) 7.745966692414834 >>> LA.norm(b, 2) 7.3484692283495345 >>> LA.norm(a, -2) nan >>> LA.norm(b, -2) 1.8570331885190563e-016 >>> LA.norm(a, 3) 5.8480354764257312 >>> LA.norm(a, -3) nan """ x = asarray(x) if ord is None: # check the default case first and handle it immediately return sqrt(add.reduce((x.conj() * x).ravel().real)) nd = x.ndim if nd == 1: if ord == Inf: return abs(x).max() elif ord == -Inf: return abs(x).min() elif ord == 0: return (x != 0).sum() # Zero norm elif ord == 1: return abs(x).sum() # special case for speedup elif ord == 2: return sqrt(((x.conj()*x).real).sum()) # special case for speedup else: try: ord + 1 except TypeError: raise ValueError("Invalid norm order for vectors.") return ((abs(x)**ord).sum())**(1.0/ord) elif nd == 2: if ord == 2: return svd(x, compute_uv=0).max() elif ord == -2: return svd(x, compute_uv=0).min() elif ord == 1: return abs(x).sum(axis=0).max() elif ord == Inf: return abs(x).sum(axis=1).max() elif ord == -1: return abs(x).sum(axis=0).min() elif ord == -Inf: return abs(x).sum(axis=1).min() elif ord in ['fro','f']: return sqrt(add.reduce((x.conj() * x).real.ravel())) else: raise ValueError("Invalid norm order for matrices.") else: raise ValueError("Improper number of dimensions to norm.")
bsd-3-clause
openp2pdesign/makerlabs
makerlabs/hackaday_io.py
2
4767
# -*- encoding: utf-8 -*- # # Access data from hackaday.io # # Author: Massimo Menichinelli # Homepage: http://www.openp2pdesign.org # License: LGPL v.3 # # from classes import Lab import json import requests from geojson import dumps, Feature, Point, FeatureCollection from geopy.geocoders import Nominatim import pandas as pd # Geocoding variable geolocator = Nominatim() # Endpoints # The documented endpoint does not have coordinates, # the undocumented one has them, so for the moment we use the latter. # The undocumented endpoint does not need API keys or OAuth. # hackaday.io API documentation: # https://dev.hackaday.io/doc/api/get-pages # Register your app for the API key here: # https://dev.hackaday.io/applications client_id = "..." client_secret = "..." API_key = "..." # Documented endpoint for the list of hackerspaces hackaday_io_labs_api_url = "https://api.hackaday.io/v1/pages/hackerspaces?api_key=" + API_key # Undocumented endpoint for the map of hackerspaces hackaday_io_labs_map_url = "http://hackaday.io/api/location/hackerspaces" class Hackerspace(Lab): """Represents a Hackerspace as it is described on hackaday.io.""" def __init__(self): self.source = "hackaday.io" self.lab_type = "Hackerspace" def data_from_hackaday_io(endpoint): """Gets data from hackaday.io.""" data = requests.get(endpoint).json() return data def get_labs(format): """Gets Hackerspaces data from hackaday.io.""" hackerspaces_json = data_from_hackaday_io(hackaday_io_labs_map_url) hackerspaces = {} # Load all the Hackerspaces for i in hackerspaces_json: current_lab = Hackerspace() current_lab.id = i["id"] current_lab.url = "https://hackaday.io/hackerspace/" + current_lab.id current_lab.name = i["name"] if len(i["description"]) != 0: current_lab.description = i["description"] elif len(i["summary"]) != 0: current_lab.description = i["summary"] current_lab.created_at = i["moments"]["exact"] # Check if there are coordinates if i["latlon"] is not None: latlon = json.loads(i["latlon"]) current_lab.latitude = latlon["lat"] current_lab.longitude = latlon["lng"] # Get country, county and city from them country = geolocator.reverse( [latlon["lat"], latlon["lng"]]) current_lab.country = country.raw[ "address"]["country"] current_lab.address = country.raw["display_name"] current_lab.address_1 = country.raw["display_name"] current_lab.country_code = country.raw[ "address"]["country_code"] current_lab.county = country.raw[ "address"]["state_district"] current_lab.city = country.raw[ "address"]["city"] current_lab.postal_code = country.raw[ "address"]["postcode"] else: # For labs without a location or coordinates # add 0,0 as coordinates current_lab.latitude = 0.0 current_lab.longitude = 0.0 # Add the lab hackerspaces[i["name"]] = current_lab # Return a dictiornary / json if format.lower() == "dict" or format.lower() == "json": output = {} for j in hackerspaces: output[j] = hackerspaces[j].__dict__ # Return a geojson elif format.lower() == "geojson" or format.lower() == "geo": labs_list = [] for l in hackerspaces: single = hackerspaces[l].__dict__ single_lab = Feature( type="Feature", geometry=Point((single["latitude"], single["longitude"])), properties=single) labs_list.append(single_lab) output = dumps(FeatureCollection(labs_list)) # Return a Pandas DataFrame elif format.lower() == "pandas" or format.lower() == "dataframe": output = {} for j in hackerspaces: output[j] = hackerspaces[j].__dict__ # Transform the dict into a Pandas DataFrame output = pd.DataFrame.from_dict(output) output = output.transpose() # Return an object elif format.lower() == "object" or format.lower() == "obj": output = hackerspaces # Default: return an oject else: output = hackerspaces # Return a proper json if format.lower() == "json": output = json.dumps(output) return output def labs_count(): """Gets the number of current Hackerspaces listed on hackaday.io.""" hackerspaces = data_from_hackaday_io(hackaday_io_labs_api_url) return len(hackerspaces["labs"]) if __name__ == "__main__": pass
lgpl-3.0
mstrandgren/homology_ocr
figures.py
1
6408
import math import numpy as np import matplotlib.pyplot as plt import homology as hm import barcode as bc from data import * from utils import sparse_sample from plot_utils import * def run(): # ellipse_filtration() # ellipse_barcode() # p_tangents() # puv_curve() # rips_test() # delaunay_test() # alpha_test() # witness_test() # delaunay_vs_alpha() # triangulation_test() distance_test() # image_preprocessing() def ellipse_filtration(): vertices, edges = get_ellipse(16, .5) k = 4 r = 1 w = 0 # plot_edges(vertices, edges, plt, k = k, r = r, w = w) plot_filtration(vertices, edges, plt, N_s = vertices.shape[0], k = k, r = r, w = w) plt.tight_layout() plt.show() def ellipse_barcode(): vertices, edges = get_ellipse(16, .5) k = 4 r = 1 w = 0 # plot_edges(vertices, edges, plt, k = k, r = r, w = w) plot_barcode(vertices, edges, plt, N_s = vertices.shape[0], k = k, r = r, w = w) plt.tight_layout() plt.show() def p_tangents(): N = 500 N_s = 50 k = 50 r = .5 w = .6 vertices = get_image('P', 0, size=200, sample_size=N)[0] plot_tangents(vertices, plt, k = k) plt.show() def puv_curve(): N = 500 N_s = 50 k = 50 r = .5 w = .6 P = get_image('P', 0, size=200, sample_size=N)[0] U = get_image('U', 0, size=200, sample_size=N)[0] V = get_image('V', 0, size=200, sample_size=N)[0] f, ax = plt.subplots(1,3) plot_curve(P, ax[0], k = k, w = w) plot_curve(U, ax[1], k = k, w = w) plot_curve(V, ax[2], k = k, w = w) plt.show() def rips_test(): N = 500 N_s = 50 k = 50 w = .6 P = get_image('P', 0, size=200, sample_size=N)[0] f, ax = plt.subplots(1, 2) plot_triangulation(P, plt=ax[0], N_s = N_s, k = k, r = 0.80, w = w, triangulation='rips4') ax[0].set_title("Rips Tangent Complex") plot_triangulation(P, plt=ax[1], N_s = N_s, k = k, r = 0.4, w = w, triangulation='rips2') ax[1].set_title("Rips Vertex Complex") plt.show() def delaunay_test(): N = 500 N_s = 20 k = 50 r = .2 w = .6 P = get_image('P', 0, size=200, sample_size=N)[0] f, ax = plt.subplots(1, 2) plot_triangulation(P, plt=ax[0], N_s = N_s, k = k, r = r, w = w, triangulation='delaunay4') ax[0].set_title("Delaunay Triangulation of Tangent Space") plot_triangulation(P, plt=ax[1], N_s = N_s, k = k, r = r, w = w, triangulation='delaunay2') ax[1].set_title("Delaunay Triangulation of Vertex Space") plt.show() def alpha_test(): N = 500 N_s = 50 k = 50 w = .7 P = get_image('P', 0, size=200, sample_size=N)[0] f, ax = plt.subplots(1, 2) plot_triangulation(P, plt=ax[0], N_s = N_s, k = k, r = .6, w = w, triangulation='alpha4') ax[0].set_title("α Tangent Complex") plot_triangulation(P, plt=ax[1], N_s = N_s, k = k, r = .2, w = w, triangulation='alpha2') ax[1].set_title("α Vertex Complex") plt.show() def delaunay_vs_alpha(): N = 500 N_s = 20 k = 50 r = .4 w = .6 P = get_image('P', 0, size=200, sample_size=N)[0] f, ax = plt.subplots(1, 2) plot_triangulation(P, plt=ax[0], N_s = N_s, k = k, r = r, w = w, triangulation='delaunay2') ax[0].set_title("Delaunay Vertex Complex") plot_triangulation(P, plt=ax[1], N_s = N_s, k = k, r = r, w = w, triangulation='alpha2') ax[1].set_title("α Vertex Complex") plt.show() def witness_test(): N = 500 N_s = 50 k = 50 w = .7 P = get_image('P', 0, size=200, sample_size=N)[0] f, ax = plt.subplots(1, 2) plot_triangulation(P, plt=ax[0], N_s = N_s, k = k, r = 1, w = w, triangulation='witness4') ax[0].set_title("Witness Tangent Complex") plot_triangulation(P, plt=ax[1], N_s = N_s, k = k, r = 1, w = w, triangulation='witness2') ax[1].set_title("Witness Vertex Complex") plt.show() def triangulation_test(): N = 500 N_s = 30 k = 50 r = .4 w = .6 M = 3 letter = 'T' f, ax = plt.subplots(3, 3) for m in range(M): vs,_,_,original = get_image(letter, m, size=200, sample_size=N) ax[0][m].set_title("Original image") ax[0][m].imshow(original, cmap='binary') ax[0][m].set_xticks([]) ax[0][m].set_yticks([]) plot_triangulation(vs, plt=ax[1][m], N_s = N_s, k = k, r = .3, w = .7, triangulation='alpha2') ax[1][m].set_title("α Complex (2D)") std_plot(ax[1][m]) plot_triangulation(vs, plt=ax[2][m], N_s = N_s, k = k, r = .5, w = .7, triangulation='witness2') ax[2][m].set_title("Witness Complex (2D)") std_plot(ax[2][m]) plt.tight_layout() plt.show() def distance_test(): letters = 'ABCDE' L = len(letters) M = 5 N = 500 N_s = 50 k = int(N/5) w = .7 r = .5 triangulation = 'alpha4' barcodes = [] f, bax = plt.subplots(len(letters),M) f, iax = plt.subplots(len(letters),M) for i, letter in enumerate(letters): for j in range(0, M): print("Doing {0}-{1}".format(letter, j)) idx = i * M + j vertices = get_image(letter, j, size=100, sample_size=N)[0] v, t, c, e, simplices = hm.get_all(vertices, N_s = N_s, k = k, r = r, w = w, triangulation=triangulation) b = bc.get_barcode(simplices, degree_values=c[np.argsort(c)]) b = b[b[:, 2] == 0, :] # Only 1-bars barcodes.append(b) plot_barcode_gant(b, plt=bax[i][j]) bax[i][j] plot_edges(v, e, iax[i][j]) std_plot(iax[i][j]) print("Doing diffs...") M_b = len(barcodes) diffs = np.zeros([M_b,M_b]) inf = 1e14 for i in range(M_b): for j in range(M_b): diffs[i,j] = bc.barcode_diff(barcodes[i], barcodes[j], inf=inf) # print("Diff ({0},{1}) = {2:1.3f}".format(i, j, diffs[i,j])) plt.figure() plot_diffs(diffs, letters, plt) plt.show() def image_preprocessing(): N = 500 N_s = 30 sample, vertices, image, original = get_image('A', 1, size=200, sample_size=N) f, ax = plt.subplots(2,2, gridspec_kw = {'width_ratios':[1,1]}) ax[0][0].imshow(original, cmap='binary') ax[0][0].set_xticks([]) ax[0][0].set_yticks([]) ax[0][0].set_title("Original Image") ax[0][1].imshow(image, cmap='binary') ax[0][1].set_xticks([]) ax[0][1].set_yticks([]) ax[0][1].set_title("Scaled, Cropped & Thinned") ax[1][0].scatter(sample[:,0], sample[:,1], marker='.') ax[1][0].invert_yaxis() ax[1][0].set_xticks(np.arange(-1, 1.1)) ax[1][0].set_yticks(np.arange(-1, 1.1)) ax[1][0].set_title('Random Sampling') sparse_idx = sparse_sample(sample, N_s) sparse = sample[sparse_idx, :] ax[1][1].scatter(sparse[:,0], sparse[:,1], marker='.') ax[1][1].invert_yaxis() ax[1][1].set_xticks(np.arange(-1, 1.1)) ax[1][1].set_yticks(np.arange(-1, 1.1)) ax[1][1].set_title('Downsampled') plt.tight_layout() plt.show() if __name__ == "__main__": run()
mit
yukisakurai/hhana
mva/plotting/mpl.py
5
2144
import os from matplotlib import rc from matplotlib import cm def package_path(name): return os.path.splitext(os.path.abspath('latex/%s.sty' % name))[0] LATEX_PREAMBLE = ''' \usepackage[EULERGREEK]{%s} \sansmath ''' % package_path('sansmath') """ LATEX_PREAMBLE = ''' \usepackage[math-style=upright]{%s} ''' % package_path('unicode-math') """ #plt.rcParams['ps.useafm'] = True #rc('text', usetex=True) #rc('font', family='sans-serif') rc('text.latex', preamble=LATEX_PREAMBLE) #plt.rcParams['pdf.fonttype'] = 42 def set_colors(hists, colors='jet'): if isinstance(colors, basestring): colors = cm.get_cmap(colors, len(hists)) if hasattr(colors, '__call__'): for i, h in enumerate(hists): color = colors((i + 1) / float(len(hists) + 1)) h.SetColor(color) else: for h, color in izip(hists, colors): h.SetColor(color) def format_legend(l): #frame = l.get_frame() #frame.set_alpha(.8) #frame.set_fill(False) # eps does not support alpha values #frame.set_linewidth(0) for t in l.get_texts(): # left align all contents t.set_ha('left') l.get_title().set_ha("left") def root_axes(ax, xtick_formatter=None, xtick_locator=None, xtick_rotation=None, logy=False, integer=False, no_xlabels=False, vscale=1., bottom=None): #ax.patch.set_linewidth(2) if integer: ax.xaxis.set_major_locator( xtick_locator or MultipleLocator(1)) ax.tick_params(axis='x', which='minor', bottom='off', top='off') else: ax.xaxis.set_minor_locator(AutoMinorLocator()) if not logy: ax.yaxis.set_minor_locator(AutoMinorLocator()) if no_xlabels: ax.xaxis.set_major_formatter(NullFormatter()) elif xtick_formatter: ax.xaxis.set_major_formatter(xtick_formatter) if xtick_rotation is not None: plt.setp(ax.xaxis.get_majorticklabels(), rotation=xtick_rotation) ax.yaxis.set_label_coords(-0.13, 1.) ax.xaxis.set_label_coords(1., -0.15 / vscale)
gpl-3.0
tomchuk/dotfiles
.ipython/profile_default/ipython_config.py
1
20489
# Configuration file for ipython. c = get_config() #------------------------------------------------------------------------------ # InteractiveShellApp configuration #------------------------------------------------------------------------------ # A Mixin for applications that start InteractiveShell instances. # # Provides configurables for loading extensions and executing files as part of # configuring a Shell environment. # # The following methods should be called by the :meth:`initialize` method of the # subclass: # # - :meth:`init_path` # - :meth:`init_shell` (to be implemented by the subclass) # - :meth:`init_gui_pylab` # - :meth:`init_extensions` # - :meth:`init_code` # Execute the given command string. # c.InteractiveShellApp.code_to_run = '' # Pre-load matplotlib and numpy for interactive use, selecting a particular # matplotlib backend and loop integration. # c.InteractiveShellApp.pylab = None # Run the file referenced by the PYTHONSTARTUP environment variable at IPython # startup. # c.InteractiveShellApp.exec_PYTHONSTARTUP = True # lines of code to run at IPython startup. # c.InteractiveShellApp.exec_lines = [] # Enable GUI event loop integration with any of ('glut', 'gtk', 'gtk3', 'osx', # 'pyglet', 'qt', 'qt5', 'tk', 'wx'). # c.InteractiveShellApp.gui = None # Reraise exceptions encountered loading IPython extensions? # c.InteractiveShellApp.reraise_ipython_extension_failures = False # Configure matplotlib for interactive use with the default matplotlib backend. # c.InteractiveShellApp.matplotlib = None # If true, IPython will populate the user namespace with numpy, pylab, etc. and # an ``import *`` is done from numpy and pylab, when using pylab mode. # # When False, pylab mode should not import any names into the user namespace. # c.InteractiveShellApp.pylab_import_all = True # A list of dotted module names of IPython extensions to load. #c.InteractiveShellApp.extensions = [ # 'powerline.bindings.ipython.post_0_11' #] # Run the module as a script. # c.InteractiveShellApp.module_to_run = '' # Should variables loaded at startup (by startup files, exec_lines, etc.) be # hidden from tools like %who? # c.InteractiveShellApp.hide_initial_ns = True # dotted module name of an IPython extension to load. # c.InteractiveShellApp.extra_extension = '' # List of files to run at IPython startup. # c.InteractiveShellApp.exec_files = [] # A file to be run # c.InteractiveShellApp.file_to_run = '' #------------------------------------------------------------------------------ # TerminalIPythonApp configuration #------------------------------------------------------------------------------ # TerminalIPythonApp will inherit config from: BaseIPythonApplication, # Application, InteractiveShellApp # Run the file referenced by the PYTHONSTARTUP environment variable at IPython # startup. # c.TerminalIPythonApp.exec_PYTHONSTARTUP = True # Pre-load matplotlib and numpy for interactive use, selecting a particular # matplotlib backend and loop integration. # c.TerminalIPythonApp.pylab = None # Create a massive crash report when IPython encounters what may be an internal # error. The default is to append a short message to the usual traceback # c.TerminalIPythonApp.verbose_crash = False # Run the module as a script. # c.TerminalIPythonApp.module_to_run = '' # The date format used by logging formatters for %(asctime)s # c.TerminalIPythonApp.log_datefmt = '%Y-%m-%d %H:%M:%S' # Whether to overwrite existing config files when copying # c.TerminalIPythonApp.overwrite = False # Execute the given command string. # c.TerminalIPythonApp.code_to_run = '' # Set the log level by value or name. # c.TerminalIPythonApp.log_level = 30 # lines of code to run at IPython startup. # c.TerminalIPythonApp.exec_lines = [] # Suppress warning messages about legacy config files # c.TerminalIPythonApp.ignore_old_config = False # Path to an extra config file to load. # # If specified, load this config file in addition to any other IPython config. # c.TerminalIPythonApp.extra_config_file = u'' # Should variables loaded at startup (by startup files, exec_lines, etc.) be # hidden from tools like %who? # c.TerminalIPythonApp.hide_initial_ns = True # dotted module name of an IPython extension to load. # c.TerminalIPythonApp.extra_extension = '' # A file to be run # c.TerminalIPythonApp.file_to_run = '' # The IPython profile to use. # c.TerminalIPythonApp.profile = u'default' # Configure matplotlib for interactive use with the default matplotlib backend. # c.TerminalIPythonApp.matplotlib = None # If a command or file is given via the command-line, e.g. 'ipython foo.py', # start an interactive shell after executing the file or command. # c.TerminalIPythonApp.force_interact = False # If true, IPython will populate the user namespace with numpy, pylab, etc. and # an ``import *`` is done from numpy and pylab, when using pylab mode. # # When False, pylab mode should not import any names into the user namespace. # c.TerminalIPythonApp.pylab_import_all = True # The name of the IPython directory. This directory is used for logging # configuration (through profiles), history storage, etc. The default is usually # $HOME/.ipython. This option can also be specified through the environment # variable IPYTHONDIR. # c.TerminalIPythonApp.ipython_dir = u'' # Whether to display a banner upon starting IPython. # c.TerminalIPythonApp.display_banner = True # Whether to install the default config files into the profile dir. If a new # profile is being created, and IPython contains config files for that profile, # then they will be staged into the new directory. Otherwise, default config # files will be automatically generated. # c.TerminalIPythonApp.copy_config_files = False # List of files to run at IPython startup. # c.TerminalIPythonApp.exec_files = [] # Enable GUI event loop integration with any of ('glut', 'gtk', 'gtk3', 'osx', # 'pyglet', 'qt', 'qt5', 'tk', 'wx'). # c.TerminalIPythonApp.gui = None # Reraise exceptions encountered loading IPython extensions? # c.TerminalIPythonApp.reraise_ipython_extension_failures = False # A list of dotted module names of IPython extensions to load. # c.TerminalIPythonApp.extensions = [] # Start IPython quickly by skipping the loading of config files. # c.TerminalIPythonApp.quick = False # The Logging format template # c.TerminalIPythonApp.log_format = '[%(name)s]%(highlevel)s %(message)s' #------------------------------------------------------------------------------ # TerminalInteractiveShell configuration #------------------------------------------------------------------------------ # TerminalInteractiveShell will inherit config from: InteractiveShell # auto editing of files with syntax errors. # c.TerminalInteractiveShell.autoedit_syntax = False # Use colors for displaying information about objects. Because this information # is passed through a pager (like 'less'), and some pagers get confused with # color codes, this capability can be turned off. # c.TerminalInteractiveShell.color_info = True # A list of ast.NodeTransformer subclass instances, which will be applied to # user input before code is run. # c.TerminalInteractiveShell.ast_transformers = [] # c.TerminalInteractiveShell.history_length = 1000000 # Don't call post-execute functions that have failed in the past. # c.TerminalInteractiveShell.disable_failing_post_execute = False # Show rewritten input, e.g. for autocall. # c.TerminalInteractiveShell.show_rewritten_input = True # Set the color scheme (NoColor, Linux, or LightBG). # c.TerminalInteractiveShell.colors = 'LightBG' # If True, anything that would be passed to the pager will be displayed as # regular output instead. # c.TerminalInteractiveShell.display_page = False # Autoindent IPython code entered interactively. c.TerminalInteractiveShell.autoindent = True # # c.TerminalInteractiveShell.separate_in = '\n' # Deprecated, use PromptManager.in2_template # c.TerminalInteractiveShell.prompt_in2 = ' .\\D.: ' # # c.TerminalInteractiveShell.separate_out = '' # Deprecated, use PromptManager.in_template # c.TerminalInteractiveShell.prompt_in1 = 'In [\\#]: ' # Make IPython automatically call any callable object even if you didn't type # explicit parentheses. For example, 'str 43' becomes 'str(43)' automatically. # The value can be '0' to disable the feature, '1' for 'smart' autocall, where # it is not applied if there are no more arguments on the line, and '2' for # 'full' autocall, where all callable objects are automatically called (even if # no arguments are present). # c.TerminalInteractiveShell.autocall = 0 # Number of lines of your screen, used to control printing of very long strings. # Strings longer than this number of lines will be sent through a pager instead # of directly printed. The default value for this is 0, which means IPython # will auto-detect your screen size every time it needs to print certain # potentially long strings (this doesn't change the behavior of the 'print' # keyword, it's only triggered internally). If for some reason this isn't # working well (it needs curses support), specify it yourself. Otherwise don't # change the default. # c.TerminalInteractiveShell.screen_length = 0 # Set the editor used by IPython (default to $EDITOR/vi/notepad). c.TerminalInteractiveShell.editor = u'vim' # Deprecated, use PromptManager.justify # c.TerminalInteractiveShell.prompts_pad_left = True # The part of the banner to be printed before the profile # c.TerminalInteractiveShell.banner1 = 'Python 2.7.10 (default, Jun 29 2015, 18:33:04) \nType "copyright", "credits" or "license" for more information.\n\nIPython 3.2.0 -- An enhanced Interactive Python.\n? -> Introduction and overview of IPython\'s features.\n%quickref -> Quick reference.\nhelp -> Python\'s own help system.\nobject? -> Details about \'object\', use \'object??\' for extra details.\n' # # c.TerminalInteractiveShell.readline_parse_and_bind = ['tab: complete', '"\\C-l": clear-screen', 'set show-all-if-ambiguous on', '"\\C-o": tab-insert', '"\\C-r": reverse-search-history', '"\\C-s": forward-search-history', '"\\C-p": history-search-backward', '"\\C-n": history-search-forward', '"\\e[A": history-search-backward', '"\\e[B": history-search-forward', '"\\C-k": kill-line', '"\\C-u": unix-line-discard'] # The part of the banner to be printed after the profile # c.TerminalInteractiveShell.banner2 = '' # # c.TerminalInteractiveShell.separate_out2 = '' # # c.TerminalInteractiveShell.wildcards_case_sensitive = True # # c.TerminalInteractiveShell.debug = False # Set to confirm when you try to exit IPython with an EOF (Control-D in Unix, # Control-Z/Enter in Windows). By typing 'exit' or 'quit', you can force a # direct exit without any confirmation. c.TerminalInteractiveShell.confirm_exit = False # # c.TerminalInteractiveShell.ipython_dir = '' # # c.TerminalInteractiveShell.readline_remove_delims = '-/~' # Start logging to the default log file in overwrite mode. Use `logappend` to # specify a log file to **append** logs to. # c.TerminalInteractiveShell.logstart = False # The name of the logfile to use. # c.TerminalInteractiveShell.logfile = '' # The shell program to be used for paging. # c.TerminalInteractiveShell.pager = 'less' # Enable magic commands to be called without the leading %. # c.TerminalInteractiveShell.automagic = True # Save multi-line entries as one entry in readline history # c.TerminalInteractiveShell.multiline_history = True # # c.TerminalInteractiveShell.readline_use = True # Enable deep (recursive) reloading by default. IPython can use the deep_reload # module which reloads changes in modules recursively (it replaces the reload() # function, so you don't need to change anything to use it). deep_reload() # forces a full reload of modules whose code may have changed, which the default # reload() function does not. When deep_reload is off, IPython will use the # normal reload(), but deep_reload will still be available as dreload(). c.TerminalInteractiveShell.deep_reload = True # Start logging to the given file in append mode. Use `logfile` to specify a log # file to **overwrite** logs to. # c.TerminalInteractiveShell.logappend = '' # # c.TerminalInteractiveShell.xmode = 'Context' # # c.TerminalInteractiveShell.quiet = False # Enable auto setting the terminal title. c.TerminalInteractiveShell.term_title = True # # c.TerminalInteractiveShell.object_info_string_level = 0 # Deprecated, use PromptManager.out_template # c.TerminalInteractiveShell.prompt_out = 'Out[\\#]: ' # Set the size of the output cache. The default is 1000, you can change it # permanently in your config file. Setting it to 0 completely disables the # caching system, and the minimum value accepted is 20 (if you provide a value # less than 20, it is reset to 0 and a warning is issued). This limit is # defined because otherwise you'll spend more time re-flushing a too small cache # than working # c.TerminalInteractiveShell.cache_size = 1000 # 'all', 'last', 'last_expr' or 'none', specifying which nodes should be run # interactively (displaying output from expressions). # c.TerminalInteractiveShell.ast_node_interactivity = 'last_expr' # Automatically call the pdb debugger after every exception. # c.TerminalInteractiveShell.pdb = False c.TerminalInteractiveShell.editing_mode = 'vi' #------------------------------------------------------------------------------ # PromptManager configuration #------------------------------------------------------------------------------ # This is the primary interface for producing IPython's prompts. # Output prompt. '\#' will be transformed to the prompt number # c.PromptManager.out_template = 'Out[\\#]: ' # Continuation prompt. # c.PromptManager.in2_template = ' .\\D.: ' # If True (default), each prompt will be right-aligned with the preceding one. # c.PromptManager.justify = True # Input prompt. '\#' will be transformed to the prompt number # c.PromptManager.in_template = 'In [\\#]: ' # # c.PromptManager.color_scheme = 'Linux' #------------------------------------------------------------------------------ # HistoryManager configuration #------------------------------------------------------------------------------ # A class to organize all history-related functionality in one place. # HistoryManager will inherit config from: HistoryAccessor # Should the history database include output? (default: no) # c.HistoryManager.db_log_output = False # Write to database every x commands (higher values save disk access & power). # Values of 1 or less effectively disable caching. # c.HistoryManager.db_cache_size = 0 # Path to file to use for SQLite history database. # # By default, IPython will put the history database in the IPython profile # directory. If you would rather share one history among profiles, you can set # this value in each, so that they are consistent. # # Due to an issue with fcntl, SQLite is known to misbehave on some NFS mounts. # If you see IPython hanging, try setting this to something on a local disk, # e.g:: # # ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite # c.HistoryManager.hist_file = u'' # Options for configuring the SQLite connection # # These options are passed as keyword args to sqlite3.connect when establishing # database conenctions. # c.HistoryManager.connection_options = {} # enable the SQLite history # # set enabled=False to disable the SQLite history, in which case there will be # no stored history, no SQLite connection, and no background saving thread. # This may be necessary in some threaded environments where IPython is embedded. # c.HistoryManager.enabled = True #------------------------------------------------------------------------------ # ProfileDir configuration #------------------------------------------------------------------------------ # An object to manage the profile directory and its resources. # # The profile directory is used by all IPython applications, to manage # configuration, logging and security. # # This object knows how to find, create and manage these directories. This # should be used by any code that wants to handle profiles. # Set the profile location directly. This overrides the logic used by the # `profile` option. # c.ProfileDir.location = u'' #------------------------------------------------------------------------------ # PlainTextFormatter configuration #------------------------------------------------------------------------------ # The default pretty-printer. # # This uses :mod:`IPython.lib.pretty` to compute the format data of the object. # If the object cannot be pretty printed, :func:`repr` is used. See the # documentation of :mod:`IPython.lib.pretty` for details on how to write pretty # printers. Here is a simple example:: # # def dtype_pprinter(obj, p, cycle): # if cycle: # return p.text('dtype(...)') # if hasattr(obj, 'fields'): # if obj.fields is None: # p.text(repr(obj)) # else: # p.begin_group(7, 'dtype([') # for i, field in enumerate(obj.descr): # if i > 0: # p.text(',') # p.breakable() # p.pretty(field) # p.end_group(7, '])') # PlainTextFormatter will inherit config from: BaseFormatter # # c.PlainTextFormatter.type_printers = {} # Truncate large collections (lists, dicts, tuples, sets) to this size. # # Set to 0 to disable truncation. # c.PlainTextFormatter.max_seq_length = 1000 # # c.PlainTextFormatter.float_precision = '' # c.PlainTextFormatter.verbose = False # # c.PlainTextFormatter.deferred_printers = {} # # c.PlainTextFormatter.newline = '\n' # # c.PlainTextFormatter.max_width = 99 # c.PlainTextFormatter.pprint = True # # c.PlainTextFormatter.singleton_printers = {} #------------------------------------------------------------------------------ # IPCompleter configuration #------------------------------------------------------------------------------ # Extension of the completer class with IPython-specific features # IPCompleter will inherit config from: Completer # Instruct the completer to omit private method names # # Specifically, when completing on ``object.<tab>``. # # When 2 [default]: all names that start with '_' will be excluded. # # When 1: all 'magic' names (``__foo__``) will be excluded. # # When 0: nothing will be excluded. # c.IPCompleter.omit__names = 2 # Whether to merge completion results into a single list # # If False, only the completion results from the first non-empty completer will # be returned. # c.IPCompleter.merge_completions = True # Instruct the completer to use __all__ for the completion # # Specifically, when completing on ``object.<tab>``. # # When True: only those names in obj.__all__ will be included. # # When False [default]: the __all__ attribute is ignored # c.IPCompleter.limit_to__all__ = False # Activate greedy completion # # This will enable completion on elements of lists, results of function calls, # etc., but can be unsafe because the code is actually evaluated on TAB. # c.IPCompleter.greedy = False #------------------------------------------------------------------------------ # ScriptMagics configuration #------------------------------------------------------------------------------ # Magics for talking to scripts # # This defines a base `%%script` cell magic for running a cell with a program in # a subprocess, and registers a few top-level magics that call %%script with # common interpreters. # Extra script cell magics to define # # This generates simple wrappers of `%%script foo` as `%%foo`. # # If you want to add script magics that aren't on your path, specify them in # script_paths # c.ScriptMagics.script_magics = [] # Dict mapping short 'ruby' names to full paths, such as '/opt/secret/bin/ruby' # # Only necessary for items in script_magics where the default path will not find # the right interpreter. # c.ScriptMagics.script_paths = {} #------------------------------------------------------------------------------ # StoreMagics configuration #------------------------------------------------------------------------------ # Lightweight persistence for python variables. # # Provides the %store magic. # If True, any %store-d variables will be automatically restored when IPython # starts. c.StoreMagics.autorestore = True
mit
zrhans/pythonanywhere
.virtualenvs/django19/lib/python3.4/site-packages/matplotlib/pyplot.py
4
123649
# Note: The first part of this file can be modified in place, but the latter # part is autogenerated by the boilerplate.py script. """ Provides a MATLAB-like plotting framework. :mod:`~matplotlib.pylab` combines pyplot with numpy into a single namespace. This is convenient for interactive work, but for programming it is recommended that the namespaces be kept separate, e.g.:: import numpy as np import matplotlib.pyplot as plt x = np.arange(0, 5, 0.1); y = np.sin(x) plt.plot(x, y) """ from __future__ import (absolute_import, division, print_function, unicode_literals) from matplotlib.externals import six import sys import warnings import types from cycler import cycler import matplotlib import matplotlib.colorbar from matplotlib import style from matplotlib import _pylab_helpers, interactive from matplotlib.cbook import dedent, silent_list, is_string_like, is_numlike from matplotlib.cbook import _string_to_bool from matplotlib import docstring from matplotlib.backend_bases import FigureCanvasBase from matplotlib.figure import Figure, figaspect from matplotlib.gridspec import GridSpec from matplotlib.image import imread as _imread from matplotlib.image import imsave as _imsave from matplotlib import rcParams, rcParamsDefault, get_backend from matplotlib import rc_context from matplotlib.rcsetup import interactive_bk as _interactive_bk from matplotlib.artist import getp, get, Artist from matplotlib.artist import setp as _setp from matplotlib.axes import Axes, Subplot from matplotlib.projections import PolarAxes from matplotlib import mlab # for csv2rec, detrend_none, window_hanning from matplotlib.scale import get_scale_docs, get_scale_names from matplotlib import cm from matplotlib.cm import get_cmap, register_cmap import numpy as np # We may not need the following imports here: from matplotlib.colors import Normalize from matplotlib.lines import Line2D from matplotlib.text import Text, Annotation from matplotlib.patches import Polygon, Rectangle, Circle, Arrow from matplotlib.widgets import SubplotTool, Button, Slider, Widget from .ticker import TickHelper, Formatter, FixedFormatter, NullFormatter,\ FuncFormatter, FormatStrFormatter, ScalarFormatter,\ LogFormatter, LogFormatterExponent, LogFormatterMathtext,\ Locator, IndexLocator, FixedLocator, NullLocator,\ LinearLocator, LogLocator, AutoLocator, MultipleLocator,\ MaxNLocator ## Backend detection ## def _backend_selection(): """ If rcParams['backend_fallback'] is true, check to see if the current backend is compatible with the current running event loop, and if not switches to a compatible one. """ backend = rcParams['backend'] if not rcParams['backend_fallback'] or \ backend not in _interactive_bk: return is_agg_backend = rcParams['backend'].endswith('Agg') if 'wx' in sys.modules and not backend in ('WX', 'WXAgg'): import wx if wx.App.IsMainLoopRunning(): rcParams['backend'] = 'wx' + 'Agg' * is_agg_backend elif 'PyQt4.QtCore' in sys.modules and not backend == 'Qt4Agg': import PyQt4.QtGui if not PyQt4.QtGui.qApp.startingUp(): # The mainloop is running. rcParams['backend'] = 'qt4Agg' elif 'PyQt5.QtCore' in sys.modules and not backend == 'Qt5Agg': import PyQt5.QtWidgets if not PyQt5.QtWidgets.qApp.startingUp(): # The mainloop is running. rcParams['backend'] = 'qt5Agg' elif ('gtk' in sys.modules and backend not in ('GTK', 'GTKAgg', 'GTKCairo')): if 'gi' in sys.modules: from gi.repository import GObject ml = GObject.MainLoop else: import gobject ml = gobject.MainLoop if ml().is_running(): rcParams['backend'] = 'gtk' + 'Agg' * is_agg_backend elif 'Tkinter' in sys.modules and not backend == 'TkAgg': # import Tkinter pass # what if anything do we need to do for tkinter? _backend_selection() ## Global ## from matplotlib.backends import pylab_setup _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() _IP_REGISTERED = None _INSTALL_FIG_OBSERVER = False def install_repl_displayhook(): """ Install a repl display hook so that any stale figure are automatically redrawn when control is returned to the repl. This works with both IPython terminals and vanilla python shells. """ global _IP_REGISTERED global _INSTALL_FIG_OBSERVER class _NotIPython(Exception): pass # see if we have IPython hooks around, if use them try: if 'IPython' in sys.modules: from IPython import get_ipython ip = get_ipython() if ip is None: raise _NotIPython() if _IP_REGISTERED: return def post_execute(): if matplotlib.is_interactive(): draw_all() # IPython >= 2 try: ip.events.register('post_execute', post_execute) except AttributeError: # IPython 1.x ip.register_post_execute(post_execute) _IP_REGISTERED = post_execute _INSTALL_FIG_OBSERVER = False else: _INSTALL_FIG_OBSERVER = True # import failed or ipython is not running except (ImportError, _NotIPython): _INSTALL_FIG_OBSERVER = True def uninstall_repl_displayhook(): """ Uninstalls the matplotlib display hook. .. warning Need IPython >= 2 for this to work. For IPython < 2 will raise a ``NotImplementedError`` .. warning If you are using vanilla python and have installed another display hook this will reset ``sys.displayhook`` to what ever function was there when matplotlib installed it's displayhook, possibly discarding your changes. """ global _IP_REGISTERED global _INSTALL_FIG_OBSERVER if _IP_REGISTERED: from IPython import get_ipython ip = get_ipython() try: ip.events.unregister('post_execute', _IP_REGISTERED) except AttributeError: raise NotImplementedError("Can not unregister events " "in IPython < 2.0") _IP_REGISTERED = None if _INSTALL_FIG_OBSERVER: _INSTALL_FIG_OBSERVER = False draw_all = _pylab_helpers.Gcf.draw_all @docstring.copy_dedent(Artist.findobj) def findobj(o=None, match=None, include_self=True): if o is None: o = gcf() return o.findobj(match, include_self=include_self) def switch_backend(newbackend): """ Switch the default backend. This feature is **experimental**, and is only expected to work switching to an image backend. e.g., if you have a bunch of PostScript scripts that you want to run from an interactive ipython session, you may want to switch to the PS backend before running them to avoid having a bunch of GUI windows popup. If you try to interactively switch from one GUI backend to another, you will explode. Calling this command will close all open windows. """ close('all') global _backend_mod, new_figure_manager, draw_if_interactive, _show matplotlib.use(newbackend, warn=False, force=True) from matplotlib.backends import pylab_setup _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() def show(*args, **kw): """ Display a figure. When running in ipython with its pylab mode, display all figures and return to the ipython prompt. In non-interactive mode, display all figures and block until the figures have been closed; in interactive mode it has no effect unless figures were created prior to a change from non-interactive to interactive mode (not recommended). In that case it displays the figures but does not block. A single experimental keyword argument, *block*, may be set to True or False to override the blocking behavior described above. """ global _show return _show(*args, **kw) def isinteractive(): """ Return status of interactive mode. """ return matplotlib.is_interactive() def ioff(): 'Turn interactive mode off.' matplotlib.interactive(False) uninstall_repl_displayhook() def ion(): 'Turn interactive mode on.' matplotlib.interactive(True) install_repl_displayhook() def pause(interval): """ Pause for *interval* seconds. If there is an active figure it will be updated and displayed, and the GUI event loop will run during the pause. If there is no active figure, or if a non-interactive backend is in use, this executes time.sleep(interval). This can be used for crude animation. For more complex animation, see :mod:`matplotlib.animation`. This function is experimental; its behavior may be changed or extended in a future release. """ backend = rcParams['backend'] if backend in _interactive_bk: figManager = _pylab_helpers.Gcf.get_active() if figManager is not None: canvas = figManager.canvas if canvas.figure.stale: canvas.draw() show(block=False) canvas.start_event_loop(interval) return # No on-screen figure is active, so sleep() is all we need. import time time.sleep(interval) @docstring.copy_dedent(matplotlib.rc) def rc(*args, **kwargs): matplotlib.rc(*args, **kwargs) @docstring.copy_dedent(matplotlib.rc_context) def rc_context(rc=None, fname=None): return matplotlib.rc_context(rc, fname) @docstring.copy_dedent(matplotlib.rcdefaults) def rcdefaults(): matplotlib.rcdefaults() if matplotlib.is_interactive(): draw_all() # The current "image" (ScalarMappable) is retrieved or set # only via the pyplot interface using the following two # functions: def gci(): """ Get the current colorable artist. Specifically, returns the current :class:`~matplotlib.cm.ScalarMappable` instance (image or patch collection), or *None* if no images or patch collections have been defined. The commands :func:`~matplotlib.pyplot.imshow` and :func:`~matplotlib.pyplot.figimage` create :class:`~matplotlib.image.Image` instances, and the commands :func:`~matplotlib.pyplot.pcolor` and :func:`~matplotlib.pyplot.scatter` create :class:`~matplotlib.collections.Collection` instances. The current image is an attribute of the current axes, or the nearest earlier axes in the current figure that contains an image. """ return gcf()._gci() def sci(im): """ Set the current image. This image will be the target of colormap commands like :func:`~matplotlib.pyplot.jet`, :func:`~matplotlib.pyplot.hot` or :func:`~matplotlib.pyplot.clim`). The current image is an attribute of the current axes. """ gca()._sci(im) ## Any Artist ## # (getp is simply imported) @docstring.copy(_setp) def setp(*args, **kwargs): return _setp(*args, **kwargs) def xkcd(scale=1, length=100, randomness=2): """ Turns on `xkcd <http://xkcd.com/>`_ sketch-style drawing mode. This will only have effect on things drawn after this function is called. For best results, the "Humor Sans" font should be installed: it is not included with matplotlib. Parameters ---------- scale : float, optional The amplitude of the wiggle perpendicular to the source line. length : float, optional The length of the wiggle along the line. randomness : float, optional The scale factor by which the length is shrunken or expanded. Notes ----- This function works by a number of rcParams, so it will probably override others you have set before. If you want the effects of this function to be temporary, it can be used as a context manager, for example:: with plt.xkcd(): # This figure will be in XKCD-style fig1 = plt.figure() # ... # This figure will be in regular style fig2 = plt.figure() """ if rcParams['text.usetex']: raise RuntimeError( "xkcd mode is not compatible with text.usetex = True") from matplotlib import patheffects context = rc_context() try: rcParams['font.family'] = ['Humor Sans', 'Comic Sans MS'] rcParams['font.size'] = 14.0 rcParams['path.sketch'] = (scale, length, randomness) rcParams['path.effects'] = [ patheffects.withStroke(linewidth=4, foreground="w")] rcParams['axes.linewidth'] = 1.5 rcParams['lines.linewidth'] = 2.0 rcParams['figure.facecolor'] = 'white' rcParams['grid.linewidth'] = 0.0 rcParams['axes.grid'] = False rcParams['axes.unicode_minus'] = False rcParams['axes.prop_cycle'] = cycler('color', ['b', 'r', 'c', 'm']) rcParams['axes.edgecolor'] = 'black' rcParams['xtick.major.size'] = 8 rcParams['xtick.major.width'] = 3 rcParams['ytick.major.size'] = 8 rcParams['ytick.major.width'] = 3 except: context.__exit__(*sys.exc_info()) raise return context ## Figures ## def figure(num=None, # autoincrement if None, else integer from 1-N figsize=None, # defaults to rc figure.figsize dpi=None, # defaults to rc figure.dpi facecolor=None, # defaults to rc figure.facecolor edgecolor=None, # defaults to rc figure.edgecolor frameon=True, FigureClass=Figure, **kwargs ): """ Creates a new figure. Parameters ---------- num : integer or string, optional, default: none If not provided, a new figure will be created, and the figure number will be incremented. The figure objects holds this number in a `number` attribute. If num is provided, and a figure with this id already exists, make it active, and returns a reference to it. If this figure does not exists, create it and returns it. If num is a string, the window title will be set to this figure's `num`. figsize : tuple of integers, optional, default: None width, height in inches. If not provided, defaults to rc figure.figsize. dpi : integer, optional, default: None resolution of the figure. If not provided, defaults to rc figure.dpi. facecolor : the background color. If not provided, defaults to rc figure.facecolor edgecolor : the border color. If not provided, defaults to rc figure.edgecolor Returns ------- figure : Figure The Figure instance returned will also be passed to new_figure_manager in the backends, which allows to hook custom Figure classes into the pylab interface. Additional kwargs will be passed to the figure init function. Notes ----- If you are creating many figures, make sure you explicitly call "close" on the figures you are not using, because this will enable pylab to properly clean up the memory. rcParams defines the default values, which can be modified in the matplotlibrc file """ if figsize is None: figsize = rcParams['figure.figsize'] if dpi is None: dpi = rcParams['figure.dpi'] if facecolor is None: facecolor = rcParams['figure.facecolor'] if edgecolor is None: edgecolor = rcParams['figure.edgecolor'] allnums = get_fignums() next_num = max(allnums) + 1 if allnums else 1 figLabel = '' if num is None: num = next_num elif is_string_like(num): figLabel = num allLabels = get_figlabels() if figLabel not in allLabels: if figLabel == 'all': warnings.warn("close('all') closes all existing figures") num = next_num else: inum = allLabels.index(figLabel) num = allnums[inum] else: num = int(num) # crude validation of num argument figManager = _pylab_helpers.Gcf.get_fig_manager(num) if figManager is None: max_open_warning = rcParams['figure.max_open_warning'] if (max_open_warning >= 1 and len(allnums) >= max_open_warning): warnings.warn( "More than %d figures have been opened. Figures " "created through the pyplot interface " "(`matplotlib.pyplot.figure`) are retained until " "explicitly closed and may consume too much memory. " "(To control this warning, see the rcParam " "`figure.max_open_warning`)." % max_open_warning, RuntimeWarning) if get_backend().lower() == 'ps': dpi = 72 figManager = new_figure_manager(num, figsize=figsize, dpi=dpi, facecolor=facecolor, edgecolor=edgecolor, frameon=frameon, FigureClass=FigureClass, **kwargs) if figLabel: figManager.set_window_title(figLabel) figManager.canvas.figure.set_label(figLabel) # make this figure current on button press event def make_active(event): _pylab_helpers.Gcf.set_active(figManager) cid = figManager.canvas.mpl_connect('button_press_event', make_active) figManager._cidgcf = cid _pylab_helpers.Gcf.set_active(figManager) fig = figManager.canvas.figure fig.number = num # make sure backends (inline) that we don't ship that expect this # to be called in plotting commands to make the figure call show # still work. There is probably a better way to do this in the # FigureManager base class. if matplotlib.is_interactive(): draw_if_interactive() if _INSTALL_FIG_OBSERVER: fig.stale_callback = _auto_draw_if_interactive return figManager.canvas.figure def _auto_draw_if_interactive(fig, val): """ This is an internal helper function for making sure that auto-redrawing works as intended in the plain python repl. Parameters ---------- fig : Figure A figure object which is assumed to be associated with a canvas """ if val and matplotlib.is_interactive() and not fig.canvas.is_saving(): fig.canvas.draw_idle() def gcf(): "Get a reference to the current figure." figManager = _pylab_helpers.Gcf.get_active() if figManager is not None: return figManager.canvas.figure else: return figure() def fignum_exists(num): return _pylab_helpers.Gcf.has_fignum(num) or num in get_figlabels() def get_fignums(): """Return a list of existing figure numbers.""" fignums = list(six.iterkeys(_pylab_helpers.Gcf.figs)) fignums.sort() return fignums def get_figlabels(): "Return a list of existing figure labels." figManagers = _pylab_helpers.Gcf.get_all_fig_managers() figManagers.sort(key=lambda m: m.num) return [m.canvas.figure.get_label() for m in figManagers] def get_current_fig_manager(): figManager = _pylab_helpers.Gcf.get_active() if figManager is None: gcf() # creates an active figure as a side effect figManager = _pylab_helpers.Gcf.get_active() return figManager @docstring.copy_dedent(FigureCanvasBase.mpl_connect) def connect(s, func): return get_current_fig_manager().canvas.mpl_connect(s, func) @docstring.copy_dedent(FigureCanvasBase.mpl_disconnect) def disconnect(cid): return get_current_fig_manager().canvas.mpl_disconnect(cid) def close(*args): """ Close a figure window. ``close()`` by itself closes the current figure ``close(h)`` where *h* is a :class:`Figure` instance, closes that figure ``close(num)`` closes figure number *num* ``close(name)`` where *name* is a string, closes figure with that label ``close('all')`` closes all the figure windows """ if len(args) == 0: figManager = _pylab_helpers.Gcf.get_active() if figManager is None: return else: _pylab_helpers.Gcf.destroy(figManager.num) elif len(args) == 1: arg = args[0] if arg == 'all': _pylab_helpers.Gcf.destroy_all() elif isinstance(arg, six.integer_types): _pylab_helpers.Gcf.destroy(arg) elif hasattr(arg, 'int'): # if we are dealing with a type UUID, we # can use its integer representation _pylab_helpers.Gcf.destroy(arg.int) elif is_string_like(arg): allLabels = get_figlabels() if arg in allLabels: num = get_fignums()[allLabels.index(arg)] _pylab_helpers.Gcf.destroy(num) elif isinstance(arg, Figure): _pylab_helpers.Gcf.destroy_fig(arg) else: raise TypeError('Unrecognized argument type %s to close' % type(arg)) else: raise TypeError('close takes 0 or 1 arguments') def clf(): """ Clear the current figure. """ gcf().clf() def draw(): """Redraw the current figure. This is used in interactive mode to update a figure that has been altered, but not automatically re-drawn. This should be only rarely needed, but there may be ways to modify the state of a figure with out marking it as `stale`. Please report these cases as bugs. A more object-oriented alternative, given any :class:`~matplotlib.figure.Figure` instance, :attr:`fig`, that was created using a :mod:`~matplotlib.pyplot` function, is:: fig.canvas.draw_idle() """ get_current_fig_manager().canvas.draw_idle() @docstring.copy_dedent(Figure.savefig) def savefig(*args, **kwargs): fig = gcf() res = fig.savefig(*args, **kwargs) fig.canvas.draw_idle() # need this if 'transparent=True' to reset colors return res @docstring.copy_dedent(Figure.ginput) def ginput(*args, **kwargs): """ Blocking call to interact with the figure. This will wait for *n* clicks from the user and return a list of the coordinates of each click. If *timeout* is negative, does not timeout. """ return gcf().ginput(*args, **kwargs) @docstring.copy_dedent(Figure.waitforbuttonpress) def waitforbuttonpress(*args, **kwargs): """ Blocking call to interact with the figure. This will wait for *n* key or mouse clicks from the user and return a list containing True's for keyboard clicks and False's for mouse clicks. If *timeout* is negative, does not timeout. """ return gcf().waitforbuttonpress(*args, **kwargs) # Putting things in figures @docstring.copy_dedent(Figure.text) def figtext(*args, **kwargs): return gcf().text(*args, **kwargs) @docstring.copy_dedent(Figure.suptitle) def suptitle(*args, **kwargs): return gcf().suptitle(*args, **kwargs) @docstring.Appender("Addition kwargs: hold = [True|False] overrides default hold state", "\n") @docstring.copy_dedent(Figure.figimage) def figimage(*args, **kwargs): # allow callers to override the hold state by passing hold=True|False #sci(ret) # JDH figimage should not set current image -- it is not mappable, etc return gcf().figimage(*args, **kwargs) def figlegend(handles, labels, loc, **kwargs): """ Place a legend in the figure. *labels* a sequence of strings *handles* a sequence of :class:`~matplotlib.lines.Line2D` or :class:`~matplotlib.patches.Patch` instances *loc* can be a string or an integer specifying the legend location A :class:`matplotlib.legend.Legend` instance is returned. Example:: figlegend( (line1, line2, line3), ('label1', 'label2', 'label3'), 'upper right' ) .. seealso:: :func:`~matplotlib.pyplot.legend` """ return gcf().legend(handles, labels, loc, **kwargs) ## Figure and Axes hybrid ## def hold(b=None): """ Set the hold state. If *b* is None (default), toggle the hold state, else set the hold state to boolean value *b*:: hold() # toggle hold hold(True) # hold is on hold(False) # hold is off When *hold* is *True*, subsequent plot commands will be added to the current axes. When *hold* is *False*, the current axes and figure will be cleared on the next plot command. """ fig = gcf() ax = fig.gca() fig.hold(b) ax.hold(b) # b=None toggles the hold state, so let's get get the current hold # state; but should pyplot hold toggle the rc setting - me thinks # not b = ax.ishold() rc('axes', hold=b) def ishold(): """ Return the hold status of the current axes. """ return gca().ishold() def over(func, *args, **kwargs): """ Call a function with hold(True). Calls:: func(*args, **kwargs) with ``hold(True)`` and then restores the hold state. """ h = ishold() hold(True) func(*args, **kwargs) hold(h) ## Axes ## def axes(*args, **kwargs): """ Add an axes to the figure. The axes is added at position *rect* specified by: - ``axes()`` by itself creates a default full ``subplot(111)`` window axis. - ``axes(rect, axisbg='w')`` where *rect* = [left, bottom, width, height] in normalized (0, 1) units. *axisbg* is the background color for the axis, default white. - ``axes(h)`` where *h* is an axes instance makes *h* the current axis. An :class:`~matplotlib.axes.Axes` instance is returned. ======= ============== ============================================== kwarg Accepts Description ======= ============== ============================================== axisbg color the axes background color frameon [True|False] display the frame? sharex otherax current axes shares xaxis attribute with otherax sharey otherax current axes shares yaxis attribute with otherax polar [True|False] use a polar axes? aspect [str | num] ['equal', 'auto'] or a number. If a number the ratio of x-unit/y-unit in screen-space. Also see :meth:`~matplotlib.axes.Axes.set_aspect`. ======= ============== ============================================== Examples: * :file:`examples/pylab_examples/axes_demo.py` places custom axes. * :file:`examples/pylab_examples/shared_axis_demo.py` uses *sharex* and *sharey*. """ nargs = len(args) if len(args) == 0: return subplot(111, **kwargs) if nargs > 1: raise TypeError('Only one non keyword arg to axes allowed') arg = args[0] if isinstance(arg, Axes): a = gcf().sca(arg) else: rect = arg a = gcf().add_axes(rect, **kwargs) return a def delaxes(*args): """ Remove an axes from the current figure. If *ax* doesn't exist, an error will be raised. ``delaxes()``: delete the current axes """ if not len(args): ax = gca() else: ax = args[0] ret = gcf().delaxes(ax) return ret def sca(ax): """ Set the current Axes instance to *ax*. The current Figure is updated to the parent of *ax*. """ managers = _pylab_helpers.Gcf.get_all_fig_managers() for m in managers: if ax in m.canvas.figure.axes: _pylab_helpers.Gcf.set_active(m) m.canvas.figure.sca(ax) return raise ValueError("Axes instance argument was not found in a figure.") def gca(**kwargs): """ Get the current :class:`~matplotlib.axes.Axes` instance on the current figure matching the given keyword args, or create one. Examples --------- To get the current polar axes on the current figure:: plt.gca(projection='polar') If the current axes doesn't exist, or isn't a polar one, the appropriate axes will be created and then returned. See Also -------- matplotlib.figure.Figure.gca : The figure's gca method. """ return gcf().gca(**kwargs) # More ways of creating axes: def subplot(*args, **kwargs): """ Return a subplot axes positioned by the given grid definition. Typical call signature:: subplot(nrows, ncols, plot_number) Where *nrows* and *ncols* are used to notionally split the figure into ``nrows * ncols`` sub-axes, and *plot_number* is used to identify the particular subplot that this function is to create within the notional grid. *plot_number* starts at 1, increments across rows first and has a maximum of ``nrows * ncols``. In the case when *nrows*, *ncols* and *plot_number* are all less than 10, a convenience exists, such that the a 3 digit number can be given instead, where the hundreds represent *nrows*, the tens represent *ncols* and the units represent *plot_number*. For instance:: subplot(211) produces a subaxes in a figure which represents the top plot (i.e. the first) in a 2 row by 1 column notional grid (no grid actually exists, but conceptually this is how the returned subplot has been positioned). .. note:: Creating a new subplot with a position which is entirely inside a pre-existing axes will trigger the larger axes to be deleted:: import matplotlib.pyplot as plt # plot a line, implicitly creating a subplot(111) plt.plot([1,2,3]) # now create a subplot which represents the top plot of a grid # with 2 rows and 1 column. Since this subplot will overlap the # first, the plot (and its axes) previously created, will be removed plt.subplot(211) plt.plot(range(12)) plt.subplot(212, axisbg='y') # creates 2nd subplot with yellow background If you do not want this behavior, use the :meth:`~matplotlib.figure.Figure.add_subplot` method or the :func:`~matplotlib.pyplot.axes` function instead. Keyword arguments: *axisbg*: The background color of the subplot, which can be any valid color specifier. See :mod:`matplotlib.colors` for more information. *polar*: A boolean flag indicating whether the subplot plot should be a polar projection. Defaults to *False*. *projection*: A string giving the name of a custom projection to be used for the subplot. This projection must have been previously registered. See :mod:`matplotlib.projections`. .. seealso:: :func:`~matplotlib.pyplot.axes` For additional information on :func:`axes` and :func:`subplot` keyword arguments. :file:`examples/pie_and_polar_charts/polar_scatter_demo.py` For an example **Example:** .. plot:: mpl_examples/subplots_axes_and_figures/subplot_demo.py """ # if subplot called without arguments, create subplot(1,1,1) if len(args)==0: args=(1,1,1) # This check was added because it is very easy to type # subplot(1, 2, False) when subplots(1, 2, False) was intended # (sharex=False, that is). In most cases, no error will # ever occur, but mysterious behavior can result because what was # intended to be the sharex argument is instead treated as a # subplot index for subplot() if len(args) >= 3 and isinstance(args[2], bool) : warnings.warn("The subplot index argument to subplot() appears" " to be a boolean. Did you intend to use subplots()?") fig = gcf() a = fig.add_subplot(*args, **kwargs) bbox = a.bbox byebye = [] for other in fig.axes: if other==a: continue if bbox.fully_overlaps(other.bbox): byebye.append(other) for ax in byebye: delaxes(ax) return a def subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw): """ Create a figure with a set of subplots already made. This utility wrapper makes it convenient to create common layouts of subplots, including the enclosing figure object, in a single call. Keyword arguments: *nrows* : int Number of rows of the subplot grid. Defaults to 1. *ncols* : int Number of columns of the subplot grid. Defaults to 1. *sharex* : string or bool If *True*, the X axis will be shared amongst all subplots. If *True* and you have multiple rows, the x tick labels on all but the last row of plots will have visible set to *False* If a string must be one of "row", "col", "all", or "none". "all" has the same effect as *True*, "none" has the same effect as *False*. If "row", each subplot row will share a X axis. If "col", each subplot column will share a X axis and the x tick labels on all but the last row will have visible set to *False*. *sharey* : string or bool If *True*, the Y axis will be shared amongst all subplots. If *True* and you have multiple columns, the y tick labels on all but the first column of plots will have visible set to *False* If a string must be one of "row", "col", "all", or "none". "all" has the same effect as *True*, "none" has the same effect as *False*. If "row", each subplot row will share a Y axis and the y tick labels on all but the first column will have visible set to *False*. If "col", each subplot column will share a Y axis. *squeeze* : bool If *True*, extra dimensions are squeezed out from the returned axis object: - if only one subplot is constructed (nrows=ncols=1), the resulting single Axis object is returned as a scalar. - for Nx1 or 1xN subplots, the returned object is a 1-d numpy object array of Axis objects are returned as numpy 1-d arrays. - for NxM subplots with N>1 and M>1 are returned as a 2d array. If *False*, no squeezing at all is done: the returned axis object is always a 2-d array containing Axis instances, even if it ends up being 1x1. *subplot_kw* : dict Dict with keywords passed to the :meth:`~matplotlib.figure.Figure.add_subplot` call used to create each subplots. *gridspec_kw* : dict Dict with keywords passed to the :class:`~matplotlib.gridspec.GridSpec` constructor used to create the grid the subplots are placed on. *fig_kw* : dict Dict with keywords passed to the :func:`figure` call. Note that all keywords not recognized above will be automatically included here. Returns: fig, ax : tuple - *fig* is the :class:`matplotlib.figure.Figure` object - *ax* can be either a single axis object or an array of axis objects if more than one subplot was created. The dimensions of the resulting array can be controlled with the squeeze keyword, see above. Examples:: x = np.linspace(0, 2*np.pi, 400) y = np.sin(x**2) # Just a figure and one subplot f, ax = plt.subplots() ax.plot(x, y) ax.set_title('Simple plot') # Two subplots, unpack the output array immediately f, (ax1, ax2) = plt.subplots(1, 2, sharey=True) ax1.plot(x, y) ax1.set_title('Sharing Y axis') ax2.scatter(x, y) # Four polar axes plt.subplots(2, 2, subplot_kw=dict(polar=True)) # Share a X axis with each column of subplots plt.subplots(2, 2, sharex='col') # Share a Y axis with each row of subplots plt.subplots(2, 2, sharey='row') # Share a X and Y axis with all subplots plt.subplots(2, 2, sharex='all', sharey='all') # same as plt.subplots(2, 2, sharex=True, sharey=True) """ # for backwards compatibility if isinstance(sharex, bool): if sharex: sharex = "all" else: sharex = "none" if isinstance(sharey, bool): if sharey: sharey = "all" else: sharey = "none" share_values = ["all", "row", "col", "none"] if sharex not in share_values: # This check was added because it is very easy to type # `subplots(1, 2, 1)` when `subplot(1, 2, 1)` was intended. # In most cases, no error will ever occur, but mysterious behavior will # result because what was intended to be the subplot index is instead # treated as a bool for sharex. if isinstance(sharex, int): warnings.warn("sharex argument to subplots() was an integer." " Did you intend to use subplot() (without 's')?") raise ValueError("sharex [%s] must be one of %s" % (sharex, share_values)) if sharey not in share_values: raise ValueError("sharey [%s] must be one of %s" % (sharey, share_values)) if subplot_kw is None: subplot_kw = {} if gridspec_kw is None: gridspec_kw = {} fig = figure(**fig_kw) gs = GridSpec(nrows, ncols, **gridspec_kw) # Create empty object array to hold all axes. It's easiest to make it 1-d # so we can just append subplots upon creation, and then nplots = nrows*ncols axarr = np.empty(nplots, dtype=object) # Create first subplot separately, so we can share it if requested ax0 = fig.add_subplot(gs[0, 0], **subplot_kw) axarr[0] = ax0 r, c = np.mgrid[:nrows, :ncols] r = r.flatten() * ncols c = c.flatten() lookup = { "none": np.arange(nplots), "all": np.zeros(nplots, dtype=int), "row": r, "col": c, } sxs = lookup[sharex] sys = lookup[sharey] # Note off-by-one counting because add_subplot uses the MATLAB 1-based # convention. for i in range(1, nplots): if sxs[i] == i: subplot_kw['sharex'] = None else: subplot_kw['sharex'] = axarr[sxs[i]] if sys[i] == i: subplot_kw['sharey'] = None else: subplot_kw['sharey'] = axarr[sys[i]] axarr[i] = fig.add_subplot(gs[i // ncols, i % ncols], **subplot_kw) # returned axis array will be always 2-d, even if nrows=ncols=1 axarr = axarr.reshape(nrows, ncols) # turn off redundant tick labeling if sharex in ["col", "all"] and nrows > 1: # turn off all but the bottom row for ax in axarr[:-1, :].flat: for label in ax.get_xticklabels(): label.set_visible(False) ax.xaxis.offsetText.set_visible(False) if sharey in ["row", "all"] and ncols > 1: # turn off all but the first column for ax in axarr[:, 1:].flat: for label in ax.get_yticklabels(): label.set_visible(False) ax.yaxis.offsetText.set_visible(False) if squeeze: # Reshape the array to have the final desired dimension (nrow,ncol), # though discarding unneeded dimensions that equal 1. If we only have # one subplot, just return it instead of a 1-element array. if nplots == 1: ret = fig, axarr[0, 0] else: ret = fig, axarr.squeeze() else: # returned axis array will be always 2-d, even if nrows=ncols=1 ret = fig, axarr.reshape(nrows, ncols) return ret def subplot2grid(shape, loc, rowspan=1, colspan=1, **kwargs): """ Create a subplot in a grid. The grid is specified by *shape*, at location of *loc*, spanning *rowspan*, *colspan* cells in each direction. The index for loc is 0-based. :: subplot2grid(shape, loc, rowspan=1, colspan=1) is identical to :: gridspec=GridSpec(shape[0], shape[1]) subplotspec=gridspec.new_subplotspec(loc, rowspan, colspan) subplot(subplotspec) """ fig = gcf() s1, s2 = shape subplotspec = GridSpec(s1, s2).new_subplotspec(loc, rowspan=rowspan, colspan=colspan) a = fig.add_subplot(subplotspec, **kwargs) bbox = a.bbox byebye = [] for other in fig.axes: if other == a: continue if bbox.fully_overlaps(other.bbox): byebye.append(other) for ax in byebye: delaxes(ax) return a def twinx(ax=None): """ Make a second axes that shares the *x*-axis. The new axes will overlay *ax* (or the current axes if *ax* is *None*). The ticks for *ax2* will be placed on the right, and the *ax2* instance is returned. .. seealso:: :file:`examples/api_examples/two_scales.py` For an example """ if ax is None: ax=gca() ax1 = ax.twinx() return ax1 def twiny(ax=None): """ Make a second axes that shares the *y*-axis. The new axis will overlay *ax* (or the current axes if *ax* is *None*). The ticks for *ax2* will be placed on the top, and the *ax2* instance is returned. """ if ax is None: ax=gca() ax1 = ax.twiny() return ax1 def subplots_adjust(*args, **kwargs): """ Tune the subplot layout. call signature:: subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None) The parameter meanings (and suggested defaults) are:: left = 0.125 # the left side of the subplots of the figure right = 0.9 # the right side of the subplots of the figure bottom = 0.1 # the bottom of the subplots of the figure top = 0.9 # the top of the subplots of the figure wspace = 0.2 # the amount of width reserved for blank space between subplots hspace = 0.2 # the amount of height reserved for white space between subplots The actual defaults are controlled by the rc file """ fig = gcf() fig.subplots_adjust(*args, **kwargs) def subplot_tool(targetfig=None): """ Launch a subplot tool window for a figure. A :class:`matplotlib.widgets.SubplotTool` instance is returned. """ tbar = rcParams['toolbar'] # turn off the navigation toolbar for the toolfig rcParams['toolbar'] = 'None' if targetfig is None: manager = get_current_fig_manager() targetfig = manager.canvas.figure else: # find the manager for this figure for manager in _pylab_helpers.Gcf._activeQue: if manager.canvas.figure==targetfig: break else: raise RuntimeError('Could not find manager for targetfig') toolfig = figure(figsize=(6,3)) toolfig.subplots_adjust(top=0.9) ret = SubplotTool(targetfig, toolfig) rcParams['toolbar'] = tbar _pylab_helpers.Gcf.set_active(manager) # restore the current figure return ret def tight_layout(pad=1.08, h_pad=None, w_pad=None, rect=None): """ Automatically adjust subplot parameters to give specified padding. Parameters: pad : float padding between the figure edge and the edges of subplots, as a fraction of the font-size. h_pad, w_pad : float padding (height/width) between edges of adjacent subplots. Defaults to `pad_inches`. rect : if rect is given, it is interpreted as a rectangle (left, bottom, right, top) in the normalized figure coordinate that the whole subplots area (including labels) will fit into. Default is (0, 0, 1, 1). """ fig = gcf() fig.tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect) def box(on=None): """ Turn the axes box on or off. *on* may be a boolean or a string, 'on' or 'off'. If *on* is *None*, toggle state. """ ax = gca() on = _string_to_bool(on) if on is None: on = not ax.get_frame_on() ax.set_frame_on(on) def title(s, *args, **kwargs): """ Set a title of the current axes. Set one of the three available axes titles. The available titles are positioned above the axes in the center, flush with the left edge, and flush with the right edge. .. seealso:: See :func:`~matplotlib.pyplot.text` for adding text to the current axes Parameters ---------- label : str Text to use for the title fontdict : dict A dictionary controlling the appearance of the title text, the default `fontdict` is: {'fontsize': rcParams['axes.titlesize'], 'fontweight' : rcParams['axes.titleweight'], 'verticalalignment': 'baseline', 'horizontalalignment': loc} loc : {'center', 'left', 'right'}, str, optional Which title to set, defaults to 'center' Returns ------- text : :class:`~matplotlib.text.Text` The matplotlib text instance representing the title Other parameters ---------------- kwargs : text properties Other keyword arguments are text properties, see :class:`~matplotlib.text.Text` for a list of valid text properties. """ return gca().set_title(s, *args, **kwargs) ## Axis ## def axis(*v, **kwargs): """ Convenience method to get or set axis properties. Calling with no arguments:: >>> axis() returns the current axes limits ``[xmin, xmax, ymin, ymax]``.:: >>> axis(v) sets the min and max of the x and y axes, with ``v = [xmin, xmax, ymin, ymax]``.:: >>> axis('off') turns off the axis lines and labels.:: >>> axis('equal') changes limits of *x* or *y* axis so that equal increments of *x* and *y* have the same length; a circle is circular.:: >>> axis('scaled') achieves the same result by changing the dimensions of the plot box instead of the axis data limits.:: >>> axis('tight') changes *x* and *y* axis limits such that all data is shown. If all data is already shown, it will move it to the center of the figure without modifying (*xmax* - *xmin*) or (*ymax* - *ymin*). Note this is slightly different than in MATLAB.:: >>> axis('image') is 'scaled' with the axis limits equal to the data limits.:: >>> axis('auto') and:: >>> axis('normal') are deprecated. They restore default behavior; axis limits are automatically scaled to make the data fit comfortably within the plot box. if ``len(*v)==0``, you can pass in *xmin*, *xmax*, *ymin*, *ymax* as kwargs selectively to alter just those limits without changing the others. >>> axis('square') changes the limit ranges (*xmax*-*xmin*) and (*ymax*-*ymin*) of the *x* and *y* axes to be the same, and have the same scaling, resulting in a square plot. The xmin, xmax, ymin, ymax tuple is returned .. seealso:: :func:`xlim`, :func:`ylim` For setting the x- and y-limits individually. """ return gca().axis(*v, **kwargs) def xlabel(s, *args, **kwargs): """ Set the *x* axis label of the current axis. Default override is:: override = { 'fontsize' : 'small', 'verticalalignment' : 'top', 'horizontalalignment' : 'center' } .. seealso:: :func:`~matplotlib.pyplot.text` For information on how override and the optional args work """ return gca().set_xlabel(s, *args, **kwargs) def ylabel(s, *args, **kwargs): """ Set the *y* axis label of the current axis. Defaults override is:: override = { 'fontsize' : 'small', 'verticalalignment' : 'center', 'horizontalalignment' : 'right', 'rotation'='vertical' : } .. seealso:: :func:`~matplotlib.pyplot.text` For information on how override and the optional args work. """ return gca().set_ylabel(s, *args, **kwargs) def xlim(*args, **kwargs): """ Get or set the *x* limits of the current axes. :: xmin, xmax = xlim() # return the current xlim xlim( (xmin, xmax) ) # set the xlim to xmin, xmax xlim( xmin, xmax ) # set the xlim to xmin, xmax If you do not specify args, you can pass the xmin and xmax as kwargs, e.g.:: xlim(xmax=3) # adjust the max leaving min unchanged xlim(xmin=1) # adjust the min leaving max unchanged Setting limits turns autoscaling off for the x-axis. The new axis limits are returned as a length 2 tuple. """ ax = gca() if not args and not kwargs: return ax.get_xlim() ret = ax.set_xlim(*args, **kwargs) return ret def ylim(*args, **kwargs): """ Get or set the *y*-limits of the current axes. :: ymin, ymax = ylim() # return the current ylim ylim( (ymin, ymax) ) # set the ylim to ymin, ymax ylim( ymin, ymax ) # set the ylim to ymin, ymax If you do not specify args, you can pass the *ymin* and *ymax* as kwargs, e.g.:: ylim(ymax=3) # adjust the max leaving min unchanged ylim(ymin=1) # adjust the min leaving max unchanged Setting limits turns autoscaling off for the y-axis. The new axis limits are returned as a length 2 tuple. """ ax = gca() if not args and not kwargs: return ax.get_ylim() ret = ax.set_ylim(*args, **kwargs) return ret @docstring.dedent_interpd def xscale(*args, **kwargs): """ Set the scaling of the *x*-axis. call signature:: xscale(scale, **kwargs) The available scales are: %(scale)s Different keywords may be accepted, depending on the scale: %(scale_docs)s """ gca().set_xscale(*args, **kwargs) @docstring.dedent_interpd def yscale(*args, **kwargs): """ Set the scaling of the *y*-axis. call signature:: yscale(scale, **kwargs) The available scales are: %(scale)s Different keywords may be accepted, depending on the scale: %(scale_docs)s """ gca().set_yscale(*args, **kwargs) def xticks(*args, **kwargs): """ Get or set the *x*-limits of the current tick locations and labels. :: # return locs, labels where locs is an array of tick locations and # labels is an array of tick labels. locs, labels = xticks() # set the locations of the xticks xticks( arange(6) ) # set the locations and labels of the xticks xticks( arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue') ) The keyword args, if any, are :class:`~matplotlib.text.Text` properties. For example, to rotate long labels:: xticks( arange(12), calendar.month_name[1:13], rotation=17 ) """ ax = gca() if len(args)==0: locs = ax.get_xticks() labels = ax.get_xticklabels() elif len(args)==1: locs = ax.set_xticks(args[0]) labels = ax.get_xticklabels() elif len(args)==2: locs = ax.set_xticks(args[0]) labels = ax.set_xticklabels(args[1], **kwargs) else: raise TypeError('Illegal number of arguments to xticks') if len(kwargs): for l in labels: l.update(kwargs) return locs, silent_list('Text xticklabel', labels) def yticks(*args, **kwargs): """ Get or set the *y*-limits of the current tick locations and labels. :: # return locs, labels where locs is an array of tick locations and # labels is an array of tick labels. locs, labels = yticks() # set the locations of the yticks yticks( arange(6) ) # set the locations and labels of the yticks yticks( arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue') ) The keyword args, if any, are :class:`~matplotlib.text.Text` properties. For example, to rotate long labels:: yticks( arange(12), calendar.month_name[1:13], rotation=45 ) """ ax = gca() if len(args)==0: locs = ax.get_yticks() labels = ax.get_yticklabels() elif len(args)==1: locs = ax.set_yticks(args[0]) labels = ax.get_yticklabels() elif len(args)==2: locs = ax.set_yticks(args[0]) labels = ax.set_yticklabels(args[1], **kwargs) else: raise TypeError('Illegal number of arguments to yticks') if len(kwargs): for l in labels: l.update(kwargs) return ( locs, silent_list('Text yticklabel', labels) ) def minorticks_on(): """ Display minor ticks on the current plot. Displaying minor ticks reduces performance; turn them off using minorticks_off() if drawing speed is a problem. """ gca().minorticks_on() def minorticks_off(): """ Remove minor ticks from the current plot. """ gca().minorticks_off() def rgrids(*args, **kwargs): """ Get or set the radial gridlines on a polar plot. call signatures:: lines, labels = rgrids() lines, labels = rgrids(radii, labels=None, angle=22.5, **kwargs) When called with no arguments, :func:`rgrid` simply returns the tuple (*lines*, *labels*), where *lines* is an array of radial gridlines (:class:`~matplotlib.lines.Line2D` instances) and *labels* is an array of tick labels (:class:`~matplotlib.text.Text` instances). When called with arguments, the labels will appear at the specified radial distances and angles. *labels*, if not *None*, is a len(*radii*) list of strings of the labels to use at each angle. If *labels* is None, the rformatter will be used Examples:: # set the locations of the radial gridlines and labels lines, labels = rgrids( (0.25, 0.5, 1.0) ) # set the locations and labels of the radial gridlines and labels lines, labels = rgrids( (0.25, 0.5, 1.0), ('Tom', 'Dick', 'Harry' ) """ ax = gca() if not isinstance(ax, PolarAxes): raise RuntimeError('rgrids only defined for polar axes') if len(args)==0: lines = ax.yaxis.get_gridlines() labels = ax.yaxis.get_ticklabels() else: lines, labels = ax.set_rgrids(*args, **kwargs) return ( silent_list('Line2D rgridline', lines), silent_list('Text rgridlabel', labels) ) def thetagrids(*args, **kwargs): """ Get or set the theta locations of the gridlines in a polar plot. If no arguments are passed, return a tuple (*lines*, *labels*) where *lines* is an array of radial gridlines (:class:`~matplotlib.lines.Line2D` instances) and *labels* is an array of tick labels (:class:`~matplotlib.text.Text` instances):: lines, labels = thetagrids() Otherwise the syntax is:: lines, labels = thetagrids(angles, labels=None, fmt='%d', frac = 1.1) set the angles at which to place the theta grids (these gridlines are equal along the theta dimension). *angles* is in degrees. *labels*, if not *None*, is a len(angles) list of strings of the labels to use at each angle. If *labels* is *None*, the labels will be ``fmt%angle``. *frac* is the fraction of the polar axes radius at which to place the label (1 is the edge). e.g., 1.05 is outside the axes and 0.95 is inside the axes. Return value is a list of tuples (*lines*, *labels*): - *lines* are :class:`~matplotlib.lines.Line2D` instances - *labels* are :class:`~matplotlib.text.Text` instances. Note that on input, the *labels* argument is a list of strings, and on output it is a list of :class:`~matplotlib.text.Text` instances. Examples:: # set the locations of the radial gridlines and labels lines, labels = thetagrids( range(45,360,90) ) # set the locations and labels of the radial gridlines and labels lines, labels = thetagrids( range(45,360,90), ('NE', 'NW', 'SW','SE') ) """ ax = gca() if not isinstance(ax, PolarAxes): raise RuntimeError('rgrids only defined for polar axes') if len(args)==0: lines = ax.xaxis.get_ticklines() labels = ax.xaxis.get_ticklabels() else: lines, labels = ax.set_thetagrids(*args, **kwargs) return (silent_list('Line2D thetagridline', lines), silent_list('Text thetagridlabel', labels) ) ## Plotting Info ## def plotting(): pass def get_plot_commands(): """ Get a sorted list of all of the plotting commands. """ # This works by searching for all functions in this module and # removing a few hard-coded exclusions, as well as all of the # colormap-setting functions, and anything marked as private with # a preceding underscore. import inspect exclude = set(['colormaps', 'colors', 'connect', 'disconnect', 'get_plot_commands', 'get_current_fig_manager', 'ginput', 'plotting', 'waitforbuttonpress']) exclude |= set(colormaps()) this_module = inspect.getmodule(get_plot_commands) commands = set() for name, obj in list(six.iteritems(globals())): if name.startswith('_') or name in exclude: continue if inspect.isfunction(obj) and inspect.getmodule(obj) is this_module: commands.add(name) commands = list(commands) commands.sort() return commands def colors(): """ This is a do-nothing function to provide you with help on how matplotlib handles colors. Commands which take color arguments can use several formats to specify the colors. For the basic built-in colors, you can use a single letter ===== ======= Alias Color ===== ======= 'b' blue 'g' green 'r' red 'c' cyan 'm' magenta 'y' yellow 'k' black 'w' white ===== ======= For a greater range of colors, you have two options. You can specify the color using an html hex string, as in:: color = '#eeefff' or you can pass an R,G,B tuple, where each of R,G,B are in the range [0,1]. You can also use any legal html name for a color, for example:: color = 'red' color = 'burlywood' color = 'chartreuse' The example below creates a subplot with a dark slate gray background:: subplot(111, axisbg=(0.1843, 0.3098, 0.3098)) Here is an example that creates a pale turquoise title:: title('Is this the best color?', color='#afeeee') """ pass def colormaps(): """ Matplotlib provides a number of colormaps, and others can be added using :func:`~matplotlib.cm.register_cmap`. This function documents the built-in colormaps, and will also return a list of all registered colormaps if called. You can set the colormap for an image, pcolor, scatter, etc, using a keyword argument:: imshow(X, cmap=cm.hot) or using the :func:`set_cmap` function:: imshow(X) pyplot.set_cmap('hot') pyplot.set_cmap('jet') In interactive mode, :func:`set_cmap` will update the colormap post-hoc, allowing you to see which one works best for your data. All built-in colormaps can be reversed by appending ``_r``: For instance, ``gray_r`` is the reverse of ``gray``. There are several common color schemes used in visualization: Sequential schemes for unipolar data that progresses from low to high Diverging schemes for bipolar data that emphasizes positive or negative deviations from a central value Cyclic schemes meant for plotting values that wrap around at the endpoints, such as phase angle, wind direction, or time of day Qualitative schemes for nominal data that has no inherent ordering, where color is used only to distinguish categories The base colormaps are derived from those of the same name provided with Matlab: ========= ======================================================= Colormap Description ========= ======================================================= autumn sequential linearly-increasing shades of red-orange-yellow bone sequential increasing black-white color map with a tinge of blue, to emulate X-ray film cool linearly-decreasing shades of cyan-magenta copper sequential increasing shades of black-copper flag repetitive red-white-blue-black pattern (not cyclic at endpoints) gray sequential linearly-increasing black-to-white grayscale hot sequential black-red-yellow-white, to emulate blackbody radiation from an object at increasing temperatures hsv cyclic red-yellow-green-cyan-blue-magenta-red, formed by changing the hue component in the HSV color space inferno perceptually uniform shades of black-red-yellow jet a spectral map with dark endpoints, blue-cyan-yellow-red; based on a fluid-jet simulation by NCSA [#]_ magma perceptually uniform shades of black-red-white pink sequential increasing pastel black-pink-white, meant for sepia tone colorization of photographs plasma perceptually uniform shades of blue-red-yellow prism repetitive red-yellow-green-blue-purple-...-green pattern (not cyclic at endpoints) spring linearly-increasing shades of magenta-yellow summer sequential linearly-increasing shades of green-yellow viridis perceptually uniform shades of blue-green-yellow winter linearly-increasing shades of blue-green ========= ======================================================= For the above list only, you can also set the colormap using the corresponding pylab shortcut interface function, similar to Matlab:: imshow(X) hot() jet() The next set of palettes are from the `Yorick scientific visualisation package <http://dhmunro.github.io/yorick-doc/>`_, an evolution of the GIST package, both by David H. Munro: ============ ======================================================= Colormap Description ============ ======================================================= gist_earth mapmaker's colors from dark blue deep ocean to green lowlands to brown highlands to white mountains gist_heat sequential increasing black-red-orange-white, to emulate blackbody radiation from an iron bar as it grows hotter gist_ncar pseudo-spectral black-blue-green-yellow-red-purple-white colormap from National Center for Atmospheric Research [#]_ gist_rainbow runs through the colors in spectral order from red to violet at full saturation (like *hsv* but not cyclic) gist_stern "Stern special" color table from Interactive Data Language software ============ ======================================================= The following colormaps are based on the `ColorBrewer <http://colorbrewer.org>`_ color specifications and designs developed by Cynthia Brewer: ColorBrewer Diverging (luminance is highest at the midpoint, and decreases towards differently-colored endpoints): ======== =================================== Colormap Description ======== =================================== BrBG brown, white, blue-green PiYG pink, white, yellow-green PRGn purple, white, green PuOr orange, white, purple RdBu red, white, blue RdGy red, white, gray RdYlBu red, yellow, blue RdYlGn red, yellow, green Spectral red, orange, yellow, green, blue ======== =================================== ColorBrewer Sequential (luminance decreases monotonically): ======== ==================================== Colormap Description ======== ==================================== Blues white to dark blue BuGn white, light blue, dark green BuPu white, light blue, dark purple GnBu white, light green, dark blue Greens white to dark green Greys white to black (not linear) Oranges white, orange, dark brown OrRd white, orange, dark red PuBu white, light purple, dark blue PuBuGn white, light purple, dark green PuRd white, light purple, dark red Purples white to dark purple RdPu white, pink, dark purple Reds white to dark red YlGn light yellow, dark green YlGnBu light yellow, light green, dark blue YlOrBr light yellow, orange, dark brown YlOrRd light yellow, orange, dark red ======== ==================================== ColorBrewer Qualitative: (For plotting nominal data, :class:`ListedColormap` should be used, not :class:`LinearSegmentedColormap`. Different sets of colors are recommended for different numbers of categories. These continuous versions of the qualitative schemes may be removed or converted in the future.) * Accent * Dark2 * Paired * Pastel1 * Pastel2 * Set1 * Set2 * Set3 Other miscellaneous schemes: ============= ======================================================= Colormap Description ============= ======================================================= afmhot sequential black-orange-yellow-white blackbody spectrum, commonly used in atomic force microscopy brg blue-red-green bwr diverging blue-white-red coolwarm diverging blue-gray-red, meant to avoid issues with 3D shading, color blindness, and ordering of colors [#]_ CMRmap "Default colormaps on color images often reproduce to confusing grayscale images. The proposed colormap maintains an aesthetically pleasing color image that automatically reproduces to a monotonic grayscale with discrete, quantifiable saturation levels." [#]_ cubehelix Unlike most other color schemes cubehelix was designed by D.A. Green to be monotonically increasing in terms of perceived brightness. Also, when printed on a black and white postscript printer, the scheme results in a greyscale with monotonically increasing brightness. This color scheme is named cubehelix because the r,g,b values produced can be visualised as a squashed helix around the diagonal in the r,g,b color cube. gnuplot gnuplot's traditional pm3d scheme (black-blue-red-yellow) gnuplot2 sequential color printable as gray (black-blue-violet-yellow-white) ocean green-blue-white rainbow spectral purple-blue-green-yellow-orange-red colormap with diverging luminance seismic diverging blue-white-red nipy_spectral black-purple-blue-green-yellow-red-white spectrum, originally from the Neuroimaging in Python project terrain mapmaker's colors, blue-green-yellow-brown-white, originally from IGOR Pro ============= ======================================================= The following colormaps are redundant and may be removed in future versions. It's recommended to use the names in the descriptions instead, which produce identical output: ========= ======================================================= Colormap Description ========= ======================================================= gist_gray identical to *gray* gist_yarg identical to *gray_r* binary identical to *gray_r* spectral identical to *nipy_spectral* [#]_ ========= ======================================================= .. rubric:: Footnotes .. [#] Rainbow colormaps, ``jet`` in particular, are considered a poor choice for scientific visualization by many researchers: `Rainbow Color Map (Still) Considered Harmful <http://www.jwave.vt.edu/%7Erkriz/Projects/create_color_table/color_07.pdf>`_ .. [#] Resembles "BkBlAqGrYeOrReViWh200" from NCAR Command Language. See `Color Table Gallery <http://www.ncl.ucar.edu/Document/Graphics/color_table_gallery.shtml>`_ .. [#] See `Diverging Color Maps for Scientific Visualization <http://www.cs.unm.edu/~kmorel/documents/ColorMaps/>`_ by Kenneth Moreland. .. [#] See `A Color Map for Effective Black-and-White Rendering of Color-Scale Images <http://www.mathworks.com/matlabcentral/fileexchange/2662-cmrmap-m>`_ by Carey Rappaport .. [#] Changed to distinguish from ColorBrewer's *Spectral* map. :func:`spectral` still works, but ``set_cmap('nipy_spectral')`` is recommended for clarity. """ return sorted(cm.cmap_d.keys()) def _setup_pyplot_info_docstrings(): """ Generates the plotting and docstring. These must be done after the entire module is imported, so it is called from the end of this module, which is generated by boilerplate.py. """ # Generate the plotting docstring import re def pad(s, l): """Pad string *s* to length *l*.""" if l < len(s): return s[:l] return s + ' ' * (l - len(s)) commands = get_plot_commands() first_sentence = re.compile("(?:\s*).+?\.(?:\s+|$)", flags=re.DOTALL) # Collect the first sentence of the docstring for all of the # plotting commands. rows = [] max_name = 0 max_summary = 0 for name in commands: doc = globals()[name].__doc__ summary = '' if doc is not None: match = first_sentence.match(doc) if match is not None: summary = match.group(0).strip().replace('\n', ' ') name = '`%s`' % name rows.append([name, summary]) max_name = max(max_name, len(name)) max_summary = max(max_summary, len(summary)) lines = [] sep = '=' * max_name + ' ' + '=' * max_summary lines.append(sep) lines.append(' '.join([pad("Function", max_name), pad("Description", max_summary)])) lines.append(sep) for name, summary in rows: lines.append(' '.join([pad(name, max_name), pad(summary, max_summary)])) lines.append(sep) plotting.__doc__ = '\n'.join(lines) ## Plotting part 1: manually generated functions and wrappers ## def colorbar(mappable=None, cax=None, ax=None, **kw): if mappable is None: mappable = gci() if mappable is None: raise RuntimeError('No mappable was found to use for colorbar ' 'creation. First define a mappable such as ' 'an image (with imshow) or a contour set (' 'with contourf).') if ax is None: ax = gca() ret = gcf().colorbar(mappable, cax = cax, ax=ax, **kw) return ret colorbar.__doc__ = matplotlib.colorbar.colorbar_doc def clim(vmin=None, vmax=None): """ Set the color limits of the current image. To apply clim to all axes images do:: clim(0, 0.5) If either *vmin* or *vmax* is None, the image min/max respectively will be used for color scaling. If you want to set the clim of multiple images, use, for example:: for im in gca().get_images(): im.set_clim(0, 0.05) """ im = gci() if im is None: raise RuntimeError('You must first define an image, e.g., with imshow') im.set_clim(vmin, vmax) def set_cmap(cmap): """ Set the default colormap. Applies to the current image if any. See help(colormaps) for more information. *cmap* must be a :class:`~matplotlib.colors.Colormap` instance, or the name of a registered colormap. See :func:`matplotlib.cm.register_cmap` and :func:`matplotlib.cm.get_cmap`. """ cmap = cm.get_cmap(cmap) rc('image', cmap=cmap.name) im = gci() if im is not None: im.set_cmap(cmap) @docstring.copy_dedent(_imread) def imread(*args, **kwargs): return _imread(*args, **kwargs) @docstring.copy_dedent(_imsave) def imsave(*args, **kwargs): return _imsave(*args, **kwargs) def matshow(A, fignum=None, **kw): """ Display an array as a matrix in a new figure window. The origin is set at the upper left hand corner and rows (first dimension of the array) are displayed horizontally. The aspect ratio of the figure window is that of the array, unless this would make an excessively short or narrow figure. Tick labels for the xaxis are placed on top. With the exception of *fignum*, keyword arguments are passed to :func:`~matplotlib.pyplot.imshow`. You may set the *origin* kwarg to "lower" if you want the first row in the array to be at the bottom instead of the top. *fignum*: [ None | integer | False ] By default, :func:`matshow` creates a new figure window with automatic numbering. If *fignum* is given as an integer, the created figure will use this figure number. Because of how :func:`matshow` tries to set the figure aspect ratio to be the one of the array, if you provide the number of an already existing figure, strange things may happen. If *fignum* is *False* or 0, a new figure window will **NOT** be created. """ A = np.asanyarray(A) if fignum is False or fignum is 0: ax = gca() else: # Extract actual aspect ratio of array and make appropriately sized figure fig = figure(fignum, figsize=figaspect(A)) ax = fig.add_axes([0.15, 0.09, 0.775, 0.775]) im = ax.matshow(A, **kw) sci(im) return im def polar(*args, **kwargs): """ Make a polar plot. call signature:: polar(theta, r, **kwargs) Multiple *theta*, *r* arguments are supported, with format strings, as in :func:`~matplotlib.pyplot.plot`. """ ax = gca(polar=True) ret = ax.plot(*args, **kwargs) return ret def plotfile(fname, cols=(0,), plotfuncs=None, comments='#', skiprows=0, checkrows=5, delimiter=',', names=None, subplots=True, newfig=True, **kwargs): """ Plot the data in in a file. *cols* is a sequence of column identifiers to plot. An identifier is either an int or a string. If it is an int, it indicates the column number. If it is a string, it indicates the column header. matplotlib will make column headers lower case, replace spaces with underscores, and remove all illegal characters; so ``'Adj Close*'`` will have name ``'adj_close'``. - If len(*cols*) == 1, only that column will be plotted on the *y* axis. - If len(*cols*) > 1, the first element will be an identifier for data for the *x* axis and the remaining elements will be the column indexes for multiple subplots if *subplots* is *True* (the default), or for lines in a single subplot if *subplots* is *False*. *plotfuncs*, if not *None*, is a dictionary mapping identifier to an :class:`~matplotlib.axes.Axes` plotting function as a string. Default is 'plot', other choices are 'semilogy', 'fill', 'bar', etc. You must use the same type of identifier in the *cols* vector as you use in the *plotfuncs* dictionary, e.g., integer column numbers in both or column names in both. If *subplots* is *False*, then including any function such as 'semilogy' that changes the axis scaling will set the scaling for all columns. *comments*, *skiprows*, *checkrows*, *delimiter*, and *names* are all passed on to :func:`matplotlib.pylab.csv2rec` to load the data into a record array. If *newfig* is *True*, the plot always will be made in a new figure; if *False*, it will be made in the current figure if one exists, else in a new figure. kwargs are passed on to plotting functions. Example usage:: # plot the 2nd and 4th column against the 1st in two subplots plotfile(fname, (0,1,3)) # plot using column names; specify an alternate plot type for volume plotfile(fname, ('date', 'volume', 'adj_close'), plotfuncs={'volume': 'semilogy'}) Note: plotfile is intended as a convenience for quickly plotting data from flat files; it is not intended as an alternative interface to general plotting with pyplot or matplotlib. """ if newfig: fig = figure() else: fig = gcf() if len(cols)<1: raise ValueError('must have at least one column of data') if plotfuncs is None: plotfuncs = dict() r = mlab.csv2rec(fname, comments=comments, skiprows=skiprows, checkrows=checkrows, delimiter=delimiter, names=names) def getname_val(identifier): 'return the name and column data for identifier' if is_string_like(identifier): return identifier, r[identifier] elif is_numlike(identifier): name = r.dtype.names[int(identifier)] return name, r[name] else: raise TypeError('identifier must be a string or integer') xname, x = getname_val(cols[0]) ynamelist = [] if len(cols)==1: ax1 = fig.add_subplot(1,1,1) funcname = plotfuncs.get(cols[0], 'plot') func = getattr(ax1, funcname) func(x, **kwargs) ax1.set_ylabel(xname) else: N = len(cols) for i in range(1,N): if subplots: if i==1: ax = ax1 = fig.add_subplot(N-1,1,i) else: ax = fig.add_subplot(N-1,1,i, sharex=ax1) elif i==1: ax = fig.add_subplot(1,1,1) yname, y = getname_val(cols[i]) ynamelist.append(yname) funcname = plotfuncs.get(cols[i], 'plot') func = getattr(ax, funcname) func(x, y, **kwargs) if subplots: ax.set_ylabel(yname) if ax.is_last_row(): ax.set_xlabel(xname) else: ax.set_xlabel('') if not subplots: ax.legend(ynamelist, loc='best') if xname=='date': fig.autofmt_xdate() def _autogen_docstring(base): """Autogenerated wrappers will get their docstring from a base function with an addendum.""" msg = "\n\nAdditional kwargs: hold = [True|False] overrides default hold state" addendum = docstring.Appender(msg, '\n\n') return lambda func: addendum(docstring.copy_dedent(base)(func)) # This function cannot be generated by boilerplate.py because it may # return an image or a line. @_autogen_docstring(Axes.spy) def spy(Z, precision=0, marker=None, markersize=None, aspect='equal', hold=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.spy(Z, precision, marker, markersize, aspect, **kwargs) finally: ax.hold(washold) if isinstance(ret, cm.ScalarMappable): sci(ret) return ret # just to be safe. Interactive mode can be turned on without # calling `plt.ion()` so register it again here. # This is safe because multiple calls to `install_repl_displayhook` # are no-ops and the registered function respect `mpl.is_interactive()` # to determine if they should trigger a draw. install_repl_displayhook() ################# REMAINING CONTENT GENERATED BY boilerplate.py ############## # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.acorr) def acorr(x, hold=None, data=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.acorr(x, data=data, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.angle_spectrum) def angle_spectrum(x, Fs=None, Fc=None, window=None, pad_to=None, sides=None, hold=None, data=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.angle_spectrum(x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to, sides=sides, data=data, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.arrow) def arrow(x, y, dx, dy, hold=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.arrow(x, y, dx, dy, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.axhline) def axhline(y=0, xmin=0, xmax=1, hold=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.axhline(y=y, xmin=xmin, xmax=xmax, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.axhspan) def axhspan(ymin, ymax, xmin=0, xmax=1, hold=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.axhspan(ymin, ymax, xmin=xmin, xmax=xmax, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.axvline) def axvline(x=0, ymin=0, ymax=1, hold=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.axvline(x=x, ymin=ymin, ymax=ymax, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.axvspan) def axvspan(xmin, xmax, ymin=0, ymax=1, hold=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.axvspan(xmin, xmax, ymin=ymin, ymax=ymax, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.bar) def bar(left, height, width=0.8, bottom=None, hold=None, data=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.bar(left, height, width=width, bottom=bottom, data=data, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.barh) def barh(bottom, width, height=0.8, left=None, hold=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.barh(bottom, width, height=height, left=left, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.broken_barh) def broken_barh(xranges, yrange, hold=None, data=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.broken_barh(xranges, yrange, data=data, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.boxplot) def boxplot(x, notch=None, sym=None, vert=None, whis=None, positions=None, widths=None, patch_artist=None, bootstrap=None, usermedians=None, conf_intervals=None, meanline=None, showmeans=None, showcaps=None, showbox=None, showfliers=None, boxprops=None, labels=None, flierprops=None, medianprops=None, meanprops=None, capprops=None, whiskerprops=None, manage_xticks=True, hold=None, data=None): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.boxplot(x, notch=notch, sym=sym, vert=vert, whis=whis, positions=positions, widths=widths, patch_artist=patch_artist, bootstrap=bootstrap, usermedians=usermedians, conf_intervals=conf_intervals, meanline=meanline, showmeans=showmeans, showcaps=showcaps, showbox=showbox, showfliers=showfliers, boxprops=boxprops, labels=labels, flierprops=flierprops, medianprops=medianprops, meanprops=meanprops, capprops=capprops, whiskerprops=whiskerprops, manage_xticks=manage_xticks, data=data) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.cohere) def cohere(x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none, window=mlab.window_hanning, noverlap=0, pad_to=None, sides='default', scale_by_freq=None, hold=None, data=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.cohere(x, y, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window, noverlap=noverlap, pad_to=pad_to, sides=sides, scale_by_freq=scale_by_freq, data=data, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.clabel) def clabel(CS, *args, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() hold = kwargs.pop('hold', None) if hold is not None: ax.hold(hold) try: ret = ax.clabel(CS, *args, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.contour) def contour(*args, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() hold = kwargs.pop('hold', None) if hold is not None: ax.hold(hold) try: ret = ax.contour(*args, **kwargs) finally: ax.hold(washold) if ret._A is not None: sci(ret) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.contourf) def contourf(*args, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() hold = kwargs.pop('hold', None) if hold is not None: ax.hold(hold) try: ret = ax.contourf(*args, **kwargs) finally: ax.hold(washold) if ret._A is not None: sci(ret) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.csd) def csd(x, y, NFFT=None, Fs=None, Fc=None, detrend=None, window=None, noverlap=None, pad_to=None, sides=None, scale_by_freq=None, return_line=None, hold=None, data=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.csd(x, y, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window, noverlap=noverlap, pad_to=pad_to, sides=sides, scale_by_freq=scale_by_freq, return_line=return_line, data=data, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.errorbar) def errorbar(x, y, yerr=None, xerr=None, fmt='', ecolor=None, elinewidth=None, capsize=None, barsabove=False, lolims=False, uplims=False, xlolims=False, xuplims=False, errorevery=1, capthick=None, hold=None, data=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.errorbar(x, y, yerr=yerr, xerr=xerr, fmt=fmt, ecolor=ecolor, elinewidth=elinewidth, capsize=capsize, barsabove=barsabove, lolims=lolims, uplims=uplims, xlolims=xlolims, xuplims=xuplims, errorevery=errorevery, capthick=capthick, data=data, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.eventplot) def eventplot(positions, orientation='horizontal', lineoffsets=1, linelengths=1, linewidths=None, colors=None, linestyles='solid', hold=None, data=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.eventplot(positions, orientation=orientation, lineoffsets=lineoffsets, linelengths=linelengths, linewidths=linewidths, colors=colors, linestyles=linestyles, data=data, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.fill) def fill(*args, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() hold = kwargs.pop('hold', None) if hold is not None: ax.hold(hold) try: ret = ax.fill(*args, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.fill_between) def fill_between(x, y1, y2=0, where=None, interpolate=False, step=None, hold=None, data=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.fill_between(x, y1, y2=y2, where=where, interpolate=interpolate, step=step, data=data, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.fill_betweenx) def fill_betweenx(y, x1, x2=0, where=None, step=None, hold=None, data=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.fill_betweenx(y, x1, x2=x2, where=where, step=step, data=data, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.hexbin) def hexbin(x, y, C=None, gridsize=100, bins=None, xscale='linear', yscale='linear', extent=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors='none', reduce_C_function=np.mean, mincnt=None, marginals=False, hold=None, data=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.hexbin(x, y, C=C, gridsize=gridsize, bins=bins, xscale=xscale, yscale=yscale, extent=extent, cmap=cmap, norm=norm, vmin=vmin, vmax=vmax, alpha=alpha, linewidths=linewidths, edgecolors=edgecolors, reduce_C_function=reduce_C_function, mincnt=mincnt, marginals=marginals, data=data, **kwargs) finally: ax.hold(washold) sci(ret) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.hist) def hist(x, bins=10, range=None, normed=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, hold=None, data=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.hist(x, bins=bins, range=range, normed=normed, weights=weights, cumulative=cumulative, bottom=bottom, histtype=histtype, align=align, orientation=orientation, rwidth=rwidth, log=log, color=color, label=label, stacked=stacked, data=data, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.hist2d) def hist2d(x, y, bins=10, range=None, normed=False, weights=None, cmin=None, cmax=None, hold=None, data=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.hist2d(x, y, bins=bins, range=range, normed=normed, weights=weights, cmin=cmin, cmax=cmax, data=data, **kwargs) finally: ax.hold(washold) sci(ret[-1]) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.hlines) def hlines(y, xmin, xmax, colors='k', linestyles='solid', label='', hold=None, data=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.hlines(y, xmin, xmax, colors=colors, linestyles=linestyles, label=label, data=data, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.imshow) def imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, shape=None, filternorm=1, filterrad=4.0, imlim=None, resample=None, url=None, hold=None, data=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.imshow(X, cmap=cmap, norm=norm, aspect=aspect, interpolation=interpolation, alpha=alpha, vmin=vmin, vmax=vmax, origin=origin, extent=extent, shape=shape, filternorm=filternorm, filterrad=filterrad, imlim=imlim, resample=resample, url=url, data=data, **kwargs) finally: ax.hold(washold) sci(ret) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.loglog) def loglog(*args, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() hold = kwargs.pop('hold', None) if hold is not None: ax.hold(hold) try: ret = ax.loglog(*args, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.magnitude_spectrum) def magnitude_spectrum(x, Fs=None, Fc=None, window=None, pad_to=None, sides=None, scale=None, hold=None, data=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.magnitude_spectrum(x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to, sides=sides, scale=scale, data=data, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.pcolor) def pcolor(*args, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() hold = kwargs.pop('hold', None) if hold is not None: ax.hold(hold) try: ret = ax.pcolor(*args, **kwargs) finally: ax.hold(washold) sci(ret) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.pcolormesh) def pcolormesh(*args, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() hold = kwargs.pop('hold', None) if hold is not None: ax.hold(hold) try: ret = ax.pcolormesh(*args, **kwargs) finally: ax.hold(washold) sci(ret) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.phase_spectrum) def phase_spectrum(x, Fs=None, Fc=None, window=None, pad_to=None, sides=None, hold=None, data=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.phase_spectrum(x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to, sides=sides, data=data, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.pie) def pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, radius=None, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, hold=None, data=None): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.pie(x, explode=explode, labels=labels, colors=colors, autopct=autopct, pctdistance=pctdistance, shadow=shadow, labeldistance=labeldistance, startangle=startangle, radius=radius, counterclock=counterclock, wedgeprops=wedgeprops, textprops=textprops, center=center, frame=frame, data=data) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.plot) def plot(*args, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() hold = kwargs.pop('hold', None) if hold is not None: ax.hold(hold) try: ret = ax.plot(*args, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.plot_date) def plot_date(x, y, fmt='o', tz=None, xdate=True, ydate=False, hold=None, data=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.plot_date(x, y, fmt=fmt, tz=tz, xdate=xdate, ydate=ydate, data=data, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.psd) def psd(x, NFFT=None, Fs=None, Fc=None, detrend=None, window=None, noverlap=None, pad_to=None, sides=None, scale_by_freq=None, return_line=None, hold=None, data=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.psd(x, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window, noverlap=noverlap, pad_to=pad_to, sides=sides, scale_by_freq=scale_by_freq, return_line=return_line, data=data, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.quiver) def quiver(*args, **kw): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() hold = kw.pop('hold', None) if hold is not None: ax.hold(hold) try: ret = ax.quiver(*args, **kw) finally: ax.hold(washold) sci(ret) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.quiverkey) def quiverkey(*args, **kw): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() hold = kw.pop('hold', None) if hold is not None: ax.hold(hold) try: ret = ax.quiverkey(*args, **kw) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.scatter) def scatter(x, y, s=20, c=None, marker='o', cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, hold=None, data=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.scatter(x, y, s=s, c=c, marker=marker, cmap=cmap, norm=norm, vmin=vmin, vmax=vmax, alpha=alpha, linewidths=linewidths, verts=verts, edgecolors=edgecolors, data=data, **kwargs) finally: ax.hold(washold) sci(ret) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.semilogx) def semilogx(*args, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() hold = kwargs.pop('hold', None) if hold is not None: ax.hold(hold) try: ret = ax.semilogx(*args, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.semilogy) def semilogy(*args, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() hold = kwargs.pop('hold', None) if hold is not None: ax.hold(hold) try: ret = ax.semilogy(*args, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.specgram) def specgram(x, NFFT=None, Fs=None, Fc=None, detrend=None, window=None, noverlap=None, cmap=None, xextent=None, pad_to=None, sides=None, scale_by_freq=None, mode=None, scale=None, vmin=None, vmax=None, hold=None, data=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.specgram(x, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window, noverlap=noverlap, cmap=cmap, xextent=xextent, pad_to=pad_to, sides=sides, scale_by_freq=scale_by_freq, mode=mode, scale=scale, vmin=vmin, vmax=vmax, data=data, **kwargs) finally: ax.hold(washold) sci(ret[-1]) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.stackplot) def stackplot(x, *args, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() hold = kwargs.pop('hold', None) if hold is not None: ax.hold(hold) try: ret = ax.stackplot(x, *args, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.stem) def stem(*args, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() hold = kwargs.pop('hold', None) if hold is not None: ax.hold(hold) try: ret = ax.stem(*args, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.step) def step(x, y, *args, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() hold = kwargs.pop('hold', None) if hold is not None: ax.hold(hold) try: ret = ax.step(x, y, *args, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.streamplot) def streamplot(x, y, u, v, density=1, linewidth=None, color=None, cmap=None, norm=None, arrowsize=1, arrowstyle='-|>', minlength=0.1, transform=None, zorder=1, start_points=None, hold=None, data=None): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.streamplot(x, y, u, v, density=density, linewidth=linewidth, color=color, cmap=cmap, norm=norm, arrowsize=arrowsize, arrowstyle=arrowstyle, minlength=minlength, transform=transform, zorder=zorder, start_points=start_points, data=data) finally: ax.hold(washold) sci(ret.lines) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.tricontour) def tricontour(*args, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() hold = kwargs.pop('hold', None) if hold is not None: ax.hold(hold) try: ret = ax.tricontour(*args, **kwargs) finally: ax.hold(washold) if ret._A is not None: sci(ret) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.tricontourf) def tricontourf(*args, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() hold = kwargs.pop('hold', None) if hold is not None: ax.hold(hold) try: ret = ax.tricontourf(*args, **kwargs) finally: ax.hold(washold) if ret._A is not None: sci(ret) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.tripcolor) def tripcolor(*args, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() hold = kwargs.pop('hold', None) if hold is not None: ax.hold(hold) try: ret = ax.tripcolor(*args, **kwargs) finally: ax.hold(washold) sci(ret) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.triplot) def triplot(*args, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() hold = kwargs.pop('hold', None) if hold is not None: ax.hold(hold) try: ret = ax.triplot(*args, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.violinplot) def violinplot(dataset, positions=None, vert=True, widths=0.5, showmeans=False, showextrema=True, showmedians=False, points=100, bw_method=None, hold=None, data=None): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.violinplot(dataset, positions=positions, vert=vert, widths=widths, showmeans=showmeans, showextrema=showextrema, showmedians=showmedians, points=points, bw_method=bw_method, data=data) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.vlines) def vlines(x, ymin, ymax, colors='k', linestyles='solid', label='', hold=None, data=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.vlines(x, ymin, ymax, colors=colors, linestyles=linestyles, label=label, data=data, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.xcorr) def xcorr(x, y, normed=True, detrend=mlab.detrend_none, usevlines=True, maxlags=10, hold=None, data=None, **kwargs): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = ax.xcorr(x, y, normed=normed, detrend=detrend, usevlines=usevlines, maxlags=maxlags, data=data, **kwargs) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.barbs) def barbs(*args, **kw): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() hold = kw.pop('hold', None) if hold is not None: ax.hold(hold) try: ret = ax.barbs(*args, **kw) finally: ax.hold(washold) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @docstring.copy_dedent(Axes.cla) def cla(): ret = gca().cla() return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @docstring.copy_dedent(Axes.grid) def grid(b=None, which='major', axis='both', **kwargs): ret = gca().grid(b=b, which=which, axis=axis, **kwargs) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @docstring.copy_dedent(Axes.legend) def legend(*args, **kwargs): ret = gca().legend(*args, **kwargs) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @docstring.copy_dedent(Axes.table) def table(**kwargs): ret = gca().table(**kwargs) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @docstring.copy_dedent(Axes.text) def text(x, y, s, fontdict=None, withdash=False, **kwargs): ret = gca().text(x, y, s, fontdict=fontdict, withdash=withdash, **kwargs) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @docstring.copy_dedent(Axes.annotate) def annotate(*args, **kwargs): ret = gca().annotate(*args, **kwargs) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @docstring.copy_dedent(Axes.ticklabel_format) def ticklabel_format(**kwargs): ret = gca().ticklabel_format(**kwargs) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @docstring.copy_dedent(Axes.locator_params) def locator_params(axis='both', tight=None, **kwargs): ret = gca().locator_params(axis=axis, tight=tight, **kwargs) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @docstring.copy_dedent(Axes.tick_params) def tick_params(axis='both', **kwargs): ret = gca().tick_params(axis=axis, **kwargs) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @docstring.copy_dedent(Axes.margins) def margins(*args, **kw): ret = gca().margins(*args, **kw) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @docstring.copy_dedent(Axes.autoscale) def autoscale(enable=True, axis='both', tight=None): ret = gca().autoscale(enable=enable, axis=axis, tight=tight) return ret # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def autumn(): ''' set the default colormap to autumn and apply to current image if any. See help(colormaps) for more information ''' rc('image', cmap='autumn') im = gci() if im is not None: im.set_cmap(cm.autumn) # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def bone(): ''' set the default colormap to bone and apply to current image if any. See help(colormaps) for more information ''' rc('image', cmap='bone') im = gci() if im is not None: im.set_cmap(cm.bone) # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def cool(): ''' set the default colormap to cool and apply to current image if any. See help(colormaps) for more information ''' rc('image', cmap='cool') im = gci() if im is not None: im.set_cmap(cm.cool) # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def copper(): ''' set the default colormap to copper and apply to current image if any. See help(colormaps) for more information ''' rc('image', cmap='copper') im = gci() if im is not None: im.set_cmap(cm.copper) # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def flag(): ''' set the default colormap to flag and apply to current image if any. See help(colormaps) for more information ''' rc('image', cmap='flag') im = gci() if im is not None: im.set_cmap(cm.flag) # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def gray(): ''' set the default colormap to gray and apply to current image if any. See help(colormaps) for more information ''' rc('image', cmap='gray') im = gci() if im is not None: im.set_cmap(cm.gray) # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def hot(): ''' set the default colormap to hot and apply to current image if any. See help(colormaps) for more information ''' rc('image', cmap='hot') im = gci() if im is not None: im.set_cmap(cm.hot) # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def hsv(): ''' set the default colormap to hsv and apply to current image if any. See help(colormaps) for more information ''' rc('image', cmap='hsv') im = gci() if im is not None: im.set_cmap(cm.hsv) # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def jet(): ''' set the default colormap to jet and apply to current image if any. See help(colormaps) for more information ''' rc('image', cmap='jet') im = gci() if im is not None: im.set_cmap(cm.jet) # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def pink(): ''' set the default colormap to pink and apply to current image if any. See help(colormaps) for more information ''' rc('image', cmap='pink') im = gci() if im is not None: im.set_cmap(cm.pink) # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def prism(): ''' set the default colormap to prism and apply to current image if any. See help(colormaps) for more information ''' rc('image', cmap='prism') im = gci() if im is not None: im.set_cmap(cm.prism) # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def spring(): ''' set the default colormap to spring and apply to current image if any. See help(colormaps) for more information ''' rc('image', cmap='spring') im = gci() if im is not None: im.set_cmap(cm.spring) # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def summer(): ''' set the default colormap to summer and apply to current image if any. See help(colormaps) for more information ''' rc('image', cmap='summer') im = gci() if im is not None: im.set_cmap(cm.summer) # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def winter(): ''' set the default colormap to winter and apply to current image if any. See help(colormaps) for more information ''' rc('image', cmap='winter') im = gci() if im is not None: im.set_cmap(cm.winter) # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def spectral(): ''' set the default colormap to spectral and apply to current image if any. See help(colormaps) for more information ''' rc('image', cmap='spectral') im = gci() if im is not None: im.set_cmap(cm.spectral) # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def magma(): ''' set the default colormap to magma and apply to current image if any. See help(colormaps) for more information ''' rc('image', cmap='magma') im = gci() if im is not None: im.set_cmap(cm.magma) # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def inferno(): ''' set the default colormap to inferno and apply to current image if any. See help(colormaps) for more information ''' rc('image', cmap='inferno') im = gci() if im is not None: im.set_cmap(cm.inferno) # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def plasma(): ''' set the default colormap to plasma and apply to current image if any. See help(colormaps) for more information ''' rc('image', cmap='plasma') im = gci() if im is not None: im.set_cmap(cm.plasma) # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def viridis(): ''' set the default colormap to viridis and apply to current image if any. See help(colormaps) for more information ''' rc('image', cmap='viridis') im = gci() if im is not None: im.set_cmap(cm.viridis) _setup_pyplot_info_docstrings()
apache-2.0
kjung/scikit-learn
sklearn/ensemble/tests/test_bagging.py
34
25693
""" Testing for the bagging ensemble module (sklearn.ensemble.bagging). """ # Author: Gilles Louppe # License: BSD 3 clause import numpy as np from sklearn.base import BaseEstimator 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.utils.testing import assert_less from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_false from sklearn.utils.testing import assert_warns from sklearn.utils.testing import assert_warns_message from sklearn.dummy import DummyClassifier, DummyRegressor from sklearn.model_selection import GridSearchCV, ParameterGrid from sklearn.ensemble import BaggingClassifier, BaggingRegressor from sklearn.linear_model import Perceptron, LogisticRegression from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from sklearn.svm import SVC, SVR from sklearn.pipeline import make_pipeline from sklearn.feature_selection import SelectKBest from sklearn.model_selection import train_test_split from sklearn.datasets import load_boston, load_iris, make_hastie_10_2 from sklearn.utils import check_random_state from scipy.sparse import csc_matrix, csr_matrix rng = check_random_state(0) # also load the iris dataset # and randomly permute it iris = load_iris() perm = rng.permutation(iris.target.size) iris.data = iris.data[perm] iris.target = iris.target[perm] # also load the boston dataset # and randomly permute it boston = load_boston() perm = rng.permutation(boston.target.size) boston.data = boston.data[perm] boston.target = boston.target[perm] def test_classification(): # Check classification for various parameter settings. rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, random_state=rng) grid = ParameterGrid({"max_samples": [0.5, 1.0], "max_features": [1, 2, 4], "bootstrap": [True, False], "bootstrap_features": [True, False]}) for base_estimator in [None, DummyClassifier(), Perceptron(), DecisionTreeClassifier(), KNeighborsClassifier(), SVC()]: for params in grid: BaggingClassifier(base_estimator=base_estimator, random_state=rng, **params).fit(X_train, y_train).predict(X_test) def test_sparse_classification(): # Check classification for various parameter settings on sparse input. class CustomSVC(SVC): """SVC variant that records the nature of the training set""" def fit(self, X, y): super(CustomSVC, self).fit(X, y) self.data_type_ = type(X) return self rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, random_state=rng) parameter_sets = [ {"max_samples": 0.5, "max_features": 2, "bootstrap": True, "bootstrap_features": True}, {"max_samples": 1.0, "max_features": 4, "bootstrap": True, "bootstrap_features": True}, {"max_features": 2, "bootstrap": False, "bootstrap_features": True}, {"max_samples": 0.5, "bootstrap": True, "bootstrap_features": False}, ] for sparse_format in [csc_matrix, csr_matrix]: X_train_sparse = sparse_format(X_train) X_test_sparse = sparse_format(X_test) for params in parameter_sets: for f in ['predict', 'predict_proba', 'predict_log_proba', 'decision_function']: # Trained on sparse format sparse_classifier = BaggingClassifier( base_estimator=CustomSVC(decision_function_shape='ovr'), random_state=1, **params ).fit(X_train_sparse, y_train) sparse_results = getattr(sparse_classifier, f)(X_test_sparse) # Trained on dense format dense_classifier = BaggingClassifier( base_estimator=CustomSVC(decision_function_shape='ovr'), random_state=1, **params ).fit(X_train, y_train) dense_results = getattr(dense_classifier, f)(X_test) assert_array_equal(sparse_results, dense_results) sparse_type = type(X_train_sparse) types = [i.data_type_ for i in sparse_classifier.estimators_] assert all([t == sparse_type for t in types]) def test_regression(): # Check regression for various parameter settings. rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(boston.data[:50], boston.target[:50], random_state=rng) grid = ParameterGrid({"max_samples": [0.5, 1.0], "max_features": [0.5, 1.0], "bootstrap": [True, False], "bootstrap_features": [True, False]}) for base_estimator in [None, DummyRegressor(), DecisionTreeRegressor(), KNeighborsRegressor(), SVR()]: for params in grid: BaggingRegressor(base_estimator=base_estimator, random_state=rng, **params).fit(X_train, y_train).predict(X_test) def test_sparse_regression(): # Check regression for various parameter settings on sparse input. rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(boston.data[:50], boston.target[:50], random_state=rng) class CustomSVR(SVR): """SVC variant that records the nature of the training set""" def fit(self, X, y): super(CustomSVR, self).fit(X, y) self.data_type_ = type(X) return self parameter_sets = [ {"max_samples": 0.5, "max_features": 2, "bootstrap": True, "bootstrap_features": True}, {"max_samples": 1.0, "max_features": 4, "bootstrap": True, "bootstrap_features": True}, {"max_features": 2, "bootstrap": False, "bootstrap_features": True}, {"max_samples": 0.5, "bootstrap": True, "bootstrap_features": False}, ] for sparse_format in [csc_matrix, csr_matrix]: X_train_sparse = sparse_format(X_train) X_test_sparse = sparse_format(X_test) for params in parameter_sets: # Trained on sparse format sparse_classifier = BaggingRegressor( base_estimator=CustomSVR(), random_state=1, **params ).fit(X_train_sparse, y_train) sparse_results = sparse_classifier.predict(X_test_sparse) # Trained on dense format dense_results = BaggingRegressor( base_estimator=CustomSVR(), random_state=1, **params ).fit(X_train, y_train).predict(X_test) sparse_type = type(X_train_sparse) types = [i.data_type_ for i in sparse_classifier.estimators_] assert_array_equal(sparse_results, dense_results) assert all([t == sparse_type for t in types]) assert_array_equal(sparse_results, dense_results) def test_bootstrap_samples(): # Test that bootstrapping samples generate non-perfect base estimators. rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=rng) base_estimator = DecisionTreeRegressor().fit(X_train, y_train) # without bootstrap, all trees are perfect on the training set ensemble = BaggingRegressor(base_estimator=DecisionTreeRegressor(), max_samples=1.0, bootstrap=False, random_state=rng).fit(X_train, y_train) assert_equal(base_estimator.score(X_train, y_train), ensemble.score(X_train, y_train)) # with bootstrap, trees are no longer perfect on the training set ensemble = BaggingRegressor(base_estimator=DecisionTreeRegressor(), max_samples=1.0, bootstrap=True, random_state=rng).fit(X_train, y_train) assert_greater(base_estimator.score(X_train, y_train), ensemble.score(X_train, y_train)) def test_bootstrap_features(): # Test that bootstrapping features may generate duplicate features. rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=rng) ensemble = BaggingRegressor(base_estimator=DecisionTreeRegressor(), max_features=1.0, bootstrap_features=False, random_state=rng).fit(X_train, y_train) for features in ensemble.estimators_features_: assert_equal(boston.data.shape[1], np.unique(features).shape[0]) ensemble = BaggingRegressor(base_estimator=DecisionTreeRegressor(), max_features=1.0, bootstrap_features=True, random_state=rng).fit(X_train, y_train) for features in ensemble.estimators_features_: assert_greater(boston.data.shape[1], np.unique(features).shape[0]) def test_probability(): # Predict probabilities. rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, random_state=rng) with np.errstate(divide="ignore", invalid="ignore"): # Normal case ensemble = BaggingClassifier(base_estimator=DecisionTreeClassifier(), random_state=rng).fit(X_train, y_train) assert_array_almost_equal(np.sum(ensemble.predict_proba(X_test), axis=1), np.ones(len(X_test))) assert_array_almost_equal(ensemble.predict_proba(X_test), np.exp(ensemble.predict_log_proba(X_test))) # Degenerate case, where some classes are missing ensemble = BaggingClassifier(base_estimator=LogisticRegression(), random_state=rng, max_samples=5).fit(X_train, y_train) assert_array_almost_equal(np.sum(ensemble.predict_proba(X_test), axis=1), np.ones(len(X_test))) assert_array_almost_equal(ensemble.predict_proba(X_test), np.exp(ensemble.predict_log_proba(X_test))) def test_oob_score_classification(): # Check that oob prediction is a good estimation of the generalization # error. rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, random_state=rng) for base_estimator in [DecisionTreeClassifier(), SVC()]: clf = BaggingClassifier(base_estimator=base_estimator, n_estimators=100, bootstrap=True, oob_score=True, random_state=rng).fit(X_train, y_train) test_score = clf.score(X_test, y_test) assert_less(abs(test_score - clf.oob_score_), 0.1) # Test with few estimators assert_warns(UserWarning, BaggingClassifier(base_estimator=base_estimator, n_estimators=1, bootstrap=True, oob_score=True, random_state=rng).fit, X_train, y_train) def test_oob_score_regression(): # Check that oob prediction is a good estimation of the generalization # error. rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=rng) clf = BaggingRegressor(base_estimator=DecisionTreeRegressor(), n_estimators=50, bootstrap=True, oob_score=True, random_state=rng).fit(X_train, y_train) test_score = clf.score(X_test, y_test) assert_less(abs(test_score - clf.oob_score_), 0.1) # Test with few estimators assert_warns(UserWarning, BaggingRegressor(base_estimator=DecisionTreeRegressor(), n_estimators=1, bootstrap=True, oob_score=True, random_state=rng).fit, X_train, y_train) def test_single_estimator(): # Check singleton ensembles. rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=rng) clf1 = BaggingRegressor(base_estimator=KNeighborsRegressor(), n_estimators=1, bootstrap=False, bootstrap_features=False, random_state=rng).fit(X_train, y_train) clf2 = KNeighborsRegressor().fit(X_train, y_train) assert_array_equal(clf1.predict(X_test), clf2.predict(X_test)) def test_error(): # Test that it gives proper exception on deficient input. X, y = iris.data, iris.target base = DecisionTreeClassifier() # Test max_samples assert_raises(ValueError, BaggingClassifier(base, max_samples=-1).fit, X, y) assert_raises(ValueError, BaggingClassifier(base, max_samples=0.0).fit, X, y) assert_raises(ValueError, BaggingClassifier(base, max_samples=2.0).fit, X, y) assert_raises(ValueError, BaggingClassifier(base, max_samples=1000).fit, X, y) assert_raises(ValueError, BaggingClassifier(base, max_samples="foobar").fit, X, y) # Test max_features assert_raises(ValueError, BaggingClassifier(base, max_features=-1).fit, X, y) assert_raises(ValueError, BaggingClassifier(base, max_features=0.0).fit, X, y) assert_raises(ValueError, BaggingClassifier(base, max_features=2.0).fit, X, y) assert_raises(ValueError, BaggingClassifier(base, max_features=5).fit, X, y) assert_raises(ValueError, BaggingClassifier(base, max_features="foobar").fit, X, y) # Test support of decision_function assert_false(hasattr(BaggingClassifier(base).fit(X, y), 'decision_function')) def test_parallel_classification(): # Check parallel classification. rng = check_random_state(0) # Classification X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, random_state=rng) ensemble = BaggingClassifier(DecisionTreeClassifier(), n_jobs=3, random_state=0).fit(X_train, y_train) # predict_proba ensemble.set_params(n_jobs=1) y1 = ensemble.predict_proba(X_test) ensemble.set_params(n_jobs=2) y2 = ensemble.predict_proba(X_test) assert_array_almost_equal(y1, y2) ensemble = BaggingClassifier(DecisionTreeClassifier(), n_jobs=1, random_state=0).fit(X_train, y_train) y3 = ensemble.predict_proba(X_test) assert_array_almost_equal(y1, y3) # decision_function ensemble = BaggingClassifier(SVC(decision_function_shape='ovr'), n_jobs=3, random_state=0).fit(X_train, y_train) ensemble.set_params(n_jobs=1) decisions1 = ensemble.decision_function(X_test) ensemble.set_params(n_jobs=2) decisions2 = ensemble.decision_function(X_test) assert_array_almost_equal(decisions1, decisions2) ensemble = BaggingClassifier(SVC(decision_function_shape='ovr'), n_jobs=1, random_state=0).fit(X_train, y_train) decisions3 = ensemble.decision_function(X_test) assert_array_almost_equal(decisions1, decisions3) def test_parallel_regression(): # Check parallel regression. rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=rng) ensemble = BaggingRegressor(DecisionTreeRegressor(), n_jobs=3, random_state=0).fit(X_train, y_train) ensemble.set_params(n_jobs=1) y1 = ensemble.predict(X_test) ensemble.set_params(n_jobs=2) y2 = ensemble.predict(X_test) assert_array_almost_equal(y1, y2) ensemble = BaggingRegressor(DecisionTreeRegressor(), n_jobs=1, random_state=0).fit(X_train, y_train) y3 = ensemble.predict(X_test) assert_array_almost_equal(y1, y3) def test_gridsearch(): # Check that bagging ensembles can be grid-searched. # Transform iris into a binary classification task X, y = iris.data, iris.target y[y == 2] = 1 # Grid search with scoring based on decision_function parameters = {'n_estimators': (1, 2), 'base_estimator__C': (1, 2)} GridSearchCV(BaggingClassifier(SVC()), parameters, scoring="roc_auc").fit(X, y) def test_base_estimator(): # Check base_estimator and its default values. rng = check_random_state(0) # Classification X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, random_state=rng) ensemble = BaggingClassifier(None, n_jobs=3, random_state=0).fit(X_train, y_train) assert_true(isinstance(ensemble.base_estimator_, DecisionTreeClassifier)) ensemble = BaggingClassifier(DecisionTreeClassifier(), n_jobs=3, random_state=0).fit(X_train, y_train) assert_true(isinstance(ensemble.base_estimator_, DecisionTreeClassifier)) ensemble = BaggingClassifier(Perceptron(), n_jobs=3, random_state=0).fit(X_train, y_train) assert_true(isinstance(ensemble.base_estimator_, Perceptron)) # Regression X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=rng) ensemble = BaggingRegressor(None, n_jobs=3, random_state=0).fit(X_train, y_train) assert_true(isinstance(ensemble.base_estimator_, DecisionTreeRegressor)) ensemble = BaggingRegressor(DecisionTreeRegressor(), n_jobs=3, random_state=0).fit(X_train, y_train) assert_true(isinstance(ensemble.base_estimator_, DecisionTreeRegressor)) ensemble = BaggingRegressor(SVR(), n_jobs=3, random_state=0).fit(X_train, y_train) assert_true(isinstance(ensemble.base_estimator_, SVR)) def test_bagging_with_pipeline(): estimator = BaggingClassifier(make_pipeline(SelectKBest(k=1), DecisionTreeClassifier()), max_features=2) estimator.fit(iris.data, iris.target) class DummyZeroEstimator(BaseEstimator): def fit(self, X, y): self.classes_ = np.unique(y) return self def predict(self, X): return self.classes_[np.zeros(X.shape[0], dtype=int)] def test_bagging_sample_weight_unsupported_but_passed(): estimator = BaggingClassifier(DummyZeroEstimator()) rng = check_random_state(0) estimator.fit(iris.data, iris.target).predict(iris.data) assert_raises(ValueError, estimator.fit, iris.data, iris.target, sample_weight=rng.randint(10, size=(iris.data.shape[0]))) def test_warm_start(random_state=42): # Test if fitting incrementally with warm start gives a forest of the # right size and the same results as a normal fit. X, y = make_hastie_10_2(n_samples=20, random_state=1) clf_ws = None for n_estimators in [5, 10]: if clf_ws is None: clf_ws = BaggingClassifier(n_estimators=n_estimators, random_state=random_state, warm_start=True) else: clf_ws.set_params(n_estimators=n_estimators) clf_ws.fit(X, y) assert_equal(len(clf_ws), n_estimators) clf_no_ws = BaggingClassifier(n_estimators=10, random_state=random_state, warm_start=False) clf_no_ws.fit(X, y) assert_equal(set([tree.random_state for tree in clf_ws]), set([tree.random_state for tree in clf_no_ws])) def test_warm_start_smaller_n_estimators(): # Test if warm start'ed second fit with smaller n_estimators raises error. X, y = make_hastie_10_2(n_samples=20, random_state=1) clf = BaggingClassifier(n_estimators=5, warm_start=True) clf.fit(X, y) clf.set_params(n_estimators=4) assert_raises(ValueError, clf.fit, X, y) def test_warm_start_equal_n_estimators(): # Test that nothing happens when fitting without increasing n_estimators X, y = make_hastie_10_2(n_samples=20, random_state=1) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=43) clf = BaggingClassifier(n_estimators=5, warm_start=True, random_state=83) clf.fit(X_train, y_train) y_pred = clf.predict(X_test) # modify X to nonsense values, this should not change anything X_train += 1. assert_warns_message(UserWarning, "Warm-start fitting without increasing n_estimators does not", clf.fit, X_train, y_train) assert_array_equal(y_pred, clf.predict(X_test)) def test_warm_start_equivalence(): # warm started classifier with 5+5 estimators should be equivalent to # one classifier with 10 estimators X, y = make_hastie_10_2(n_samples=20, random_state=1) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=43) clf_ws = BaggingClassifier(n_estimators=5, warm_start=True, random_state=3141) clf_ws.fit(X_train, y_train) clf_ws.set_params(n_estimators=10) clf_ws.fit(X_train, y_train) y1 = clf_ws.predict(X_test) clf = BaggingClassifier(n_estimators=10, warm_start=False, random_state=3141) clf.fit(X_train, y_train) y2 = clf.predict(X_test) assert_array_almost_equal(y1, y2) def test_warm_start_with_oob_score_fails(): # Check using oob_score and warm_start simultaneously fails X, y = make_hastie_10_2(n_samples=20, random_state=1) clf = BaggingClassifier(n_estimators=5, warm_start=True, oob_score=True) assert_raises(ValueError, clf.fit, X, y) def test_oob_score_removed_on_warm_start(): X, y = make_hastie_10_2(n_samples=2000, random_state=1) clf = BaggingClassifier(n_estimators=50, oob_score=True) clf.fit(X, y) clf.set_params(warm_start=True, oob_score=False, n_estimators=100) clf.fit(X, y) assert_raises(AttributeError, getattr, clf, "oob_score_")
bsd-3-clause
ahara/kaggle_otto
otto/model/model_03_svm/svm.py
1
2661
""" 5-fold CV - log loss 0.513778609795 """ import numpy as np import os from hyperopt import fmin, hp, tpe from sklearn import feature_extraction, preprocessing, svm from sklearn.calibration import CalibratedClassifierCV from sklearn.multiclass import OneVsRestClassifier from otto_utils import consts, utils MODEL_NAME = 'model_03_svm' MODE = 'cv' # cv|submission|holdout|tune # import data train, labels, test, _, _ = utils.load_data() # transform counts to TFIDF features tfidf = feature_extraction.text.TfidfTransformer(smooth_idf=False) train = tfidf.fit_transform(train).toarray() test = tfidf.transform(test).toarray() # encode labels lbl_enc = preprocessing.LabelEncoder() labels = lbl_enc.fit_transform(labels) # train classifier clf = OneVsRestClassifier(svm.SVC(C=4.919646+2., kernel='rbf', tol=.001, verbose=True, probability=True, gamma=0.646508+.3, random_state=23)) if MODE == 'cv': scores, predictions = utils.make_blender_cv(clf, train, labels, calibrate=True) print 'CV:', scores, 'Mean log loss:', np.mean(scores) utils.write_blender_data(consts.BLEND_PATH, MODEL_NAME + '.csv', predictions) elif MODE == 'submission': calibrated_classifier = CalibratedClassifierCV(clf, method='isotonic', cv=utils.get_cv(labels)) fitted_classifier = calibrated_classifier.fit(train, labels) predictions = fitted_classifier.predict_proba(test) utils.save_submission(consts.DATA_SAMPLE_SUBMISSION_PATH, os.path.join(consts.ENSEMBLE_PATH, MODEL_NAME + '.csv'), predictions) elif MODE == 'holdout': score = utils.hold_out_evaluation(clf, train, labels, calibrate=False, test_size=0.9) print 'Log loss:', score elif MODE == 'tune': train, labels, valid, valid_labels = utils.stratified_split(train, labels, test_size=.8) from sklearn.metrics import log_loss # Objective function def objective(args): c, gamma = args clf = OneVsRestClassifier(svm.SVC(C=c, kernel='rbf', tol=.001, gamma=gamma, probability=True, random_state=23)) score1 = 0 score2 = utils.hold_out_evaluation(clf, train, labels, calibrate=False) score = log_loss(valid_labels, clf.predict_proba(valid)) print 'C=%f, gamma=%f, score1=%f, score2=%f, score=%f' % (c, gamma, score1, score2, score) return score # Searching space space = ( hp.uniform('c', 4, 10), hp.uniform('gamma', 0.3, 3) ) best_sln = fmin(objective, space, algo=tpe.suggest, max_evals=200) print 'Best solution:', best_sln else: print 'Unknown mode'
bsd-3-clause
itoledoc/gWTO3
DsaScorers3.py
1
4632
import numpy as np import pandas as pd import math def calc_cond_score(pwv, maxpwvc, fraction): """ :param pwv: :param maxpwvc: :param fraction: :return: """ frac = 1. / fraction pwv_corr = 1 - (abs(pwv - maxpwvc) / 4.) if pwv_corr < 0.1: pwv_corr = 0.1 if frac < 1: x = frac - 1. sb_cond_score = 10 * (1 - (x ** 10.)) * pwv_corr elif frac == 1: sb_cond_score = 10. else: x = frac - 1 if frac <= 1.3: sb_cond_score = (1. - (x / 0.3) ** 3.) * 10. * pwv_corr else: sb_cond_score = 0. return sb_cond_score def calc_array_score(name, array_kind, ar, dec, array_ar_sb, minar, maxar): c_bmax = (0.4001 / np.cos(math.radians(-23.0262015) - math.radians(dec)) + 0.6103) corr = 1. / c_bmax if array_kind == 'SEVEN-M' or array_kind == 'TP-Array': sb_array_score = 10. corr = 0 elif array_ar_sb == np.NaN or array_ar_sb <= 0: sb_array_score = 0. else: arcorr = ar * corr # if arcorr > maxar or arcorr < minar: # print("WTF??? %s" % name) if name.endswith('_TC'): arcorr = minar / 0.8 if arcorr > 3.35: arcorr = 3.35 if arcorr < 0.075: arcorr = 0.075 if 0.9 * arcorr <= array_ar_sb <= 1.1 * arcorr: sb_array_score = 10. elif 0.8 * arcorr < array_ar_sb <= 1.2 * arcorr: sb_array_score = 8.0 elif array_ar_sb < 0.8 * arcorr: # and not points: l = 0.8 * arcorr - minar sb_array_score = ((array_ar_sb - minar) / l) * 8.0 elif array_ar_sb > 1.2 * arcorr: l = arcorr * 1.2 - maxar try: s = 8. / l except ZeroDivisionError: s = 8. / 1.e-5 sb_array_score = (array_ar_sb - maxar) * s else: # print("What happened with %s?" % name) sb_array_score = -1. return sb_array_score, ar * corr def calc_sb_completion(observed, execount): sb_completion = observed / execount return 6 * sb_completion + 4. def calc_executive_score(): return 10. def calc_sciencerank_score(srank, max_scirank=1400.): sb_science_score = 10. * (max_scirank - srank) / max_scirank return sb_science_score def calc_cycle_grade_score(grade, cycle): if grade == 'A' and str(cycle).startswith('2015'): sb_grade_score = 10. elif str(cycle).startswith('2013'): sb_grade_score = 8. elif grade == 'B': sb_grade_score = 4. else: sb_grade_score = -100. return sb_grade_score def calc_ha_scorer(ha): sb_ha_scorer = ((math.cos(math.radians((ha + 1.) * 15.)) - 0.3) / (1 - 0.3)) * 10. return sb_ha_scorer def calc_total_score(scores, weights=None): if not weights: weights = {'cond': 0.35, 'array': 0.05, 'sbcompletion': 0.20, 'executive': 0.05, 'sciencerank': 0.05, 'cyclegrade': 0.20, 'ha': 0.10} score = 0. keys = weights.keys() for n, s in enumerate(scores): score += weights[keys[n]] * s return score def calc_all_scores(pwv, maxpwvc, fraction, name, array_kind, ar, dec, array_ar_sb, minar, maxar, observed, execount, srank, grade, cycle, ha): try: cond_score = calc_cond_score(pwv, maxpwvc, fraction) except ZeroDivisionError: cond_score = -9999.0 array_score = calc_array_score(name, array_kind, ar, dec, array_ar_sb, minar, maxar) sbcompletion_score = calc_sb_completion(observed, execount) executive_score = 10. sciencerank_score = calc_sciencerank_score(srank) cyclegrade_score = calc_cycle_grade_score(grade, cycle) ha_score = calc_ha_scorer(ha) score = calc_total_score( [cond_score, array_score[0], sbcompletion_score, executive_score, sciencerank_score, cyclegrade_score, ha_score]) if cond_score == -9999.0: score = -9999.0 return pd.Series([cond_score, array_score[0], sbcompletion_score, executive_score, sciencerank_score, cyclegrade_score, ha_score, score, array_score[1]], index=[ 'conditon score', 'array score', 'sb completion score', 'executive score', 'science rank score', 'cycle grade score', 'ha score', 'Score', 'AR PI'])
gpl-2.0
ryfeus/lambda-packs
Sklearn_scipy_numpy/source/scipy/stats/tests/test_morestats.py
17
50896
# Author: Travis Oliphant, 2002 # # Further enhancements and tests added by numerous SciPy developers. # from __future__ import division, print_function, absolute_import import warnings import numpy as np from numpy.random import RandomState from numpy.testing import (TestCase, run_module_suite, assert_array_equal, assert_almost_equal, assert_array_less, assert_array_almost_equal, assert_raises, assert_, assert_allclose, assert_equal, dec, assert_warns) from scipy import stats from common_tests import check_named_results # Matplotlib is not a scipy dependency but is optionally used in probplot, so # check if it's available try: import matplotlib.pyplot as plt have_matplotlib = True except: have_matplotlib = False g1 = [1.006, 0.996, 0.998, 1.000, 0.992, 0.993, 1.002, 0.999, 0.994, 1.000] g2 = [0.998, 1.006, 1.000, 1.002, 0.997, 0.998, 0.996, 1.000, 1.006, 0.988] g3 = [0.991, 0.987, 0.997, 0.999, 0.995, 0.994, 1.000, 0.999, 0.996, 0.996] g4 = [1.005, 1.002, 0.994, 1.000, 0.995, 0.994, 0.998, 0.996, 1.002, 0.996] g5 = [0.998, 0.998, 0.982, 0.990, 1.002, 0.984, 0.996, 0.993, 0.980, 0.996] g6 = [1.009, 1.013, 1.009, 0.997, 0.988, 1.002, 0.995, 0.998, 0.981, 0.996] g7 = [0.990, 1.004, 0.996, 1.001, 0.998, 1.000, 1.018, 1.010, 0.996, 1.002] g8 = [0.998, 1.000, 1.006, 1.000, 1.002, 0.996, 0.998, 0.996, 1.002, 1.006] g9 = [1.002, 0.998, 0.996, 0.995, 0.996, 1.004, 1.004, 0.998, 0.999, 0.991] g10 = [0.991, 0.995, 0.984, 0.994, 0.997, 0.997, 0.991, 0.998, 1.004, 0.997] class TestBayes_mvs(TestCase): def test_basic(self): # Expected values in this test simply taken from the function. For # some checks regarding correctness of implementation, see review in # gh-674 data = [6, 9, 12, 7, 8, 8, 13] mean, var, std = stats.bayes_mvs(data) assert_almost_equal(mean.statistic, 9.0) assert_allclose(mean.minmax, (7.1036502226125329, 10.896349777387467), rtol=1e-14) assert_almost_equal(var.statistic, 10.0) assert_allclose(var.minmax, (3.1767242068607087, 24.45910381334018), rtol=1e-09) assert_almost_equal(std.statistic, 2.9724954732045084, decimal=14) assert_allclose(std.minmax, (1.7823367265645145, 4.9456146050146312), rtol=1e-14) def test_empty_input(self): assert_raises(ValueError, stats.bayes_mvs, []) def test_result_attributes(self): x = np.arange(15) attributes = ('statistic', 'minmax') res = stats.bayes_mvs(x) for i in res: check_named_results(i, attributes) class TestMvsdist(TestCase): def test_basic(self): data = [6, 9, 12, 7, 8, 8, 13] mean, var, std = stats.mvsdist(data) assert_almost_equal(mean.mean(), 9.0) assert_allclose(mean.interval(0.9), (7.1036502226125329, 10.896349777387467), rtol=1e-14) assert_almost_equal(var.mean(), 10.0) assert_allclose(var.interval(0.9), (3.1767242068607087, 24.45910381334018), rtol=1e-09) assert_almost_equal(std.mean(), 2.9724954732045084, decimal=14) assert_allclose(std.interval(0.9), (1.7823367265645145, 4.9456146050146312), rtol=1e-14) def test_empty_input(self): assert_raises(ValueError, stats.mvsdist, []) def test_bad_arg(self): # Raise ValueError if fewer than two data points are given. data = [1] assert_raises(ValueError, stats.mvsdist, data) def test_warns(self): # regression test for gh-5270 # make sure there are no spurious divide-by-zero warnings with warnings.catch_warnings(): warnings.simplefilter('error', RuntimeWarning) [x.mean() for x in stats.mvsdist([1, 2, 3])] [x.mean() for x in stats.mvsdist([1, 2, 3, 4, 5])] class TestShapiro(TestCase): def test_basic(self): x1 = [0.11,7.87,4.61,10.14,7.95,3.14,0.46, 4.43,0.21,4.75,0.71,1.52,3.24, 0.93,0.42,4.97,9.53,4.55,0.47,6.66] w,pw = stats.shapiro(x1) assert_almost_equal(w,0.90047299861907959,6) assert_almost_equal(pw,0.042089745402336121,6) x2 = [1.36,1.14,2.92,2.55,1.46,1.06,5.27,-1.11, 3.48,1.10,0.88,-0.51,1.46,0.52,6.20,1.69, 0.08,3.67,2.81,3.49] w,pw = stats.shapiro(x2) assert_almost_equal(w,0.9590270,6) assert_almost_equal(pw,0.52460,3) # Verified against R np.random.seed(12345678) x3 = stats.norm.rvs(loc=5, scale=3, size=100) w, pw = stats.shapiro(x3) assert_almost_equal(w, 0.9772805571556091, decimal=6) assert_almost_equal(pw, 0.08144091814756393, decimal=3) # Extracted from original paper x4 = [0.139, 0.157, 0.175, 0.256, 0.344, 0.413, 0.503, 0.577, 0.614, 0.655, 0.954, 1.392, 1.557, 1.648, 1.690, 1.994, 2.174, 2.206, 3.245, 3.510, 3.571, 4.354, 4.980, 6.084, 8.351] W_expected = 0.83467 p_expected = 0.000914 w, pw = stats.shapiro(x4) assert_almost_equal(w, W_expected, decimal=4) assert_almost_equal(pw, p_expected, decimal=5) def test_2d(self): x1 = [[0.11, 7.87, 4.61, 10.14, 7.95, 3.14, 0.46, 4.43, 0.21, 4.75], [0.71, 1.52, 3.24, 0.93, 0.42, 4.97, 9.53, 4.55, 0.47, 6.66]] w, pw = stats.shapiro(x1) assert_almost_equal(w, 0.90047299861907959, 6) assert_almost_equal(pw, 0.042089745402336121, 6) x2 = [[1.36, 1.14, 2.92, 2.55, 1.46, 1.06, 5.27, -1.11, 3.48, 1.10], [0.88, -0.51, 1.46, 0.52, 6.20, 1.69, 0.08, 3.67, 2.81, 3.49]] w, pw = stats.shapiro(x2) assert_almost_equal(w, 0.9590270, 6) assert_almost_equal(pw, 0.52460, 3) def test_empty_input(self): assert_raises(ValueError, stats.shapiro, []) assert_raises(ValueError, stats.shapiro, [[], [], []]) def test_not_enough_values(self): assert_raises(ValueError, stats.shapiro, [1, 2]) assert_raises(ValueError, stats.shapiro, [[], [2]]) def test_bad_arg(self): # Length of x is less than 3. x = [1] assert_raises(ValueError, stats.shapiro, x) def test_nan_input(self): x = np.arange(10.) x[9] = np.nan w, pw = stats.shapiro(x) assert_equal(w, np.nan) assert_almost_equal(pw, 1.0) class TestAnderson(TestCase): def test_normal(self): rs = RandomState(1234567890) x1 = rs.standard_exponential(size=50) x2 = rs.standard_normal(size=50) A,crit,sig = stats.anderson(x1) assert_array_less(crit[:-1], A) A,crit,sig = stats.anderson(x2) assert_array_less(A, crit[-2:]) def test_expon(self): rs = RandomState(1234567890) x1 = rs.standard_exponential(size=50) x2 = rs.standard_normal(size=50) A,crit,sig = stats.anderson(x1,'expon') assert_array_less(A, crit[-2:]) olderr = np.seterr(all='ignore') try: A,crit,sig = stats.anderson(x2,'expon') finally: np.seterr(**olderr) assert_(A > crit[-1]) def test_bad_arg(self): assert_raises(ValueError, stats.anderson, [1], dist='plate_of_shrimp') def test_result_attributes(self): rs = RandomState(1234567890) x = rs.standard_exponential(size=50) res = stats.anderson(x) attributes = ('statistic', 'critical_values', 'significance_level') check_named_results(res, attributes) class TestAndersonKSamp(TestCase): def test_example1a(self): # Example data from Scholz & Stephens (1987), originally # published in Lehmann (1995, Nonparametrics, Statistical # Methods Based on Ranks, p. 309) # Pass a mixture of lists and arrays t1 = [38.7, 41.5, 43.8, 44.5, 45.5, 46.0, 47.7, 58.0] t2 = np.array([39.2, 39.3, 39.7, 41.4, 41.8, 42.9, 43.3, 45.8]) t3 = np.array([34.0, 35.0, 39.0, 40.0, 43.0, 43.0, 44.0, 45.0]) t4 = np.array([34.0, 34.8, 34.8, 35.4, 37.2, 37.8, 41.2, 42.8]) assert_warns(UserWarning, stats.anderson_ksamp, (t1, t2, t3, t4), midrank=False) with warnings.catch_warnings(): warnings.filterwarnings('ignore', message='approximate p-value') Tk, tm, p = stats.anderson_ksamp((t1, t2, t3, t4), midrank=False) assert_almost_equal(Tk, 4.449, 3) assert_array_almost_equal([0.4985, 1.3237, 1.9158, 2.4930, 3.2459], tm, 4) assert_almost_equal(p, 0.0021, 4) def test_example1b(self): # Example data from Scholz & Stephens (1987), originally # published in Lehmann (1995, Nonparametrics, Statistical # Methods Based on Ranks, p. 309) # Pass arrays t1 = np.array([38.7, 41.5, 43.8, 44.5, 45.5, 46.0, 47.7, 58.0]) t2 = np.array([39.2, 39.3, 39.7, 41.4, 41.8, 42.9, 43.3, 45.8]) t3 = np.array([34.0, 35.0, 39.0, 40.0, 43.0, 43.0, 44.0, 45.0]) t4 = np.array([34.0, 34.8, 34.8, 35.4, 37.2, 37.8, 41.2, 42.8]) with warnings.catch_warnings(): warnings.filterwarnings('ignore', message='approximate p-value') Tk, tm, p = stats.anderson_ksamp((t1, t2, t3, t4), midrank=True) assert_almost_equal(Tk, 4.480, 3) assert_array_almost_equal([0.4985, 1.3237, 1.9158, 2.4930, 3.2459], tm, 4) assert_almost_equal(p, 0.0020, 4) def test_example2a(self): # Example data taken from an earlier technical report of # Scholz and Stephens # Pass lists instead of arrays t1 = [194, 15, 41, 29, 33, 181] t2 = [413, 14, 58, 37, 100, 65, 9, 169, 447, 184, 36, 201, 118] t3 = [34, 31, 18, 18, 67, 57, 62, 7, 22, 34] t4 = [90, 10, 60, 186, 61, 49, 14, 24, 56, 20, 79, 84, 44, 59, 29, 118, 25, 156, 310, 76, 26, 44, 23, 62] t5 = [130, 208, 70, 101, 208] t6 = [74, 57, 48, 29, 502, 12, 70, 21, 29, 386, 59, 27] t7 = [55, 320, 56, 104, 220, 239, 47, 246, 176, 182, 33] t8 = [23, 261, 87, 7, 120, 14, 62, 47, 225, 71, 246, 21, 42, 20, 5, 12, 120, 11, 3, 14, 71, 11, 14, 11, 16, 90, 1, 16, 52, 95] t9 = [97, 51, 11, 4, 141, 18, 142, 68, 77, 80, 1, 16, 106, 206, 82, 54, 31, 216, 46, 111, 39, 63, 18, 191, 18, 163, 24] t10 = [50, 44, 102, 72, 22, 39, 3, 15, 197, 188, 79, 88, 46, 5, 5, 36, 22, 139, 210, 97, 30, 23, 13, 14] t11 = [359, 9, 12, 270, 603, 3, 104, 2, 438] t12 = [50, 254, 5, 283, 35, 12] t13 = [487, 18, 100, 7, 98, 5, 85, 91, 43, 230, 3, 130] t14 = [102, 209, 14, 57, 54, 32, 67, 59, 134, 152, 27, 14, 230, 66, 61, 34] with warnings.catch_warnings(): warnings.filterwarnings('ignore', message='approximate p-value') Tk, tm, p = stats.anderson_ksamp((t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14), midrank=False) assert_almost_equal(Tk, 3.288, 3) assert_array_almost_equal([0.5990, 1.3269, 1.8052, 2.2486, 2.8009], tm, 4) assert_almost_equal(p, 0.0041, 4) def test_example2b(self): # Example data taken from an earlier technical report of # Scholz and Stephens t1 = [194, 15, 41, 29, 33, 181] t2 = [413, 14, 58, 37, 100, 65, 9, 169, 447, 184, 36, 201, 118] t3 = [34, 31, 18, 18, 67, 57, 62, 7, 22, 34] t4 = [90, 10, 60, 186, 61, 49, 14, 24, 56, 20, 79, 84, 44, 59, 29, 118, 25, 156, 310, 76, 26, 44, 23, 62] t5 = [130, 208, 70, 101, 208] t6 = [74, 57, 48, 29, 502, 12, 70, 21, 29, 386, 59, 27] t7 = [55, 320, 56, 104, 220, 239, 47, 246, 176, 182, 33] t8 = [23, 261, 87, 7, 120, 14, 62, 47, 225, 71, 246, 21, 42, 20, 5, 12, 120, 11, 3, 14, 71, 11, 14, 11, 16, 90, 1, 16, 52, 95] t9 = [97, 51, 11, 4, 141, 18, 142, 68, 77, 80, 1, 16, 106, 206, 82, 54, 31, 216, 46, 111, 39, 63, 18, 191, 18, 163, 24] t10 = [50, 44, 102, 72, 22, 39, 3, 15, 197, 188, 79, 88, 46, 5, 5, 36, 22, 139, 210, 97, 30, 23, 13, 14] t11 = [359, 9, 12, 270, 603, 3, 104, 2, 438] t12 = [50, 254, 5, 283, 35, 12] t13 = [487, 18, 100, 7, 98, 5, 85, 91, 43, 230, 3, 130] t14 = [102, 209, 14, 57, 54, 32, 67, 59, 134, 152, 27, 14, 230, 66, 61, 34] with warnings.catch_warnings(): warnings.filterwarnings('ignore', message='approximate p-value') Tk, tm, p = stats.anderson_ksamp((t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14), midrank=True) assert_almost_equal(Tk, 3.294, 3) assert_array_almost_equal([0.5990, 1.3269, 1.8052, 2.2486, 2.8009], tm, 4) assert_almost_equal(p, 0.0041, 4) def test_not_enough_samples(self): assert_raises(ValueError, stats.anderson_ksamp, np.ones(5)) def test_no_distinct_observations(self): assert_raises(ValueError, stats.anderson_ksamp, (np.ones(5), np.ones(5))) def test_empty_sample(self): assert_raises(ValueError, stats.anderson_ksamp, (np.ones(5), [])) def test_result_attributes(self): # Example data from Scholz & Stephens (1987), originally # published in Lehmann (1995, Nonparametrics, Statistical # Methods Based on Ranks, p. 309) # Pass a mixture of lists and arrays t1 = [38.7, 41.5, 43.8, 44.5, 45.5, 46.0, 47.7, 58.0] t2 = np.array([39.2, 39.3, 39.7, 41.4, 41.8, 42.9, 43.3, 45.8]) t3 = np.array([34.0, 35.0, 39.0, 40.0, 43.0, 43.0, 44.0, 45.0]) t4 = np.array([34.0, 34.8, 34.8, 35.4, 37.2, 37.8, 41.2, 42.8]) with warnings.catch_warnings(): warnings.filterwarnings('ignore', message='approximate p-value') res = stats.anderson_ksamp((t1, t2, t3, t4), midrank=False) attributes = ('statistic', 'critical_values', 'significance_level') check_named_results(res, attributes) class TestAnsari(TestCase): def test_small(self): x = [1,2,3,3,4] y = [3,2,6,1,6,1,4,1] with warnings.catch_warnings(record=True): # Ties preclude use ... W, pval = stats.ansari(x,y) assert_almost_equal(W,23.5,11) assert_almost_equal(pval,0.13499256881897437,11) def test_approx(self): ramsay = np.array((111, 107, 100, 99, 102, 106, 109, 108, 104, 99, 101, 96, 97, 102, 107, 113, 116, 113, 110, 98)) parekh = np.array((107, 108, 106, 98, 105, 103, 110, 105, 104, 100, 96, 108, 103, 104, 114, 114, 113, 108, 106, 99)) with warnings.catch_warnings(): warnings.filterwarnings('ignore', message="Ties preclude use of exact statistic.") W, pval = stats.ansari(ramsay, parekh) assert_almost_equal(W,185.5,11) assert_almost_equal(pval,0.18145819972867083,11) def test_exact(self): W,pval = stats.ansari([1,2,3,4],[15,5,20,8,10,12]) assert_almost_equal(W,10.0,11) assert_almost_equal(pval,0.533333333333333333,7) def test_bad_arg(self): assert_raises(ValueError, stats.ansari, [], [1]) assert_raises(ValueError, stats.ansari, [1], []) def test_result_attributes(self): x = [1, 2, 3, 3, 4] y = [3, 2, 6, 1, 6, 1, 4, 1] with warnings.catch_warnings(record=True): # Ties preclude use ... res = stats.ansari(x, y) attributes = ('statistic', 'pvalue') check_named_results(res, attributes) class TestBartlett(TestCase): def test_data(self): args = [g1, g2, g3, g4, g5, g6, g7, g8, g9, g10] T, pval = stats.bartlett(*args) assert_almost_equal(T,20.78587342806484,7) assert_almost_equal(pval,0.0136358632781,7) def test_bad_arg(self): # Too few args raises ValueError. assert_raises(ValueError, stats.bartlett, [1]) def test_result_attributes(self): args = [g1, g2, g3, g4, g5, g6, g7, g8, g9, g10] res = stats.bartlett(*args) attributes = ('statistic', 'pvalue') check_named_results(res, attributes) def test_empty_arg(self): args = (g1, g2, g3, g4, g5, g6, g7, g8, g9, g10, []) assert_equal((np.nan, np.nan), stats.bartlett(*args)) class TestLevene(TestCase): def test_data(self): args = [g1, g2, g3, g4, g5, g6, g7, g8, g9, g10] W, pval = stats.levene(*args) assert_almost_equal(W,1.7059176930008939,7) assert_almost_equal(pval,0.0990829755522,7) def test_trimmed1(self): # Test that center='trimmed' gives the same result as center='mean' # when proportiontocut=0. W1, pval1 = stats.levene(g1, g2, g3, center='mean') W2, pval2 = stats.levene(g1, g2, g3, center='trimmed', proportiontocut=0.0) assert_almost_equal(W1, W2) assert_almost_equal(pval1, pval2) def test_trimmed2(self): x = [1.2, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 100.0] y = [0.0, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 200.0] np.random.seed(1234) x2 = np.random.permutation(x) # Use center='trimmed' W0, pval0 = stats.levene(x, y, center='trimmed', proportiontocut=0.125) W1, pval1 = stats.levene(x2, y, center='trimmed', proportiontocut=0.125) # Trim the data here, and use center='mean' W2, pval2 = stats.levene(x[1:-1], y[1:-1], center='mean') # Result should be the same. assert_almost_equal(W0, W2) assert_almost_equal(W1, W2) assert_almost_equal(pval1, pval2) def test_equal_mean_median(self): x = np.linspace(-1,1,21) np.random.seed(1234) x2 = np.random.permutation(x) y = x**3 W1, pval1 = stats.levene(x, y, center='mean') W2, pval2 = stats.levene(x2, y, center='median') assert_almost_equal(W1, W2) assert_almost_equal(pval1, pval2) def test_bad_keyword(self): x = np.linspace(-1,1,21) assert_raises(TypeError, stats.levene, x, x, portiontocut=0.1) def test_bad_center_value(self): x = np.linspace(-1,1,21) assert_raises(ValueError, stats.levene, x, x, center='trim') def test_too_few_args(self): assert_raises(ValueError, stats.levene, [1]) def test_result_attributes(self): args = [g1, g2, g3, g4, g5, g6, g7, g8, g9, g10] res = stats.levene(*args) attributes = ('statistic', 'pvalue') check_named_results(res, attributes) class TestBinomP(TestCase): def test_data(self): pval = stats.binom_test(100,250) assert_almost_equal(pval,0.0018833009350757682,11) pval = stats.binom_test(201,405) assert_almost_equal(pval,0.92085205962670713,11) pval = stats.binom_test([682,243],p=3.0/4) assert_almost_equal(pval,0.38249155957481695,11) def test_bad_len_x(self): # Length of x must be 1 or 2. assert_raises(ValueError, stats.binom_test, [1,2,3]) def test_bad_n(self): # len(x) is 1, but n is invalid. # Missing n assert_raises(ValueError, stats.binom_test, [100]) # n less than x[0] assert_raises(ValueError, stats.binom_test, [100], n=50) def test_bad_p(self): assert_raises(ValueError, stats.binom_test, [50, 50], p=2.0) def test_alternatives(self): res = stats.binom_test(51, 235, p=1./6, alternative='less') assert_almost_equal(res, 0.982022657605858) res = stats.binom_test(51, 235, p=1./6, alternative='greater') assert_almost_equal(res, 0.02654424571169085) res = stats.binom_test(51, 235, p=1./6, alternative='two-sided') assert_almost_equal(res, 0.0437479701823997) class TestFligner(TestCase): def test_data(self): # numbers from R: fligner.test in package stats x1 = np.arange(5) assert_array_almost_equal(stats.fligner(x1,x1**2), (3.2282229927203536, 0.072379187848207877), 11) def test_trimmed1(self): # Test that center='trimmed' gives the same result as center='mean' # when proportiontocut=0. Xsq1, pval1 = stats.fligner(g1, g2, g3, center='mean') Xsq2, pval2 = stats.fligner(g1, g2, g3, center='trimmed', proportiontocut=0.0) assert_almost_equal(Xsq1, Xsq2) assert_almost_equal(pval1, pval2) def test_trimmed2(self): x = [1.2, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 100.0] y = [0.0, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 200.0] # Use center='trimmed' Xsq1, pval1 = stats.fligner(x, y, center='trimmed', proportiontocut=0.125) # Trim the data here, and use center='mean' Xsq2, pval2 = stats.fligner(x[1:-1], y[1:-1], center='mean') # Result should be the same. assert_almost_equal(Xsq1, Xsq2) assert_almost_equal(pval1, pval2) # The following test looks reasonable at first, but fligner() uses the # function stats.rankdata(), and in one of the cases in this test, # there are ties, while in the other (because of normal rounding # errors) there are not. This difference leads to differences in the # third significant digit of W. # #def test_equal_mean_median(self): # x = np.linspace(-1,1,21) # y = x**3 # W1, pval1 = stats.fligner(x, y, center='mean') # W2, pval2 = stats.fligner(x, y, center='median') # assert_almost_equal(W1, W2) # assert_almost_equal(pval1, pval2) def test_bad_keyword(self): x = np.linspace(-1,1,21) assert_raises(TypeError, stats.fligner, x, x, portiontocut=0.1) def test_bad_center_value(self): x = np.linspace(-1,1,21) assert_raises(ValueError, stats.fligner, x, x, center='trim') def test_bad_num_args(self): # Too few args raises ValueError. assert_raises(ValueError, stats.fligner, [1]) def test_empty_arg(self): x = np.arange(5) assert_equal((np.nan, np.nan), stats.fligner(x, x**2, [])) class TestMood(TestCase): def test_mood(self): # numbers from R: mood.test in package stats x1 = np.arange(5) assert_array_almost_equal(stats.mood(x1, x1**2), (-1.3830857299399906, 0.16663858066771478), 11) def test_mood_order_of_args(self): # z should change sign when the order of arguments changes, pvalue # should not change np.random.seed(1234) x1 = np.random.randn(10, 1) x2 = np.random.randn(15, 1) z1, p1 = stats.mood(x1, x2) z2, p2 = stats.mood(x2, x1) assert_array_almost_equal([z1, p1], [-z2, p2]) def test_mood_with_axis_none(self): #Test with axis = None, compare with results from R x1 = [-0.626453810742332, 0.183643324222082, -0.835628612410047, 1.59528080213779, 0.329507771815361, -0.820468384118015, 0.487429052428485, 0.738324705129217, 0.575781351653492, -0.305388387156356, 1.51178116845085, 0.389843236411431, -0.621240580541804, -2.2146998871775, 1.12493091814311, -0.0449336090152309, -0.0161902630989461, 0.943836210685299, 0.821221195098089, 0.593901321217509] x2 = [-0.896914546624981, 0.184849184646742, 1.58784533120882, -1.13037567424629, -0.0802517565509893, 0.132420284381094, 0.707954729271733, -0.23969802417184, 1.98447393665293, -0.138787012119665, 0.417650750792556, 0.981752777463662, -0.392695355503813, -1.03966897694891, 1.78222896030858, -2.31106908460517, 0.878604580921265, 0.035806718015226, 1.01282869212708, 0.432265154539617, 2.09081920524915, -1.19992581964387, 1.58963820029007, 1.95465164222325, 0.00493777682814261, -2.45170638784613, 0.477237302613617, -0.596558168631403, 0.792203270299649, 0.289636710177348] x1 = np.array(x1) x2 = np.array(x2) x1.shape = (10, 2) x2.shape = (15, 2) assert_array_almost_equal(stats.mood(x1, x2, axis=None), [-1.31716607555, 0.18778296257]) def test_mood_2d(self): # Test if the results of mood test in 2-D case are consistent with the # R result for the same inputs. Numbers from R mood.test(). ny = 5 np.random.seed(1234) x1 = np.random.randn(10, ny) x2 = np.random.randn(15, ny) z_vectest, pval_vectest = stats.mood(x1, x2) for j in range(ny): assert_array_almost_equal([z_vectest[j], pval_vectest[j]], stats.mood(x1[:, j], x2[:, j])) # inverse order of dimensions x1 = x1.transpose() x2 = x2.transpose() z_vectest, pval_vectest = stats.mood(x1, x2, axis=1) for i in range(ny): # check axis handling is self consistent assert_array_almost_equal([z_vectest[i], pval_vectest[i]], stats.mood(x1[i, :], x2[i, :])) def test_mood_3d(self): shape = (10, 5, 6) np.random.seed(1234) x1 = np.random.randn(*shape) x2 = np.random.randn(*shape) for axis in range(3): z_vectest, pval_vectest = stats.mood(x1, x2, axis=axis) # Tests that result for 3-D arrays is equal to that for the # same calculation on a set of 1-D arrays taken from the # 3-D array axes_idx = ([1, 2], [0, 2], [0, 1]) # the two axes != axis for i in range(shape[axes_idx[axis][0]]): for j in range(shape[axes_idx[axis][1]]): if axis == 0: slice1 = x1[:, i, j] slice2 = x2[:, i, j] elif axis == 1: slice1 = x1[i, :, j] slice2 = x2[i, :, j] else: slice1 = x1[i, j, :] slice2 = x2[i, j, :] assert_array_almost_equal([z_vectest[i, j], pval_vectest[i, j]], stats.mood(slice1, slice2)) def test_mood_bad_arg(self): # Raise ValueError when the sum of the lengths of the args is less than 3 assert_raises(ValueError, stats.mood, [1], []) class TestProbplot(TestCase): def test_basic(self): np.random.seed(12345) x = stats.norm.rvs(size=20) osm, osr = stats.probplot(x, fit=False) osm_expected = [-1.8241636, -1.38768012, -1.11829229, -0.91222575, -0.73908135, -0.5857176, -0.44506467, -0.31273668, -0.18568928, -0.06158146, 0.06158146, 0.18568928, 0.31273668, 0.44506467, 0.5857176, 0.73908135, 0.91222575, 1.11829229, 1.38768012, 1.8241636] assert_allclose(osr, np.sort(x)) assert_allclose(osm, osm_expected) res, res_fit = stats.probplot(x, fit=True) res_fit_expected = [1.05361841, 0.31297795, 0.98741609] assert_allclose(res_fit, res_fit_expected) def test_sparams_keyword(self): np.random.seed(123456) x = stats.norm.rvs(size=100) # Check that None, () and 0 (loc=0, for normal distribution) all work # and give the same results osm1, osr1 = stats.probplot(x, sparams=None, fit=False) osm2, osr2 = stats.probplot(x, sparams=0, fit=False) osm3, osr3 = stats.probplot(x, sparams=(), fit=False) assert_allclose(osm1, osm2) assert_allclose(osm1, osm3) assert_allclose(osr1, osr2) assert_allclose(osr1, osr3) # Check giving (loc, scale) params for normal distribution osm, osr = stats.probplot(x, sparams=(), fit=False) def test_dist_keyword(self): np.random.seed(12345) x = stats.norm.rvs(size=20) osm1, osr1 = stats.probplot(x, fit=False, dist='t', sparams=(3,)) osm2, osr2 = stats.probplot(x, fit=False, dist=stats.t, sparams=(3,)) assert_allclose(osm1, osm2) assert_allclose(osr1, osr2) assert_raises(ValueError, stats.probplot, x, dist='wrong-dist-name') assert_raises(AttributeError, stats.probplot, x, dist=[]) class custom_dist(object): """Some class that looks just enough like a distribution.""" def ppf(self, q): return stats.norm.ppf(q, loc=2) osm1, osr1 = stats.probplot(x, sparams=(2,), fit=False) osm2, osr2 = stats.probplot(x, dist=custom_dist(), fit=False) assert_allclose(osm1, osm2) assert_allclose(osr1, osr2) @dec.skipif(not have_matplotlib) def test_plot_kwarg(self): np.random.seed(7654321) fig = plt.figure() fig.add_subplot(111) x = stats.t.rvs(3, size=100) res1, fitres1 = stats.probplot(x, plot=plt) plt.close() res2, fitres2 = stats.probplot(x, plot=None) res3 = stats.probplot(x, fit=False, plot=plt) plt.close() res4 = stats.probplot(x, fit=False, plot=None) # Check that results are consistent between combinations of `fit` and # `plot` keywords. assert_(len(res1) == len(res2) == len(res3) == len(res4) == 2) assert_allclose(res1, res2) assert_allclose(res1, res3) assert_allclose(res1, res4) assert_allclose(fitres1, fitres2) # Check that a Matplotlib Axes object is accepted fig = plt.figure() ax = fig.add_subplot(111) stats.probplot(x, fit=False, plot=ax) plt.close() def test_probplot_bad_args(self): # Raise ValueError when given an invalid distribution. assert_raises(ValueError, stats.probplot, [1], dist="plate_of_shrimp") def test_empty(self): assert_equal(stats.probplot([], fit=False), (np.array([]), np.array([]))) assert_equal(stats.probplot([], fit=True), ((np.array([]), np.array([])), (np.nan, np.nan, 0.0))) def test_array_of_size_one(self): with np.errstate(invalid='ignore'): assert_equal(stats.probplot([1], fit=True), ((np.array([0.]), np.array([1])), (np.nan, np.nan, 0.0))) def test_wilcoxon_bad_arg(): # Raise ValueError when two args of different lengths are given or # zero_method is unknown. assert_raises(ValueError, stats.wilcoxon, [1], [1,2]) assert_raises(ValueError, stats.wilcoxon, [1,2], [1,2], "dummy") class TestKstat(TestCase): def test_moments_normal_distribution(self): np.random.seed(32149) data = np.random.randn(12345) moments = [] for n in [1, 2, 3, 4]: moments.append(stats.kstat(data, n)) expected = [0.011315, 1.017931, 0.05811052, 0.0754134] assert_allclose(moments, expected, rtol=1e-4) # test equivalence with `stats.moment` m1 = stats.moment(data, moment=1) m2 = stats.moment(data, moment=2) m3 = stats.moment(data, moment=3) assert_allclose((m1, m2, m3), expected[:-1], atol=0.02, rtol=1e-2) def test_empty_input(self): assert_raises(ValueError, stats.kstat, []) def test_nan_input(self): data = np.arange(10.) data[6] = np.nan assert_equal(stats.kstat(data), np.nan) def test_kstat_bad_arg(self): # Raise ValueError if n > 4 or n < 1. data = np.arange(10) for n in [0, 4.001]: assert_raises(ValueError, stats.kstat, data, n=n) class TestKstatVar(TestCase): def test_empty_input(self): assert_raises(ValueError, stats.kstatvar, []) def test_nan_input(self): data = np.arange(10.) data[6] = np.nan assert_equal(stats.kstat(data), np.nan) def test_bad_arg(self): # Raise ValueError is n is not 1 or 2. data = [1] n = 10 assert_raises(ValueError, stats.kstatvar, data, n=n) class TestPpccPlot(TestCase): def setUp(self): np.random.seed(7654321) self.x = stats.loggamma.rvs(5, size=500) + 5 def test_basic(self): N = 5 svals, ppcc = stats.ppcc_plot(self.x, -10, 10, N=N) ppcc_expected = [0.21139644, 0.21384059, 0.98766719, 0.97980182, 0.93519298] assert_allclose(svals, np.linspace(-10, 10, num=N)) assert_allclose(ppcc, ppcc_expected) def test_dist(self): # Test that we can specify distributions both by name and as objects. svals1, ppcc1 = stats.ppcc_plot(self.x, -10, 10, dist='tukeylambda') svals2, ppcc2 = stats.ppcc_plot(self.x, -10, 10, dist=stats.tukeylambda) assert_allclose(svals1, svals2, rtol=1e-20) assert_allclose(ppcc1, ppcc2, rtol=1e-20) # Test that 'tukeylambda' is the default dist svals3, ppcc3 = stats.ppcc_plot(self.x, -10, 10) assert_allclose(svals1, svals3, rtol=1e-20) assert_allclose(ppcc1, ppcc3, rtol=1e-20) @dec.skipif(not have_matplotlib) def test_plot_kwarg(self): # Check with the matplotlib.pyplot module fig = plt.figure() fig.add_subplot(111) stats.ppcc_plot(self.x, -20, 20, plot=plt) plt.close() # Check that a Matplotlib Axes object is accepted fig.add_subplot(111) ax = fig.add_subplot(111) stats.ppcc_plot(self.x, -20, 20, plot=ax) plt.close() def test_invalid_inputs(self): # `b` has to be larger than `a` assert_raises(ValueError, stats.ppcc_plot, self.x, 1, 0) # Raise ValueError when given an invalid distribution. assert_raises(ValueError, stats.ppcc_plot, [1, 2, 3], 0, 1, dist="plate_of_shrimp") def test_empty(self): # For consistency with probplot return for one empty array, # ppcc contains all zeros and svals is the same as for normal array # input. svals, ppcc = stats.ppcc_plot([], 0, 1) assert_allclose(svals, np.linspace(0, 1, num=80)) assert_allclose(ppcc, np.zeros(80, dtype=float)) class TestPpccMax(TestCase): def test_ppcc_max_bad_arg(self): # Raise ValueError when given an invalid distribution. data = [1] assert_raises(ValueError, stats.ppcc_max, data, dist="plate_of_shrimp") def test_ppcc_max_basic(self): np.random.seed(1234567) x = stats.tukeylambda.rvs(-0.7, loc=2, scale=0.5, size=10000) + 1e4 # On Python 2.6 the result is accurate to 5 decimals. On Python >= 2.7 # it is accurate up to 16 decimals assert_almost_equal(stats.ppcc_max(x), -0.71215366521264145, decimal=5) def test_dist(self): np.random.seed(1234567) x = stats.tukeylambda.rvs(-0.7, loc=2, scale=0.5, size=10000) + 1e4 # Test that we can specify distributions both by name and as objects. max1 = stats.ppcc_max(x, dist='tukeylambda') max2 = stats.ppcc_max(x, dist=stats.tukeylambda) assert_almost_equal(max1, -0.71215366521264145, decimal=5) assert_almost_equal(max2, -0.71215366521264145, decimal=5) # Test that 'tukeylambda' is the default dist max3 = stats.ppcc_max(x) assert_almost_equal(max3, -0.71215366521264145, decimal=5) def test_brack(self): np.random.seed(1234567) x = stats.tukeylambda.rvs(-0.7, loc=2, scale=0.5, size=10000) + 1e4 assert_raises(ValueError, stats.ppcc_max, x, brack=(0.0, 1.0, 0.5)) # On Python 2.6 the result is accurate to 5 decimals. On Python >= 2.7 # it is accurate up to 16 decimals assert_almost_equal(stats.ppcc_max(x, brack=(0, 1)), -0.71215366521264145, decimal=5) # On Python 2.6 the result is accurate to 5 decimals. On Python >= 2.7 # it is accurate up to 16 decimals assert_almost_equal(stats.ppcc_max(x, brack=(-2, 2)), -0.71215366521264145, decimal=5) class TestBoxcox_llf(TestCase): def test_basic(self): np.random.seed(54321) x = stats.norm.rvs(size=10000, loc=10) lmbda = 1 llf = stats.boxcox_llf(lmbda, x) llf_expected = -x.size / 2. * np.log(np.sum(x.std()**2)) assert_allclose(llf, llf_expected) def test_array_like(self): np.random.seed(54321) x = stats.norm.rvs(size=100, loc=10) lmbda = 1 llf = stats.boxcox_llf(lmbda, x) llf2 = stats.boxcox_llf(lmbda, list(x)) assert_allclose(llf, llf2, rtol=1e-12) def test_2d_input(self): # Note: boxcox_llf() was already working with 2-D input (sort of), so # keep it like that. boxcox() doesn't work with 2-D input though, due # to brent() returning a scalar. np.random.seed(54321) x = stats.norm.rvs(size=100, loc=10) lmbda = 1 llf = stats.boxcox_llf(lmbda, x) llf2 = stats.boxcox_llf(lmbda, np.vstack([x, x]).T) assert_allclose([llf, llf], llf2, rtol=1e-12) def test_empty(self): assert_(np.isnan(stats.boxcox_llf(1, []))) class TestBoxcox(TestCase): def test_fixed_lmbda(self): np.random.seed(12345) x = stats.loggamma.rvs(5, size=50) + 5 xt = stats.boxcox(x, lmbda=1) assert_allclose(xt, x - 1) xt = stats.boxcox(x, lmbda=-1) assert_allclose(xt, 1 - 1/x) xt = stats.boxcox(x, lmbda=0) assert_allclose(xt, np.log(x)) # Also test that array_like input works xt = stats.boxcox(list(x), lmbda=0) assert_allclose(xt, np.log(x)) def test_lmbda_None(self): np.random.seed(1234567) # Start from normal rv's, do inverse transform to check that # optimization function gets close to the right answer. np.random.seed(1245) lmbda = 2.5 x = stats.norm.rvs(loc=10, size=50000) x_inv = (x * lmbda + 1)**(-lmbda) xt, maxlog = stats.boxcox(x_inv) assert_almost_equal(maxlog, -1 / lmbda, decimal=2) def test_alpha(self): np.random.seed(1234) x = stats.loggamma.rvs(5, size=50) + 5 # Some regular values for alpha, on a small sample size _, _, interval = stats.boxcox(x, alpha=0.75) assert_allclose(interval, [4.004485780226041, 5.138756355035744]) _, _, interval = stats.boxcox(x, alpha=0.05) assert_allclose(interval, [1.2138178554857557, 8.209033272375663]) # Try some extreme values, see we don't hit the N=500 limit x = stats.loggamma.rvs(7, size=500) + 15 _, _, interval = stats.boxcox(x, alpha=0.001) assert_allclose(interval, [0.3988867, 11.40553131]) _, _, interval = stats.boxcox(x, alpha=0.999) assert_allclose(interval, [5.83316246, 5.83735292]) def test_boxcox_bad_arg(self): # Raise ValueError if any data value is negative. x = np.array([-1]) assert_raises(ValueError, stats.boxcox, x) def test_empty(self): assert_(stats.boxcox([]).shape == (0,)) class TestBoxcoxNormmax(TestCase): def setUp(self): np.random.seed(12345) self.x = stats.loggamma.rvs(5, size=50) + 5 def test_pearsonr(self): maxlog = stats.boxcox_normmax(self.x) assert_allclose(maxlog, 1.804465, rtol=1e-6) def test_mle(self): maxlog = stats.boxcox_normmax(self.x, method='mle') assert_allclose(maxlog, 1.758101, rtol=1e-6) # Check that boxcox() uses 'mle' _, maxlog_boxcox = stats.boxcox(self.x) assert_allclose(maxlog_boxcox, maxlog) def test_all(self): maxlog_all = stats.boxcox_normmax(self.x, method='all') assert_allclose(maxlog_all, [1.804465, 1.758101], rtol=1e-6) class TestBoxcoxNormplot(TestCase): def setUp(self): np.random.seed(7654321) self.x = stats.loggamma.rvs(5, size=500) + 5 def test_basic(self): N = 5 lmbdas, ppcc = stats.boxcox_normplot(self.x, -10, 10, N=N) ppcc_expected = [0.57783375, 0.83610988, 0.97524311, 0.99756057, 0.95843297] assert_allclose(lmbdas, np.linspace(-10, 10, num=N)) assert_allclose(ppcc, ppcc_expected) @dec.skipif(not have_matplotlib) def test_plot_kwarg(self): # Check with the matplotlib.pyplot module fig = plt.figure() fig.add_subplot(111) stats.boxcox_normplot(self.x, -20, 20, plot=plt) plt.close() # Check that a Matplotlib Axes object is accepted fig.add_subplot(111) ax = fig.add_subplot(111) stats.boxcox_normplot(self.x, -20, 20, plot=ax) plt.close() def test_invalid_inputs(self): # `lb` has to be larger than `la` assert_raises(ValueError, stats.boxcox_normplot, self.x, 1, 0) # `x` can not contain negative values assert_raises(ValueError, stats.boxcox_normplot, [-1, 1], 0, 1) def test_empty(self): assert_(stats.boxcox_normplot([], 0, 1).size == 0) class TestCircFuncs(TestCase): def test_circfuncs(self): x = np.array([355,5,2,359,10,350]) M = stats.circmean(x, high=360) Mval = 0.167690146 assert_allclose(M, Mval, rtol=1e-7) V = stats.circvar(x, high=360) Vval = 42.51955609 assert_allclose(V, Vval, rtol=1e-7) S = stats.circstd(x, high=360) Sval = 6.520702116 assert_allclose(S, Sval, rtol=1e-7) def test_circfuncs_small(self): x = np.array([20,21,22,18,19,20.5,19.2]) M1 = x.mean() M2 = stats.circmean(x, high=360) assert_allclose(M2, M1, rtol=1e-5) V1 = x.var() V2 = stats.circvar(x, high=360) assert_allclose(V2, V1, rtol=1e-4) S1 = x.std() S2 = stats.circstd(x, high=360) assert_allclose(S2, S1, rtol=1e-4) def test_circmean_axis(self): x = np.array([[355,5,2,359,10,350], [351,7,4,352,9,349], [357,9,8,358,4,356]]) M1 = stats.circmean(x, high=360) M2 = stats.circmean(x.ravel(), high=360) assert_allclose(M1, M2, rtol=1e-14) M1 = stats.circmean(x, high=360, axis=1) M2 = [stats.circmean(x[i], high=360) for i in range(x.shape[0])] assert_allclose(M1, M2, rtol=1e-14) M1 = stats.circmean(x, high=360, axis=0) M2 = [stats.circmean(x[:,i], high=360) for i in range(x.shape[1])] assert_allclose(M1, M2, rtol=1e-14) def test_circvar_axis(self): x = np.array([[355,5,2,359,10,350], [351,7,4,352,9,349], [357,9,8,358,4,356]]) V1 = stats.circvar(x, high=360) V2 = stats.circvar(x.ravel(), high=360) assert_allclose(V1, V2, rtol=1e-11) V1 = stats.circvar(x, high=360, axis=1) V2 = [stats.circvar(x[i], high=360) for i in range(x.shape[0])] assert_allclose(V1, V2, rtol=1e-11) V1 = stats.circvar(x, high=360, axis=0) V2 = [stats.circvar(x[:,i], high=360) for i in range(x.shape[1])] assert_allclose(V1, V2, rtol=1e-11) def test_circstd_axis(self): x = np.array([[355,5,2,359,10,350], [351,7,4,352,9,349], [357,9,8,358,4,356]]) S1 = stats.circstd(x, high=360) S2 = stats.circstd(x.ravel(), high=360) assert_allclose(S1, S2, rtol=1e-11) S1 = stats.circstd(x, high=360, axis=1) S2 = [stats.circstd(x[i], high=360) for i in range(x.shape[0])] assert_allclose(S1, S2, rtol=1e-11) S1 = stats.circstd(x, high=360, axis=0) S2 = [stats.circstd(x[:,i], high=360) for i in range(x.shape[1])] assert_allclose(S1, S2, rtol=1e-11) def test_circfuncs_array_like(self): x = [355,5,2,359,10,350] assert_allclose(stats.circmean(x, high=360), 0.167690146, rtol=1e-7) assert_allclose(stats.circvar(x, high=360), 42.51955609, rtol=1e-7) assert_allclose(stats.circstd(x, high=360), 6.520702116, rtol=1e-7) def test_empty(self): assert_(np.isnan(stats.circmean([]))) assert_(np.isnan(stats.circstd([]))) assert_(np.isnan(stats.circvar([]))) def test_accuracy_wilcoxon(): freq = [1, 4, 16, 15, 8, 4, 5, 1, 2] nums = range(-4, 5) x = np.concatenate([[u] * v for u, v in zip(nums, freq)]) y = np.zeros(x.size) T, p = stats.wilcoxon(x, y, "pratt") assert_allclose(T, 423) assert_allclose(p, 0.00197547303533107) T, p = stats.wilcoxon(x, y, "zsplit") assert_allclose(T, 441) assert_allclose(p, 0.0032145343172473055) T, p = stats.wilcoxon(x, y, "wilcox") assert_allclose(T, 327) assert_allclose(p, 0.00641346115861) # Test the 'correction' option, using values computed in R with: # > wilcox.test(x, y, paired=TRUE, exact=FALSE, correct={FALSE,TRUE}) x = np.array([120, 114, 181, 188, 180, 146, 121, 191, 132, 113, 127, 112]) y = np.array([133, 143, 119, 189, 112, 199, 198, 113, 115, 121, 142, 187]) T, p = stats.wilcoxon(x, y, correction=False) assert_equal(T, 34) assert_allclose(p, 0.6948866, rtol=1e-6) T, p = stats.wilcoxon(x, y, correction=True) assert_equal(T, 34) assert_allclose(p, 0.7240817, rtol=1e-6) def test_wilcoxon_result_attributes(): x = np.array([120, 114, 181, 188, 180, 146, 121, 191, 132, 113, 127, 112]) y = np.array([133, 143, 119, 189, 112, 199, 198, 113, 115, 121, 142, 187]) res = stats.wilcoxon(x, y, correction=False) attributes = ('statistic', 'pvalue') check_named_results(res, attributes) def test_wilcoxon_tie(): # Regression test for gh-2391. # Corresponding R code is: # > result = wilcox.test(rep(0.1, 10), exact=FALSE, correct=FALSE) # > result$p.value # [1] 0.001565402 # > result = wilcox.test(rep(0.1, 10), exact=FALSE, correct=TRUE) # > result$p.value # [1] 0.001904195 stat, p = stats.wilcoxon([0.1] * 10) expected_p = 0.001565402 assert_equal(stat, 0) assert_allclose(p, expected_p, rtol=1e-6) stat, p = stats.wilcoxon([0.1] * 10, correction=True) expected_p = 0.001904195 assert_equal(stat, 0) assert_allclose(p, expected_p, rtol=1e-6) class TestMedianTest(TestCase): def test_bad_n_samples(self): # median_test requires at least two samples. assert_raises(ValueError, stats.median_test, [1, 2, 3]) def test_empty_sample(self): # Each sample must contain at least one value. assert_raises(ValueError, stats.median_test, [], [1, 2, 3]) def test_empty_when_ties_ignored(self): # The grand median is 1, and all values in the first argument are # equal to the grand median. With ties="ignore", those values are # ignored, which results in the first sample being (in effect) empty. # This should raise a ValueError. assert_raises(ValueError, stats.median_test, [1, 1, 1, 1], [2, 0, 1], [2, 0], ties="ignore") def test_empty_contingency_row(self): # The grand median is 1, and with the default ties="below", all the # values in the samples are counted as being below the grand median. # This would result a row of zeros in the contingency table, which is # an error. assert_raises(ValueError, stats.median_test, [1, 1, 1], [1, 1, 1]) # With ties="above", all the values are counted as above the # grand median. assert_raises(ValueError, stats.median_test, [1, 1, 1], [1, 1, 1], ties="above") def test_bad_ties(self): assert_raises(ValueError, stats.median_test, [1, 2, 3], [4, 5], ties="foo") def test_bad_keyword(self): assert_raises(TypeError, stats.median_test, [1, 2, 3], [4, 5], foo="foo") def test_simple(self): x = [1, 2, 3] y = [1, 2, 3] stat, p, med, tbl = stats.median_test(x, y) # The median is floating point, but this equality test should be safe. assert_equal(med, 2.0) assert_array_equal(tbl, [[1, 1], [2, 2]]) # The expected values of the contingency table equal the contingency table, # so the statistic should be 0 and the p-value should be 1. assert_equal(stat, 0) assert_equal(p, 1) def test_ties_options(self): # Test the contingency table calculation. x = [1, 2, 3, 4] y = [5, 6] z = [7, 8, 9] # grand median is 5. # Default 'ties' option is "below". stat, p, m, tbl = stats.median_test(x, y, z) assert_equal(m, 5) assert_equal(tbl, [[0, 1, 3], [4, 1, 0]]) stat, p, m, tbl = stats.median_test(x, y, z, ties="ignore") assert_equal(m, 5) assert_equal(tbl, [[0, 1, 3], [4, 0, 0]]) stat, p, m, tbl = stats.median_test(x, y, z, ties="above") assert_equal(m, 5) assert_equal(tbl, [[0, 2, 3], [4, 0, 0]]) def test_basic(self): # median_test calls chi2_contingency to compute the test statistic # and p-value. Make sure it hasn't screwed up the call... x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8] stat, p, m, tbl = stats.median_test(x, y) assert_equal(m, 4) assert_equal(tbl, [[1, 2], [4, 2]]) exp_stat, exp_p, dof, e = stats.chi2_contingency(tbl) assert_allclose(stat, exp_stat) assert_allclose(p, exp_p) stat, p, m, tbl = stats.median_test(x, y, lambda_=0) assert_equal(m, 4) assert_equal(tbl, [[1, 2], [4, 2]]) exp_stat, exp_p, dof, e = stats.chi2_contingency(tbl, lambda_=0) assert_allclose(stat, exp_stat) assert_allclose(p, exp_p) stat, p, m, tbl = stats.median_test(x, y, correction=False) assert_equal(m, 4) assert_equal(tbl, [[1, 2], [4, 2]]) exp_stat, exp_p, dof, e = stats.chi2_contingency(tbl, correction=False) assert_allclose(stat, exp_stat) assert_allclose(p, exp_p) if __name__ == "__main__": run_module_suite()
mit
beiko-lab/gengis
bin/Lib/site-packages/matplotlib/backends/backend_gtk.py
4
45322
from __future__ import division, print_function import os, sys, warnings def fn_name(): return sys._getframe(1).f_code.co_name if sys.version_info[0] >= 3: warnings.warn( "The gtk* backends have not been tested with Python 3.x", ImportWarning) try: import gobject import gtk; gdk = gtk.gdk import pango except ImportError: raise ImportError("Gtk* backend requires pygtk to be installed.") pygtk_version_required = (2,4,0) if gtk.pygtk_version < pygtk_version_required: raise ImportError ("PyGTK %d.%d.%d is installed\n" "PyGTK %d.%d.%d or later is required" % (gtk.pygtk_version + pygtk_version_required)) del pygtk_version_required _new_tooltip_api = (gtk.pygtk_version[1] >= 12) import matplotlib from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import RendererBase, GraphicsContextBase, \ FigureManagerBase, FigureCanvasBase, NavigationToolbar2, cursors, TimerBase from matplotlib.backend_bases import ShowBase from matplotlib.backends.backend_gdk import RendererGDK, FigureCanvasGDK from matplotlib.cbook import is_string_like, is_writable_file_like from matplotlib.colors import colorConverter from matplotlib.figure import Figure from matplotlib.widgets import SubplotTool from matplotlib import lines from matplotlib import markers from matplotlib import cbook from matplotlib import verbose from matplotlib import rcParams backend_version = "%d.%d.%d" % gtk.pygtk_version _debug = False #_debug = True # the true dots per inch on the screen; should be display dependent # see http://groups.google.com/groups?q=screen+dpi+x11&hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&selm=7077.26e81ad5%40swift.cs.tcd.ie&rnum=5 for some info about screen dpi PIXELS_PER_INCH = 96 # Hide the benign warning that it can't stat a file that doesn't warnings.filterwarnings('ignore', '.*Unable to retrieve the file info for.*', gtk.Warning) cursord = { cursors.MOVE : gdk.Cursor(gdk.FLEUR), cursors.HAND : gdk.Cursor(gdk.HAND2), cursors.POINTER : gdk.Cursor(gdk.LEFT_PTR), cursors.SELECT_REGION : gdk.Cursor(gdk.TCROSS), } # ref gtk+/gtk/gtkwidget.h def GTK_WIDGET_DRAWABLE(w): flags = w.flags(); return flags & gtk.VISIBLE != 0 and flags & gtk.MAPPED != 0 def draw_if_interactive(): """ Is called after every pylab drawing command """ if matplotlib.is_interactive(): figManager = Gcf.get_active() if figManager is not None: figManager.canvas.draw_idle() class Show(ShowBase): def mainloop(self): if gtk.main_level() == 0: gtk.main() show = Show() def new_figure_manager(num, *args, **kwargs): """ Create a new figure manager instance """ FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass(*args, **kwargs) return new_figure_manager_given_figure(num, thisFig) def new_figure_manager_given_figure(num, figure): """ Create a new figure manager instance for the given figure. """ canvas = FigureCanvasGTK(figure) manager = FigureManagerGTK(canvas, num) return manager class TimerGTK(TimerBase): ''' Subclass of :class:`backend_bases.TimerBase` that uses GTK for timer events. Attributes: * interval: The time between timer events in milliseconds. Default is 1000 ms. * single_shot: Boolean flag indicating whether this timer should operate as single shot (run once and then stop). Defaults to False. * callbacks: Stores list of (func, args) tuples that will be called upon timer events. This list can be manipulated directly, or the functions add_callback and remove_callback can be used. ''' def _timer_start(self): # Need to stop it, otherwise we potentially leak a timer id that will # never be stopped. self._timer_stop() self._timer = gobject.timeout_add(self._interval, self._on_timer) def _timer_stop(self): if self._timer is not None: gobject.source_remove(self._timer) self._timer = None def _timer_set_interval(self): # Only stop and restart it if the timer has already been started if self._timer is not None: self._timer_stop() self._timer_start() def _on_timer(self): TimerBase._on_timer(self) # Gtk timeout_add() requires that the callback returns True if it # is to be called again. if len(self.callbacks) > 0 and not self._single: return True else: self._timer = None return False class FigureCanvasGTK (gtk.DrawingArea, FigureCanvasBase): keyvald = {65507 : 'control', 65505 : 'shift', 65513 : 'alt', 65508 : 'control', 65506 : 'shift', 65514 : 'alt', 65361 : 'left', 65362 : 'up', 65363 : 'right', 65364 : 'down', 65307 : 'escape', 65470 : 'f1', 65471 : 'f2', 65472 : 'f3', 65473 : 'f4', 65474 : 'f5', 65475 : 'f6', 65476 : 'f7', 65477 : 'f8', 65478 : 'f9', 65479 : 'f10', 65480 : 'f11', 65481 : 'f12', 65300 : 'scroll_lock', 65299 : 'break', 65288 : 'backspace', 65293 : 'enter', 65379 : 'insert', 65535 : 'delete', 65360 : 'home', 65367 : 'end', 65365 : 'pageup', 65366 : 'pagedown', 65438 : '0', 65436 : '1', 65433 : '2', 65435 : '3', 65430 : '4', 65437 : '5', 65432 : '6', 65429 : '7', 65431 : '8', 65434 : '9', 65451 : '+', 65453 : '-', 65450 : '*', 65455 : '/', 65439 : 'dec', 65421 : 'enter', 65511 : 'super', 65512 : 'super', 65406 : 'alt', 65289 : 'tab', } # Setting this as a static constant prevents # this resulting expression from leaking event_mask = (gdk.BUTTON_PRESS_MASK | gdk.BUTTON_RELEASE_MASK | gdk.EXPOSURE_MASK | gdk.KEY_PRESS_MASK | gdk.KEY_RELEASE_MASK | gdk.ENTER_NOTIFY_MASK | gdk.LEAVE_NOTIFY_MASK | gdk.POINTER_MOTION_MASK | gdk.POINTER_MOTION_HINT_MASK) def __init__(self, figure): if _debug: print('FigureCanvasGTK.%s' % fn_name()) FigureCanvasBase.__init__(self, figure) gtk.DrawingArea.__init__(self) self._idle_draw_id = 0 self._need_redraw = True self._pixmap_width = -1 self._pixmap_height = -1 self._lastCursor = None self.connect('scroll_event', self.scroll_event) self.connect('button_press_event', self.button_press_event) self.connect('button_release_event', self.button_release_event) self.connect('configure_event', self.configure_event) self.connect('expose_event', self.expose_event) self.connect('key_press_event', self.key_press_event) self.connect('key_release_event', self.key_release_event) self.connect('motion_notify_event', self.motion_notify_event) self.connect('leave_notify_event', self.leave_notify_event) self.connect('enter_notify_event', self.enter_notify_event) self.set_events(self.__class__.event_mask) self.set_double_buffered(False) self.set_flags(gtk.CAN_FOCUS) self._renderer_init() self._idle_event_id = gobject.idle_add(self.idle_event) self.last_downclick = {} def destroy(self): #gtk.DrawingArea.destroy(self) self.close_event() gobject.source_remove(self._idle_event_id) if self._idle_draw_id != 0: gobject.source_remove(self._idle_draw_id) def scroll_event(self, widget, event): if _debug: print('FigureCanvasGTK.%s' % fn_name()) x = event.x # flipy so y=0 is bottom of canvas y = self.allocation.height - event.y if event.direction==gdk.SCROLL_UP: step = 1 else: step = -1 FigureCanvasBase.scroll_event(self, x, y, step, guiEvent=event) return False # finish event propagation? def button_press_event(self, widget, event): if _debug: print('FigureCanvasGTK.%s' % fn_name()) x = event.x # flipy so y=0 is bottom of canvas y = self.allocation.height - event.y dblclick = (event.type == gdk._2BUTTON_PRESS) if not dblclick: # GTK is the only backend that generates a DOWN-UP-DOWN-DBLCLICK-UP event # sequence for a double click. All other backends have a DOWN-UP-DBLCLICK-UP # sequence. In order to provide consistency to matplotlib users, we will # eat the extra DOWN event in the case that we detect it is part of a double # click. # first, get the double click time in milliseconds. current_time = event.get_time() last_time = self.last_downclick.get(event.button,0) dblclick_time = gtk.settings_get_for_screen(gdk.screen_get_default()).get_property('gtk-double-click-time') delta_time = current_time-last_time if delta_time < dblclick_time: del self.last_downclick[event.button] # we do not want to eat more than one event. return False # eat. self.last_downclick[event.button] = current_time FigureCanvasBase.button_press_event(self, x, y, event.button, dblclick=dblclick, guiEvent=event) return False # finish event propagation? def button_release_event(self, widget, event): if _debug: print('FigureCanvasGTK.%s' % fn_name()) x = event.x # flipy so y=0 is bottom of canvas y = self.allocation.height - event.y FigureCanvasBase.button_release_event(self, x, y, event.button, guiEvent=event) return False # finish event propagation? def key_press_event(self, widget, event): if _debug: print('FigureCanvasGTK.%s' % fn_name()) key = self._get_key(event) if _debug: print("hit", key) FigureCanvasBase.key_press_event(self, key, guiEvent=event) return False # finish event propagation? def key_release_event(self, widget, event): if _debug: print('FigureCanvasGTK.%s' % fn_name()) key = self._get_key(event) if _debug: print("release", key) FigureCanvasBase.key_release_event(self, key, guiEvent=event) return False # finish event propagation? def motion_notify_event(self, widget, event): if _debug: print('FigureCanvasGTK.%s' % fn_name()) if event.is_hint: x, y, state = event.window.get_pointer() else: x, y, state = event.x, event.y, event.state # flipy so y=0 is bottom of canvas y = self.allocation.height - y FigureCanvasBase.motion_notify_event(self, x, y, guiEvent=event) return False # finish event propagation? def leave_notify_event(self, widget, event): FigureCanvasBase.leave_notify_event(self, event) def enter_notify_event(self, widget, event): x, y, state = event.window.get_pointer() FigureCanvasBase.enter_notify_event(self, event, xy=(x, y)) def _get_key(self, event): if event.keyval in self.keyvald: key = self.keyvald[event.keyval] elif event.keyval < 256: key = chr(event.keyval) else: key = None for key_mask, prefix in ( [gdk.MOD4_MASK, 'super'], [gdk.MOD1_MASK, 'alt'], [gdk.CONTROL_MASK, 'ctrl'], ): if event.state & key_mask: key = '{0}+{1}'.format(prefix, key) return key def configure_event(self, widget, event): if _debug: print('FigureCanvasGTK.%s' % fn_name()) if widget.window is None: return w, h = event.width, event.height if w < 3 or h < 3: return # empty fig # resize the figure (in inches) dpi = self.figure.dpi self.figure.set_size_inches (w/dpi, h/dpi) self._need_redraw = True return False # finish event propagation? def draw(self): # Note: FigureCanvasBase.draw() is inconveniently named as it clashes # with the deprecated gtk.Widget.draw() self._need_redraw = True if GTK_WIDGET_DRAWABLE(self): self.queue_draw() # do a synchronous draw (its less efficient than an async draw, # but is required if/when animation is used) self.window.process_updates (False) def draw_idle(self): def idle_draw(*args): self.draw() self._idle_draw_id = 0 return False if self._idle_draw_id == 0: self._idle_draw_id = gobject.idle_add(idle_draw) def _renderer_init(self): """Override by GTK backends to select a different renderer Renderer should provide the methods: set_pixmap () set_width_height () that are used by _render_figure() / _pixmap_prepare() """ self._renderer = RendererGDK (self, self.figure.dpi) def _pixmap_prepare(self, width, height): """ Make sure _._pixmap is at least width, height, create new pixmap if necessary """ if _debug: print('FigureCanvasGTK.%s' % fn_name()) create_pixmap = False if width > self._pixmap_width: # increase the pixmap in 10%+ (rather than 1 pixel) steps self._pixmap_width = max (int (self._pixmap_width * 1.1), width) create_pixmap = True if height > self._pixmap_height: self._pixmap_height = max (int (self._pixmap_height * 1.1), height) create_pixmap = True if create_pixmap: self._pixmap = gdk.Pixmap (self.window, self._pixmap_width, self._pixmap_height) self._renderer.set_pixmap (self._pixmap) def _render_figure(self, pixmap, width, height): """used by GTK and GTKcairo. GTKAgg overrides """ self._renderer.set_width_height (width, height) self.figure.draw (self._renderer) def expose_event(self, widget, event): """Expose_event for all GTK backends. Should not be overridden. """ if _debug: print('FigureCanvasGTK.%s' % fn_name()) if GTK_WIDGET_DRAWABLE(self): if self._need_redraw: x, y, w, h = self.allocation self._pixmap_prepare (w, h) self._render_figure(self._pixmap, w, h) self._need_redraw = False x, y, w, h = event.area self.window.draw_drawable (self.style.fg_gc[self.state], self._pixmap, x, y, x, y, w, h) return False # finish event propagation? filetypes = FigureCanvasBase.filetypes.copy() filetypes['jpg'] = 'JPEG' filetypes['jpeg'] = 'JPEG' filetypes['png'] = 'Portable Network Graphics' def print_jpeg(self, filename, *args, **kwargs): return self._print_image(filename, 'jpeg') print_jpg = print_jpeg def print_png(self, filename, *args, **kwargs): return self._print_image(filename, 'png') def _print_image(self, filename, format, *args, **kwargs): if self.flags() & gtk.REALIZED == 0: # for self.window(for pixmap) and has a side effect of altering # figure width,height (via configure-event?) gtk.DrawingArea.realize(self) width, height = self.get_width_height() pixmap = gdk.Pixmap (self.window, width, height) self._renderer.set_pixmap (pixmap) self._render_figure(pixmap, width, height) # jpg colors don't match the display very well, png colors match # better pixbuf = gdk.Pixbuf(gdk.COLORSPACE_RGB, 0, 8, width, height) pixbuf.get_from_drawable(pixmap, pixmap.get_colormap(), 0, 0, 0, 0, width, height) # set the default quality, if we are writing a JPEG. # http://www.pygtk.org/docs/pygtk/class-gdkpixbuf.html#method-gdkpixbuf--save options = cbook.restrict_dict(kwargs, ['quality']) if format in ['jpg','jpeg']: if 'quality' not in options: options['quality'] = rcParams['savefig.jpeg_quality'] options['quality'] = str(options['quality']) if is_string_like(filename): try: pixbuf.save(filename, format, options=options) except gobject.GError as exc: error_msg_gtk('Save figure failure:\n%s' % (exc,), parent=self) elif is_writable_file_like(filename): if hasattr(pixbuf, 'save_to_callback'): def save_callback(buf, data=None): data.write(buf) try: pixbuf.save_to_callback(save_callback, format, user_data=filename, options=options) except gobject.GError as exc: error_msg_gtk('Save figure failure:\n%s' % (exc,), parent=self) else: raise ValueError("Saving to a Python file-like object is only supported by PyGTK >= 2.8") else: raise ValueError("filename must be a path or a file-like object") def new_timer(self, *args, **kwargs): """ Creates a new backend-specific subclass of :class:`backend_bases.Timer`. This is useful for getting periodic events through the backend's native event loop. Implemented only for backends with GUIs. optional arguments: *interval* Timer interval in milliseconds *callbacks* Sequence of (func, args, kwargs) where func(*args, **kwargs) will be executed by the timer every *interval*. """ return TimerGTK(*args, **kwargs) def flush_events(self): gtk.gdk.threads_enter() while gtk.events_pending(): gtk.main_iteration(True) gtk.gdk.flush() gtk.gdk.threads_leave() def start_event_loop(self,timeout): FigureCanvasBase.start_event_loop_default(self,timeout) start_event_loop.__doc__=FigureCanvasBase.start_event_loop_default.__doc__ def stop_event_loop(self): FigureCanvasBase.stop_event_loop_default(self) stop_event_loop.__doc__=FigureCanvasBase.stop_event_loop_default.__doc__ class FigureManagerGTK(FigureManagerBase): """ Public attributes canvas : The FigureCanvas instance num : The Figure number toolbar : The gtk.Toolbar (gtk only) vbox : The gtk.VBox containing the canvas and toolbar (gtk only) window : The gtk.Window (gtk only) """ def __init__(self, canvas, num): if _debug: print('FigureManagerGTK.%s' % fn_name()) FigureManagerBase.__init__(self, canvas, num) self.window = gtk.Window() self.set_window_title("Figure %d" % num) if (window_icon): try: self.window.set_icon_from_file(window_icon) except: # some versions of gtk throw a glib.GError but not # all, so I am not sure how to catch it. I am unhappy # diong a blanket catch here, but an not sure what a # better way is - JDH verbose.report('Could not load matplotlib icon: %s' % sys.exc_info()[1]) self.vbox = gtk.VBox() self.window.add(self.vbox) self.vbox.show() self.canvas.show() self.vbox.pack_start(self.canvas, True, True) self.toolbar = self._get_toolbar(canvas) # calculate size for window w = int (self.canvas.figure.bbox.width) h = int (self.canvas.figure.bbox.height) if self.toolbar is not None: self.toolbar.show() self.vbox.pack_end(self.toolbar, False, False) tb_w, tb_h = self.toolbar.size_request() h += tb_h self.window.set_default_size (w, h) def destroy(*args): Gcf.destroy(num) self.window.connect("destroy", destroy) self.window.connect("delete_event", destroy) if matplotlib.is_interactive(): self.window.show() def notify_axes_change(fig): 'this will be called whenever the current axes is changed' if self.toolbar is not None: self.toolbar.update() self.canvas.figure.add_axobserver(notify_axes_change) self.canvas.grab_focus() def destroy(self, *args): if _debug: print('FigureManagerGTK.%s' % fn_name()) if hasattr(self, 'toolbar') and self.toolbar is not None: self.toolbar.destroy() if hasattr(self, 'vbox'): self.vbox.destroy() if hasattr(self, 'window'): self.window.destroy() if hasattr(self, 'canvas'): self.canvas.destroy() self.__dict__.clear() #Is this needed? Other backends don't have it. if Gcf.get_num_fig_managers()==0 and \ not matplotlib.is_interactive() and \ gtk.main_level() >= 1: gtk.main_quit() def show(self): # show the figure window self.window.show() def full_screen_toggle(self): self._full_screen_flag = not self._full_screen_flag if self._full_screen_flag: self.window.fullscreen() else: self.window.unfullscreen() _full_screen_flag = False def _get_toolbar(self, canvas): # must be inited after the window, drawingArea and figure # attrs are set if rcParams['toolbar'] == 'classic': toolbar = NavigationToolbar (canvas, self.window) elif rcParams['toolbar'] == 'toolbar2': toolbar = NavigationToolbar2GTK (canvas, self.window) else: toolbar = None return toolbar def get_window_title(self): return self.window.get_title() def set_window_title(self, title): self.window.set_title(title) def resize(self, width, height): 'set the canvas size in pixels' #_, _, cw, ch = self.canvas.allocation #_, _, ww, wh = self.window.allocation #self.window.resize (width-cw+ww, height-ch+wh) self.window.resize(width, height) class NavigationToolbar2GTK(NavigationToolbar2, gtk.Toolbar): def __init__(self, canvas, window): self.win = window gtk.Toolbar.__init__(self) NavigationToolbar2.__init__(self, canvas) def set_message(self, s): self.message.set_label(s) def set_cursor(self, cursor): self.canvas.window.set_cursor(cursord[cursor]) def release(self, event): try: del self._pixmapBack except AttributeError: pass def dynamic_update(self): # legacy method; new method is canvas.draw_idle self.canvas.draw_idle() def draw_rubberband(self, event, x0, y0, x1, y1): 'adapted from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/189744' drawable = self.canvas.window if drawable is None: return gc = drawable.new_gc() height = self.canvas.figure.bbox.height y1 = height - y1 y0 = height - y0 w = abs(x1 - x0) h = abs(y1 - y0) rect = [int(val)for val in (min(x0,x1), min(y0, y1), w, h)] try: lastrect, pixmapBack = self._pixmapBack except AttributeError: #snap image back if event.inaxes is None: return ax = event.inaxes l,b,w,h = [int(val) for val in ax.bbox.bounds] b = int(height)-(b+h) axrect = l,b,w,h self._pixmapBack = axrect, gtk.gdk.Pixmap(drawable, w, h) self._pixmapBack[1].draw_drawable(gc, drawable, l, b, 0, 0, w, h) else: drawable.draw_drawable(gc, pixmapBack, 0, 0, *lastrect) drawable.draw_rectangle(gc, False, *rect) def _init_toolbar(self): self.set_style(gtk.TOOLBAR_ICONS) self._init_toolbar2_4() def _init_toolbar2_4(self): basedir = os.path.join(rcParams['datapath'],'images') if not _new_tooltip_api: self.tooltips = gtk.Tooltips() for text, tooltip_text, image_file, callback in self.toolitems: if text is None: self.insert( gtk.SeparatorToolItem(), -1 ) continue fname = os.path.join(basedir, image_file + '.png') image = gtk.Image() image.set_from_file(fname) tbutton = gtk.ToolButton(image, text) self.insert(tbutton, -1) tbutton.connect('clicked', getattr(self, callback)) if _new_tooltip_api: tbutton.set_tooltip_text(tooltip_text) else: tbutton.set_tooltip(self.tooltips, tooltip_text, 'Private') toolitem = gtk.SeparatorToolItem() self.insert(toolitem, -1) # set_draw() not making separator invisible, # bug #143692 fixed Jun 06 2004, will be in GTK+ 2.6 toolitem.set_draw(False) toolitem.set_expand(True) toolitem = gtk.ToolItem() self.insert(toolitem, -1) self.message = gtk.Label() toolitem.add(self.message) self.show_all() def get_filechooser(self): fc = FileChooserDialog( title='Save the figure', parent=self.win, path=os.path.expanduser(rcParams.get('savefig.directory', '')), filetypes=self.canvas.get_supported_filetypes(), default_filetype=self.canvas.get_default_filetype()) fc.set_current_name(self.canvas.get_default_filename()) return fc def save_figure(self, *args): chooser = self.get_filechooser() fname, format = chooser.get_filename_from_user() chooser.destroy() if fname: startpath = os.path.expanduser(rcParams.get('savefig.directory', '')) if startpath == '': # explicitly missing key or empty str signals to use cwd rcParams['savefig.directory'] = startpath else: # save dir for next time rcParams['savefig.directory'] = os.path.dirname(unicode(fname)) try: self.canvas.print_figure(fname, format=format) except Exception as e: error_msg_gtk(str(e), parent=self) def configure_subplots(self, button): toolfig = Figure(figsize=(6,3)) canvas = self._get_canvas(toolfig) toolfig.subplots_adjust(top=0.9) tool = SubplotTool(self.canvas.figure, toolfig) w = int (toolfig.bbox.width) h = int (toolfig.bbox.height) window = gtk.Window() if (window_icon): try: window.set_icon_from_file(window_icon) except: # we presumably already logged a message on the # failure of the main plot, don't keep reporting pass window.set_title("Subplot Configuration Tool") window.set_default_size(w, h) vbox = gtk.VBox() window.add(vbox) vbox.show() canvas.show() vbox.pack_start(canvas, True, True) window.show() def _get_canvas(self, fig): return FigureCanvasGTK(fig) class NavigationToolbar(gtk.Toolbar): """ Public attributes canvas - the FigureCanvas (gtk.DrawingArea) win - the gtk.Window """ # list of toolitems to add to the toolbar, format is: # text, tooltip_text, image, callback(str), callback_arg, scroll(bool) toolitems = ( ('Left', 'Pan left with click or wheel mouse (bidirectional)', gtk.STOCK_GO_BACK, 'panx', -1, True), ('Right', 'Pan right with click or wheel mouse (bidirectional)', gtk.STOCK_GO_FORWARD, 'panx', 1, True), ('Zoom In X', 'Zoom In X (shrink the x axis limits) with click or wheel' ' mouse (bidirectional)', gtk.STOCK_ZOOM_IN, 'zoomx', 1, True), ('Zoom Out X', 'Zoom Out X (expand the x axis limits) with click or wheel' ' mouse (bidirectional)', gtk.STOCK_ZOOM_OUT, 'zoomx', -1, True), (None, None, None, None, None, None,), ('Up', 'Pan up with click or wheel mouse (bidirectional)', gtk.STOCK_GO_UP, 'pany', 1, True), ('Down', 'Pan down with click or wheel mouse (bidirectional)', gtk.STOCK_GO_DOWN, 'pany', -1, True), ('Zoom In Y', 'Zoom in Y (shrink the y axis limits) with click or wheel' ' mouse (bidirectional)', gtk.STOCK_ZOOM_IN, 'zoomy', 1, True), ('Zoom Out Y', 'Zoom Out Y (expand the y axis limits) with click or wheel' ' mouse (bidirectional)', gtk.STOCK_ZOOM_OUT, 'zoomy', -1, True), (None, None, None, None, None, None,), ('Save', 'Save the figure', gtk.STOCK_SAVE, 'save_figure', None, False), ) def __init__(self, canvas, window): """ figManager is the FigureManagerGTK instance that contains the toolbar, with attributes figure, window and drawingArea """ gtk.Toolbar.__init__(self) self.canvas = canvas # Note: gtk.Toolbar already has a 'window' attribute self.win = window self.set_style(gtk.TOOLBAR_ICONS) self._create_toolitems_2_4() self.update = self._update_2_4 self.fileselect = FileChooserDialog( title='Save the figure', parent=self.win, filetypes=self.canvas.get_supported_filetypes(), default_filetype=self.canvas.get_default_filetype()) self.show_all() self.update() def _create_toolitems_2_4(self): # use the GTK+ 2.4 GtkToolbar API iconSize = gtk.ICON_SIZE_SMALL_TOOLBAR if not _new_tooltip_api: self.tooltips = gtk.Tooltips() for text, tooltip_text, image_num, callback, callback_arg, scroll \ in self.toolitems: if text is None: self.insert( gtk.SeparatorToolItem(), -1 ) continue image = gtk.Image() image.set_from_stock(image_num, iconSize) tbutton = gtk.ToolButton(image, text) self.insert(tbutton, -1) if callback_arg: tbutton.connect('clicked', getattr(self, callback), callback_arg) else: tbutton.connect('clicked', getattr(self, callback)) if scroll: tbutton.connect('scroll_event', getattr(self, callback)) if _new_tooltip_api: tbutton.set_tooltip_text(tooltip_text) else: tbutton.set_tooltip(self.tooltips, tooltip_text, 'Private') # Axes toolitem, is empty at start, update() adds a menu if >=2 axes self.axes_toolitem = gtk.ToolItem() self.insert(self.axes_toolitem, 0) if _new_tooltip_api: self.axes_toolitem.set_tooltip_text( 'Select axes that controls affect') else: self.axes_toolitem.set_tooltip ( self.tooltips, tip_text='Select axes that controls affect', tip_private = 'Private') align = gtk.Alignment (xalign=0.5, yalign=0.5, xscale=0.0, yscale=0.0) self.axes_toolitem.add(align) self.menubutton = gtk.Button ("Axes") align.add (self.menubutton) def position_menu (menu): """Function for positioning a popup menu. Place menu below the menu button, but ensure it does not go off the bottom of the screen. The default is to popup menu at current mouse position """ x0, y0 = self.window.get_origin() x1, y1, m = self.window.get_pointer() x2, y2 = self.menubutton.get_pointer() sc_h = self.get_screen().get_height() # requires GTK+ 2.2 + w, h = menu.size_request() x = x0 + x1 - x2 y = y0 + y1 - y2 + self.menubutton.allocation.height y = min(y, sc_h - h) return x, y, True def button_clicked (button, data=None): self.axismenu.popup (None, None, position_menu, 0, gtk.get_current_event_time()) self.menubutton.connect ("clicked", button_clicked) def _update_2_4(self): # for GTK+ 2.4+ # called by __init__() and FigureManagerGTK self._axes = self.canvas.figure.axes if len(self._axes) >= 2: self.axismenu = self._make_axis_menu() self.menubutton.show_all() else: self.menubutton.hide() self.set_active(range(len(self._axes))) def _make_axis_menu(self): # called by self._update*() def toggled(item, data=None): if item == self.itemAll: for item in items: item.set_active(True) elif item == self.itemInvert: for item in items: item.set_active(not item.get_active()) ind = [i for i,item in enumerate(items) if item.get_active()] self.set_active(ind) menu = gtk.Menu() self.itemAll = gtk.MenuItem("All") menu.append(self.itemAll) self.itemAll.connect("activate", toggled) self.itemInvert = gtk.MenuItem("Invert") menu.append(self.itemInvert) self.itemInvert.connect("activate", toggled) items = [] for i in range(len(self._axes)): item = gtk.CheckMenuItem("Axis %d" % (i+1)) menu.append(item) item.connect("toggled", toggled) item.set_active(True) items.append(item) menu.show_all() return menu def set_active(self, ind): self._ind = ind self._active = [ self._axes[i] for i in self._ind ] def panx(self, button, direction): 'panx in direction' for a in self._active: a.xaxis.pan(direction) self.canvas.draw() return True def pany(self, button, direction): 'pany in direction' for a in self._active: a.yaxis.pan(direction) self.canvas.draw() return True def zoomx(self, button, direction): 'zoomx in direction' for a in self._active: a.xaxis.zoom(direction) self.canvas.draw() return True def zoomy(self, button, direction): 'zoomy in direction' for a in self._active: a.yaxis.zoom(direction) self.canvas.draw() return True def get_filechooser(self): return FileChooserDialog( title='Save the figure', parent=self.win, filetypes=self.canvas.get_supported_filetypes(), default_filetype=self.canvas.get_default_filetype()) def save_figure(self, *args): fname, format = self.get_filechooser().get_filename_from_user() if fname: try: self.canvas.print_figure(fname, format=format) except Exception as e: error_msg_gtk(str(e), parent=self) class FileChooserDialog(gtk.FileChooserDialog): """GTK+ 2.4 file selector which presents the user with a menu of supported image formats """ def __init__ (self, title = 'Save file', parent = None, action = gtk.FILE_CHOOSER_ACTION_SAVE, buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK), path = None, filetypes = [], default_filetype = None ): super(FileChooserDialog, self).__init__ (title, parent, action, buttons) super(FileChooserDialog, self).set_do_overwrite_confirmation(True) self.set_default_response (gtk.RESPONSE_OK) if not path: path = os.getcwd() + os.sep # create an extra widget to list supported image formats self.set_current_folder (path) self.set_current_name ('image.' + default_filetype) hbox = gtk.HBox (spacing=10) hbox.pack_start (gtk.Label ("File Format:"), expand=False) liststore = gtk.ListStore(gobject.TYPE_STRING) cbox = gtk.ComboBox(liststore) cell = gtk.CellRendererText() cbox.pack_start(cell, True) cbox.add_attribute(cell, 'text', 0) hbox.pack_start (cbox) self.filetypes = filetypes self.sorted_filetypes = filetypes.items() self.sorted_filetypes.sort() default = 0 for i, (ext, name) in enumerate(self.sorted_filetypes): cbox.append_text ("%s (*.%s)" % (name, ext)) if ext == default_filetype: default = i cbox.set_active(default) self.ext = default_filetype def cb_cbox_changed (cbox, data=None): """File extension changed""" head, filename = os.path.split(self.get_filename()) root, ext = os.path.splitext(filename) ext = ext[1:] new_ext = self.sorted_filetypes[cbox.get_active()][0] self.ext = new_ext if ext in self.filetypes: filename = root + '.' + new_ext elif ext == '': filename = filename.rstrip('.') + '.' + new_ext self.set_current_name (filename) cbox.connect ("changed", cb_cbox_changed) hbox.show_all() self.set_extra_widget(hbox) def get_filename_from_user (self): while True: filename = None if self.run() != int(gtk.RESPONSE_OK): break filename = self.get_filename() break return filename, self.ext class DialogLineprops: """ A GUI dialog for controlling lineprops """ signals = ( 'on_combobox_lineprops_changed', 'on_combobox_linestyle_changed', 'on_combobox_marker_changed', 'on_colorbutton_linestyle_color_set', 'on_colorbutton_markerface_color_set', 'on_dialog_lineprops_okbutton_clicked', 'on_dialog_lineprops_cancelbutton_clicked', ) linestyles = [ls for ls in lines.Line2D.lineStyles if ls.strip()] linestyled = dict([ (s,i) for i,s in enumerate(linestyles)]) markers = [m for m in markers.MarkerStyle.markers if cbook.is_string_like(m)] markerd = dict([(s,i) for i,s in enumerate(markers)]) def __init__(self, lines): import gtk.glade datadir = matplotlib.get_data_path() gladefile = os.path.join(datadir, 'lineprops.glade') if not os.path.exists(gladefile): raise IOError('Could not find gladefile lineprops.glade in %s'%datadir) self._inited = False self._updateson = True # suppress updates when setting widgets manually self.wtree = gtk.glade.XML(gladefile, 'dialog_lineprops') self.wtree.signal_autoconnect(dict([(s, getattr(self, s)) for s in self.signals])) self.dlg = self.wtree.get_widget('dialog_lineprops') self.lines = lines cbox = self.wtree.get_widget('combobox_lineprops') cbox.set_active(0) self.cbox_lineprops = cbox cbox = self.wtree.get_widget('combobox_linestyles') for ls in self.linestyles: cbox.append_text(ls) cbox.set_active(0) self.cbox_linestyles = cbox cbox = self.wtree.get_widget('combobox_markers') for m in self.markers: cbox.append_text(m) cbox.set_active(0) self.cbox_markers = cbox self._lastcnt = 0 self._inited = True def show(self): 'populate the combo box' self._updateson = False # flush the old cbox = self.cbox_lineprops for i in range(self._lastcnt-1,-1,-1): cbox.remove_text(i) # add the new for line in self.lines: cbox.append_text(line.get_label()) cbox.set_active(0) self._updateson = True self._lastcnt = len(self.lines) self.dlg.show() def get_active_line(self): 'get the active line' ind = self.cbox_lineprops.get_active() line = self.lines[ind] return line def get_active_linestyle(self): 'get the active lineinestyle' ind = self.cbox_linestyles.get_active() ls = self.linestyles[ind] return ls def get_active_marker(self): 'get the active lineinestyle' ind = self.cbox_markers.get_active() m = self.markers[ind] return m def _update(self): 'update the active line props from the widgets' if not self._inited or not self._updateson: return line = self.get_active_line() ls = self.get_active_linestyle() marker = self.get_active_marker() line.set_linestyle(ls) line.set_marker(marker) button = self.wtree.get_widget('colorbutton_linestyle') color = button.get_color() r, g, b = [val/65535. for val in (color.red, color.green, color.blue)] line.set_color((r,g,b)) button = self.wtree.get_widget('colorbutton_markerface') color = button.get_color() r, g, b = [val/65535. for val in (color.red, color.green, color.blue)] line.set_markerfacecolor((r,g,b)) line.figure.canvas.draw() def on_combobox_lineprops_changed(self, item): 'update the widgets from the active line' if not self._inited: return self._updateson = False line = self.get_active_line() ls = line.get_linestyle() if ls is None: ls = 'None' self.cbox_linestyles.set_active(self.linestyled[ls]) marker = line.get_marker() if marker is None: marker = 'None' self.cbox_markers.set_active(self.markerd[marker]) r,g,b = colorConverter.to_rgb(line.get_color()) color = gtk.gdk.Color(*[int(val*65535) for val in (r,g,b)]) button = self.wtree.get_widget('colorbutton_linestyle') button.set_color(color) r,g,b = colorConverter.to_rgb(line.get_markerfacecolor()) color = gtk.gdk.Color(*[int(val*65535) for val in (r,g,b)]) button = self.wtree.get_widget('colorbutton_markerface') button.set_color(color) self._updateson = True def on_combobox_linestyle_changed(self, item): self._update() def on_combobox_marker_changed(self, item): self._update() def on_colorbutton_linestyle_color_set(self, button): self._update() def on_colorbutton_markerface_color_set(self, button): 'called colorbutton marker clicked' self._update() def on_dialog_lineprops_okbutton_clicked(self, button): self._update() self.dlg.hide() def on_dialog_lineprops_cancelbutton_clicked(self, button): self.dlg.hide() # set icon used when windows are minimized # Unfortunately, the SVG renderer (rsvg) leaks memory under earlier # versions of pygtk, so we have to use a PNG file instead. try: if gtk.pygtk_version < (2, 8, 0) or sys.platform == 'win32': icon_filename = 'matplotlib.png' else: icon_filename = 'matplotlib.svg' window_icon = os.path.join(rcParams['datapath'], 'images', icon_filename) except: window_icon = None verbose.report('Could not load matplotlib icon: %s' % sys.exc_info()[1]) def error_msg_gtk(msg, parent=None): if parent is not None: # find the toplevel gtk.Window parent = parent.get_toplevel() if parent.flags() & gtk.TOPLEVEL == 0: parent = None if not is_string_like(msg): msg = ','.join(map(str,msg)) dialog = gtk.MessageDialog( parent = parent, type = gtk.MESSAGE_ERROR, buttons = gtk.BUTTONS_OK, message_format = msg) dialog.run() dialog.destroy() FigureManager = FigureManagerGTK
gpl-3.0
chrsrds/scikit-learn
benchmarks/bench_20newsgroups.py
22
3387
from time import time import argparse import numpy as np from sklearn.dummy import DummyClassifier from sklearn.datasets import fetch_20newsgroups_vectorized from sklearn.metrics import accuracy_score from sklearn.utils.validation import check_array from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import ExtraTreesClassifier from sklearn.ensemble import AdaBoostClassifier from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import MultinomialNB ESTIMATORS = { "dummy": DummyClassifier(), "random_forest": RandomForestClassifier(max_features="sqrt", min_samples_split=10), "extra_trees": ExtraTreesClassifier(max_features="sqrt", min_samples_split=10), "logistic_regression": LogisticRegression(), "naive_bayes": MultinomialNB(), "adaboost": AdaBoostClassifier(n_estimators=10), } ############################################################################### # Data if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-e', '--estimators', nargs="+", required=True, choices=ESTIMATORS) args = vars(parser.parse_args()) data_train = fetch_20newsgroups_vectorized(subset="train") data_test = fetch_20newsgroups_vectorized(subset="test") X_train = check_array(data_train.data, dtype=np.float32, accept_sparse="csc") X_test = check_array(data_test.data, dtype=np.float32, accept_sparse="csr") y_train = data_train.target y_test = data_test.target print("20 newsgroups") print("=============") print("X_train.shape = {0}".format(X_train.shape)) print("X_train.format = {0}".format(X_train.format)) print("X_train.dtype = {0}".format(X_train.dtype)) print("X_train density = {0}" "".format(X_train.nnz / np.product(X_train.shape))) print("y_train {0}".format(y_train.shape)) print("X_test {0}".format(X_test.shape)) print("X_test.format = {0}".format(X_test.format)) print("X_test.dtype = {0}".format(X_test.dtype)) print("y_test {0}".format(y_test.shape)) print() print("Classifier Training") print("===================") accuracy, train_time, test_time = {}, {}, {} for name in sorted(args["estimators"]): clf = ESTIMATORS[name] try: clf.set_params(random_state=0) except (TypeError, ValueError): pass print("Training %s ... " % name, end="") t0 = time() clf.fit(X_train, y_train) train_time[name] = time() - t0 t0 = time() y_pred = clf.predict(X_test) test_time[name] = time() - t0 accuracy[name] = accuracy_score(y_test, y_pred) print("done") print() print("Classification performance:") print("===========================") print() print("%s %s %s %s" % ("Classifier ", "train-time", "test-time", "Accuracy")) print("-" * 44) for name in sorted(accuracy, key=accuracy.get): print("%s %s %s %s" % (name.ljust(16), ("%.4fs" % train_time[name]).center(10), ("%.4fs" % test_time[name]).center(10), ("%.4f" % accuracy[name]).center(10))) print()
bsd-3-clause
tdgoodrich/mase
python101/code/zipf.py
14
1453
"""This module contains code from Think Python by Allen B. Downey http://thinkpython.com Copyright 2012 Allen B. Downey License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html """ import sys import string import matplotlib.pyplot as pyplot from analyze_book import * def rank_freq(hist): """Returns a list of tuples where each tuple is a rank and the number of times the item with that rank appeared. """ # sort the list of frequencies in decreasing order freqs = hist.values() freqs.sort(reverse=True) # enumerate the ranks and frequencies rf = [(r+1, f) for r, f in enumerate(freqs)] return rf def print_ranks(hist): """Prints the rank vs. frequency data.""" for r, f in rank_freq(hist): print r, f def plot_ranks(hist, scale='log'): """Plots frequency vs. rank.""" t = rank_freq(hist) rs, fs = zip(*t) pyplot.clf() pyplot.xscale(scale) pyplot.yscale(scale) pyplot.title('Zipf plot') pyplot.xlabel('rank') pyplot.ylabel('frequency') pyplot.plot(rs, fs, 'r-') pyplot.show() def main(name, filename='emma.txt', flag='plot', *args): hist = process_file(filename, skip_header=True) # either print the results or plot them if flag == 'print': print_ranks(hist) elif flag == 'plot': plot_ranks(hist) else: print 'Usage: zipf.py filename [print|plot]' if __name__ == '__main__': main(*sys.argv)
unlicense
kris-singh/pgmpy
pgmpy/tests/test_models/test_BayesianModel.py
1
26569
import unittest import networkx as nx import pandas as pd import numpy as np import numpy.testing as np_test from pgmpy.models import BayesianModel, MarkovModel import pgmpy.tests.help_functions as hf from pgmpy.factors.discrete import TabularCPD, JointProbabilityDistribution, DiscreteFactor from pgmpy.independencies import Independencies from pgmpy.estimators import BayesianEstimator, BaseEstimator, MaximumLikelihoodEstimator class TestBaseModelCreation(unittest.TestCase): def setUp(self): self.G = BayesianModel() def test_class_init_without_data(self): self.assertIsInstance(self.G, nx.DiGraph) def test_class_init_with_data_string(self): self.g = BayesianModel([('a', 'b'), ('b', 'c')]) self.assertListEqual(sorted(self.g.nodes()), ['a', 'b', 'c']) self.assertListEqual(hf.recursive_sorted(self.g.edges()), [['a', 'b'], ['b', 'c']]) def test_class_init_with_data_nonstring(self): BayesianModel([(1, 2), (2, 3)]) def test_add_node_string(self): self.G.add_node('a') self.assertListEqual(self.G.nodes(), ['a']) def test_add_node_nonstring(self): self.G.add_node(1) def test_add_nodes_from_string(self): self.G.add_nodes_from(['a', 'b', 'c', 'd']) self.assertListEqual(sorted(self.G.nodes()), ['a', 'b', 'c', 'd']) def test_add_nodes_from_non_string(self): self.G.add_nodes_from([1, 2, 3, 4]) def test_add_edge_string(self): self.G.add_edge('d', 'e') self.assertListEqual(sorted(self.G.nodes()), ['d', 'e']) self.assertListEqual(self.G.edges(), [('d', 'e')]) self.G.add_nodes_from(['a', 'b', 'c']) self.G.add_edge('a', 'b') self.assertListEqual(hf.recursive_sorted(self.G.edges()), [['a', 'b'], ['d', 'e']]) def test_add_edge_nonstring(self): self.G.add_edge(1, 2) def test_add_edge_selfloop(self): self.assertRaises(ValueError, self.G.add_edge, 'a', 'a') def test_add_edge_result_cycle(self): self.G.add_edges_from([('a', 'b'), ('a', 'c')]) self.assertRaises(ValueError, self.G.add_edge, 'c', 'a') def test_add_edges_from_string(self): self.G.add_edges_from([('a', 'b'), ('b', 'c')]) self.assertListEqual(sorted(self.G.nodes()), ['a', 'b', 'c']) self.assertListEqual(hf.recursive_sorted(self.G.edges()), [['a', 'b'], ['b', 'c']]) self.G.add_nodes_from(['d', 'e', 'f']) self.G.add_edges_from([('d', 'e'), ('e', 'f')]) self.assertListEqual(sorted(self.G.nodes()), ['a', 'b', 'c', 'd', 'e', 'f']) self.assertListEqual(hf.recursive_sorted(self.G.edges()), hf.recursive_sorted([('a', 'b'), ('b', 'c'), ('d', 'e'), ('e', 'f')])) def test_add_edges_from_nonstring(self): self.G.add_edges_from([(1, 2), (2, 3)]) def test_add_edges_from_self_loop(self): self.assertRaises(ValueError, self.G.add_edges_from, [('a', 'a')]) def test_add_edges_from_result_cycle(self): self.assertRaises(ValueError, self.G.add_edges_from, [('a', 'b'), ('b', 'c'), ('c', 'a')]) def test_update_node_parents_bm_constructor(self): self.g = BayesianModel([('a', 'b'), ('b', 'c')]) self.assertListEqual(self.g.predecessors('a'), []) self.assertListEqual(self.g.predecessors('b'), ['a']) self.assertListEqual(self.g.predecessors('c'), ['b']) def test_update_node_parents(self): self.G.add_nodes_from(['a', 'b', 'c']) self.G.add_edges_from([('a', 'b'), ('b', 'c')]) self.assertListEqual(self.G.predecessors('a'), []) self.assertListEqual(self.G.predecessors('b'), ['a']) self.assertListEqual(self.G.predecessors('c'), ['b']) def tearDown(self): del self.G class TestBayesianModelMethods(unittest.TestCase): def setUp(self): self.G = BayesianModel([('a', 'd'), ('b', 'd'), ('d', 'e'), ('b', 'c')]) self.G1 = BayesianModel([('diff', 'grade'), ('intel', 'grade')]) diff_cpd = TabularCPD('diff', 2, values=[[0.2], [0.8]]) intel_cpd = TabularCPD('intel', 3, values=[[0.5], [0.3], [0.2]]) grade_cpd = TabularCPD('grade', 3, values=[[0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.8, 0.8, 0.8, 0.8, 0.8, 0.8]], evidence=['diff', 'intel'], evidence_card=[2, 3]) self.G1.add_cpds(diff_cpd, intel_cpd, grade_cpd) def test_moral_graph(self): moral_graph = self.G.moralize() self.assertListEqual(sorted(moral_graph.nodes()), ['a', 'b', 'c', 'd', 'e']) for edge in moral_graph.edges(): self.assertTrue(edge in [('a', 'b'), ('a', 'd'), ('b', 'c'), ('d', 'b'), ('e', 'd')] or (edge[1], edge[0]) in [('a', 'b'), ('a', 'd'), ('b', 'c'), ('d', 'b'), ('e', 'd')]) def test_moral_graph_with_edge_present_over_parents(self): G = BayesianModel([('a', 'd'), ('d', 'e'), ('b', 'd'), ('b', 'c'), ('a', 'b')]) moral_graph = G.moralize() self.assertListEqual(sorted(moral_graph.nodes()), ['a', 'b', 'c', 'd', 'e']) for edge in moral_graph.edges(): self.assertTrue(edge in [('a', 'b'), ('c', 'b'), ('d', 'a'), ('d', 'b'), ('d', 'e')] or (edge[1], edge[0]) in [('a', 'b'), ('c', 'b'), ('d', 'a'), ('d', 'b'), ('d', 'e')]) def test_local_independencies(self): self.assertEqual(self.G.local_independencies('a'), Independencies(['a', ['b', 'c']])) self.assertEqual(self.G.local_independencies('c'), Independencies(['c', ['a', 'd', 'e'], 'b'])) self.assertEqual(self.G.local_independencies('d'), Independencies(['d', 'c', ['b', 'a']])) self.assertEqual(self.G.local_independencies('e'), Independencies(['e', ['c', 'b', 'a'], 'd'])) self.assertEqual(self.G.local_independencies('b'), Independencies(['b', 'a'])) self.assertEqual(self.G1.local_independencies('grade'), Independencies()) def test_get_independencies(self): chain = BayesianModel([('X', 'Y'), ('Y', 'Z')]) self.assertEqual(chain.get_independencies(), Independencies(('X', 'Z', 'Y'), ('Z', 'X', 'Y'))) fork = BayesianModel([('Y', 'X'), ('Y', 'Z')]) self.assertEqual(fork.get_independencies(), Independencies(('X', 'Z', 'Y'), ('Z', 'X', 'Y'))) collider = BayesianModel([('X', 'Y'), ('Z', 'Y')]) self.assertEqual(collider.get_independencies(), Independencies(('X', 'Z'), ('Z', 'X'))) def test_is_imap(self): val = [0.01, 0.01, 0.08, 0.006, 0.006, 0.048, 0.004, 0.004, 0.032, 0.04, 0.04, 0.32, 0.024, 0.024, 0.192, 0.016, 0.016, 0.128] JPD = JointProbabilityDistribution(['diff', 'intel', 'grade'], [2, 3, 3], val) fac = DiscreteFactor(['diff', 'intel', 'grade'], [2, 3, 3], val) self.assertTrue(self.G1.is_imap(JPD)) self.assertRaises(TypeError, self.G1.is_imap, fac) def test_get_immoralities(self): G = BayesianModel([('x', 'y'), ('z', 'y'), ('x', 'z'), ('w', 'y')]) self.assertEqual(G.get_immoralities(), {('w', 'x'), ('w', 'z')}) G1 = BayesianModel([('x', 'y'), ('z', 'y'), ('z', 'x'), ('w', 'y')]) self.assertEqual(G1.get_immoralities(), {('w', 'x'), ('w', 'z')}) G2 = BayesianModel([('x', 'y'), ('z', 'y'), ('x', 'z'), ('w', 'y'), ('w', 'x')]) self.assertEqual(G2.get_immoralities(), {('w', 'z')}) def test_is_iequivalent(self): G = BayesianModel([('x', 'y'), ('z', 'y'), ('x', 'z'), ('w', 'y')]) self.assertRaises(TypeError, G.is_iequivalent, MarkovModel()) G1 = BayesianModel([('V', 'W'), ('W', 'X'), ('X', 'Y'), ('Z', 'Y')]) G2 = BayesianModel([('W', 'V'), ('X', 'W'), ('X', 'Y'), ('Z', 'Y')]) self.assertTrue(G1.is_iequivalent(G2)) G3 = BayesianModel([('W', 'V'), ('W', 'X'), ('Y', 'X'), ('Z', 'Y')]) self.assertFalse(G3.is_iequivalent(G2)) def test_copy(self): model_copy = self.G1.copy() self.assertEqual(sorted(self.G1.nodes()), sorted(model_copy.nodes())) self.assertEqual(sorted(self.G1.edges()), sorted(model_copy.edges())) self.assertNotEqual(id(self.G1.get_cpds('diff')), id(model_copy.get_cpds('diff'))) self.G1.remove_cpds('diff') diff_cpd = TabularCPD('diff', 2, values=[[0.3], [0.7]]) self.G1.add_cpds(diff_cpd) self.assertNotEqual(self.G1.get_cpds('diff'), model_copy.get_cpds('diff')) self.G1.remove_node('intel') self.assertNotEqual(sorted(self.G1.nodes()), sorted(model_copy.nodes())) self.assertNotEqual(sorted(self.G1.edges()), sorted(model_copy.edges())) def test_remove_node(self): self.G1.remove_node('diff') self.assertEqual(sorted(self.G1.nodes()), sorted(['grade', 'intel'])) self.assertRaises(ValueError, self.G1.get_cpds, 'diff') def test_remove_nodes_from(self): self.G1.remove_nodes_from(['diff', 'grade']) self.assertEqual(sorted(self.G1.nodes()), sorted(['intel'])) self.assertRaises(ValueError, self.G1.get_cpds, 'diff') self.assertRaises(ValueError, self.G1.get_cpds, 'grade') def tearDown(self): del self.G del self.G1 class TestBayesianModelCPD(unittest.TestCase): def setUp(self): self.G = BayesianModel([('d', 'g'), ('i', 'g'), ('g', 'l'), ('i', 's')]) def test_active_trail_nodes(self): self.assertEqual(sorted(self.G.active_trail_nodes('d')), ['d', 'g', 'l']) self.assertEqual(sorted(self.G.active_trail_nodes('i')), ['g', 'i', 'l', 's']) def test_active_trail_nodes_args(self): self.assertEqual(sorted(self.G.active_trail_nodes('d', observed='g')), ['d', 'i', 's']) self.assertEqual(sorted(self.G.active_trail_nodes('l', observed='g')), ['l']) self.assertEqual(sorted(self.G.active_trail_nodes('s', observed=['i', 'l'])), ['s']) self.assertEqual(sorted(self.G.active_trail_nodes('s', observed=['d', 'l'])), ['g', 'i', 's']) def test_is_active_trail_triplets(self): self.assertTrue(self.G.is_active_trail('d', 'l')) self.assertTrue(self.G.is_active_trail('g', 's')) self.assertFalse(self.G.is_active_trail('d', 'i')) self.assertTrue(self.G.is_active_trail('d', 'i', observed='g')) self.assertFalse(self.G.is_active_trail('d', 'l', observed='g')) self.assertFalse(self.G.is_active_trail('i', 'l', observed='g')) self.assertTrue(self.G.is_active_trail('d', 'i', observed='l')) self.assertFalse(self.G.is_active_trail('g', 's', observed='i')) def test_is_active_trail(self): self.assertFalse(self.G.is_active_trail('d', 's')) self.assertTrue(self.G.is_active_trail('s', 'l')) self.assertTrue(self.G.is_active_trail('d', 's', observed='g')) self.assertFalse(self.G.is_active_trail('s', 'l', observed='g')) def test_is_active_trail_args(self): self.assertFalse(self.G.is_active_trail('s', 'l', 'i')) self.assertFalse(self.G.is_active_trail('s', 'l', 'g')) self.assertTrue(self.G.is_active_trail('d', 's', 'l')) self.assertFalse(self.G.is_active_trail('d', 's', ['i', 'l'])) def test_get_cpds(self): cpd_d = TabularCPD('d', 2, values=np.random.rand(2, 1)) cpd_i = TabularCPD('i', 2, values=np.random.rand(2, 1)) cpd_g = TabularCPD('g', 2, values=np.random.rand(2, 4), evidence=['d', 'i'], evidence_card=[2, 2]) cpd_l = TabularCPD('l', 2, values=np.random.rand(2, 2), evidence=['g'], evidence_card=[2]) cpd_s = TabularCPD('s', 2, values=np.random.rand(2, 2), evidence=['i'], evidence_card=[2]) self.G.add_cpds(cpd_d, cpd_i, cpd_g, cpd_l, cpd_s) self.assertEqual(self.G.get_cpds('d').variable, 'd') def test_get_cpds1(self): self.model = BayesianModel([('A', 'AB')]) cpd_a = TabularCPD('A', 2, values=np.random.rand(2, 1)) cpd_ab = TabularCPD('AB', 2, values=np.random.rand(2, 2), evidence=['A'], evidence_card=[2]) self.model.add_cpds(cpd_a, cpd_ab) self.assertEqual(self.model.get_cpds('A').variable, 'A') self.assertEqual(self.model.get_cpds('AB').variable, 'AB') self.assertRaises(ValueError, self.model.get_cpds, 'B') self.model.add_node('B') self.assertRaises(ValueError, self.model.get_cpds, 'B') def test_add_single_cpd(self): cpd_s = TabularCPD('s', 2, np.random.rand(2, 2), ['i'], [2]) self.G.add_cpds(cpd_s) self.assertListEqual(self.G.get_cpds(), [cpd_s]) def test_add_multiple_cpds(self): cpd_d = TabularCPD('d', 2, values=np.random.rand(2, 1)) cpd_i = TabularCPD('i', 2, values=np.random.rand(2, 1)) cpd_g = TabularCPD('g', 2, values=np.random.rand(2, 4), evidence=['d', 'i'], evidence_card=[2, 2]) cpd_l = TabularCPD('l', 2, values=np.random.rand(2, 2), evidence=['g'], evidence_card=[2]) cpd_s = TabularCPD('s', 2, values=np.random.rand(2, 2), evidence=['i'], evidence_card=[2]) self.G.add_cpds(cpd_d, cpd_i, cpd_g, cpd_l, cpd_s) self.assertEqual(self.G.get_cpds('d'), cpd_d) self.assertEqual(self.G.get_cpds('i'), cpd_i) self.assertEqual(self.G.get_cpds('g'), cpd_g) self.assertEqual(self.G.get_cpds('l'), cpd_l) self.assertEqual(self.G.get_cpds('s'), cpd_s) def test_check_model(self): cpd_g = TabularCPD('g', 2, values=np.array([[0.2, 0.3, 0.4, 0.6], [0.8, 0.7, 0.6, 0.4]]), evidence=['d', 'i'], evidence_card=[2, 2]) cpd_s = TabularCPD('s', 2, values=np.array([[0.2, 0.3], [0.8, 0.7]]), evidence=['i'], evidence_card=[2]) cpd_l = TabularCPD('l', 2, values=np.array([[0.2, 0.3], [0.8, 0.7]]), evidence=['g'], evidence_card=[2]) self.G.add_cpds(cpd_g, cpd_s, cpd_l) self.assertRaises(ValueError, self.G.check_model) cpd_d = TabularCPD('d', 2, values=[[0.8, 0.2]]) cpd_i = TabularCPD('i', 2, values=[[0.7, 0.3]]) self.G.add_cpds(cpd_d, cpd_i) self.assertTrue(self.G.check_model()) def test_check_model1(self): cpd_g = TabularCPD('g', 2, values=np.array([[0.2, 0.3], [0.8, 0.7]]), evidence=['i'], evidence_card=[2]) self.G.add_cpds(cpd_g) self.assertRaises(ValueError, self.G.check_model) self.G.remove_cpds(cpd_g) cpd_g = TabularCPD('g', 2, values=np.array([[0.2, 0.3, 0.4, 0.6], [0.8, 0.7, 0.6, 0.4]]), evidence=['d', 's'], evidence_card=[2, 2]) self.G.add_cpds(cpd_g) self.assertRaises(ValueError, self.G.check_model) self.G.remove_cpds(cpd_g) cpd_g = TabularCPD('g', 2, values=np.array([[0.2, 0.3], [0.8, 0.7]]), evidence=['l'], evidence_card=[2]) self.G.add_cpds(cpd_g) self.assertRaises(ValueError, self.G.check_model) self.G.remove_cpds(cpd_g) cpd_l = TabularCPD('l', 2, values=np.array([[0.2, 0.3], [0.8, 0.7]]), evidence=['d'], evidence_card=[2]) self.G.add_cpds(cpd_l) self.assertRaises(ValueError, self.G.check_model) self.G.remove_cpds(cpd_l) cpd_l = TabularCPD('l', 2, values=np.array([[0.2, 0.3, 0.4, 0.6], [0.8, 0.7, 0.6, 0.4]]), evidence=['d', 'i'], evidence_card=[2, 2]) self.G.add_cpds(cpd_l) self.assertRaises(ValueError, self.G.check_model) self.G.remove_cpds(cpd_l) cpd_l = TabularCPD('l', 2, values=np.array([[0.2, 0.3, 0.4, 0.6, 0.2, 0.3, 0.4, 0.6], [0.8, 0.7, 0.6, 0.4, 0.8, 0.7, 0.6, 0.4]]), evidence=['g', 'd', 'i'], evidence_card=[2, 2, 2]) self.G.add_cpds(cpd_l) self.assertRaises(ValueError, self.G.check_model) self.G.remove_cpds(cpd_l) def test_check_model2(self): cpd_s = TabularCPD('s', 2, values=np.array([[0.5, 0.3], [0.8, 0.7]]), evidence=['i'], evidence_card=[2]) self.G.add_cpds(cpd_s) self.assertRaises(ValueError, self.G.check_model) self.G.remove_cpds(cpd_s) cpd_g = TabularCPD('g', 2, values=np.array([[0.2, 0.3, 0.4, 0.6], [0.3, 0.7, 0.6, 0.4]]), evidence=['d', 'i'], evidence_card=[2, 2]) self.G.add_cpds(cpd_g) self.assertRaises(ValueError, self.G.check_model) self.G.remove_cpds(cpd_g) cpd_l = TabularCPD('l', 2, values=np.array([[0.2, 0.3], [0.1, 0.7]]), evidence=['g'], evidence_card=[2]) self.G.add_cpds(cpd_l) self.assertRaises(ValueError, self.G.check_model) self.G.remove_cpds(cpd_l) def tearDown(self): del self.G class TestBayesianModelFitPredict(unittest.TestCase): def setUp(self): self.model_disconnected = BayesianModel() self.model_disconnected.add_nodes_from(['A', 'B', 'C', 'D', 'E']) self.model_connected = BayesianModel([('A', 'B'), ('C', 'B'), ('C', 'D'), ('B', 'E')]) self.model2 = BayesianModel([('A', 'C'), ('B', 'C')]) self.data1 = pd.DataFrame(data={'A': [0, 0, 1], 'B': [0, 1, 0], 'C': [1, 1, 0]}) self.data2 = pd.DataFrame(data={'A': [0, np.NaN, 1], 'B': [0, 1, 0], 'C': [1, 1, np.NaN], 'D': [np.NaN, 'Y', np.NaN]}) def test_bayesian_fit(self): print(isinstance(BayesianEstimator, BaseEstimator)) print(isinstance(MaximumLikelihoodEstimator, BaseEstimator)) self.model2.fit(self.data1, estimator_type=BayesianEstimator, prior_type="dirichlet", pseudo_counts=[9, 3]) self.assertEqual(self.model2.get_cpds('B'), TabularCPD('B', 2, [[11.0 / 15], [4.0 / 15]])) def test_fit_missing_data(self): self.model2.fit(self.data2, state_names={'C': [0, 1]}, complete_samples_only=False) cpds = set([TabularCPD('A', 2, [[0.5], [0.5]]), TabularCPD('B', 2, [[2. / 3], [1. / 3]]), TabularCPD('C', 2, [[0, 0.5, 0.5, 0.5], [1, 0.5, 0.5, 0.5]], evidence=['A', 'B'], evidence_card=[2, 2])]) self.assertSetEqual(cpds, set(self.model2.get_cpds())) def test_disconnected_fit(self): values = pd.DataFrame(np.random.randint(low=0, high=2, size=(1000, 5)), columns=['A', 'B', 'C', 'D', 'E']) self.model_disconnected.fit(values) for node in ['A', 'B', 'C', 'D', 'E']: cpd = self.model_disconnected.get_cpds(node) self.assertEqual(cpd.variable, node) np_test.assert_array_equal(cpd.cardinality, np.array([2])) value = (values.ix[:, node].value_counts() / values.ix[:, node].value_counts().sum()) value = value.reindex(sorted(value.index)).values np_test.assert_array_equal(cpd.values, value) def test_connected_predict(self): np.random.seed(42) values = pd.DataFrame(np.random.randint(low=0, high=2, size=(1000, 5)), columns=['A', 'B', 'C', 'D', 'E']) fit_data = values[:800] predict_data = values[800:].copy() self.model_connected.fit(fit_data) self.assertRaises(ValueError, self.model_connected.predict, predict_data) predict_data.drop('E', axis=1, inplace=True) e_predict = self.model_connected.predict(predict_data) np_test.assert_array_equal(e_predict.values.ravel(), np.array([1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0])) def tearDown(self): del self.model_connected del self.model_disconnected class TestDirectedGraphCPDOperations(unittest.TestCase): def setUp(self): self.graph = BayesianModel() def test_add_single_cpd(self): cpd = TabularCPD('grade', 2, values=np.random.rand(2, 4), evidence=['diff', 'intel'], evidence_card=[2, 2]) self.graph.add_edges_from([('diff', 'grade'), ('intel', 'grade')]) self.graph.add_cpds(cpd) self.assertListEqual(self.graph.get_cpds(), [cpd]) def test_add_multiple_cpds(self): cpd1 = TabularCPD('diff', 2, values=np.random.rand(2, 1)) cpd2 = TabularCPD('intel', 2, values=np.random.rand(2, 1)) cpd3 = TabularCPD('grade', 2, values=np.random.rand(2, 4), evidence=['diff', 'intel'], evidence_card=[2, 2]) self.graph.add_edges_from([('diff', 'grade'), ('intel', 'grade')]) self.graph.add_cpds(cpd1, cpd2, cpd3) self.assertListEqual(self.graph.get_cpds(), [cpd1, cpd2, cpd3]) def test_remove_single_cpd(self): cpd1 = TabularCPD('diff', 2, values=np.random.rand(2, 1)) cpd2 = TabularCPD('intel', 2, values=np.random.rand(2, 1)) cpd3 = TabularCPD('grade', 2, values=np.random.rand(2, 4), evidence=['diff', 'intel'], evidence_card=[2, 2]) self.graph.add_edges_from([('diff', 'grade'), ('intel', 'grade')]) self.graph.add_cpds(cpd1, cpd2, cpd3) self.graph.remove_cpds(cpd1) self.assertListEqual(self.graph.get_cpds(), [cpd2, cpd3]) def test_remove_multiple_cpds(self): cpd1 = TabularCPD('diff', 2, values=np.random.rand(2, 1)) cpd2 = TabularCPD('intel', 2, values=np.random.rand(2, 1)) cpd3 = TabularCPD('grade', 2, values=np.random.rand(2, 4), evidence=['diff', 'intel'], evidence_card=[2, 2]) self.graph.add_edges_from([('diff', 'grade'), ('intel', 'grade')]) self.graph.add_cpds(cpd1, cpd2, cpd3) self.graph.remove_cpds(cpd1, cpd3) self.assertListEqual(self.graph.get_cpds(), [cpd2]) def test_remove_single_cpd_string(self): cpd1 = TabularCPD('diff', 2, values=np.random.rand(2, 1)) cpd2 = TabularCPD('intel', 2, values=np.random.rand(2, 1)) cpd3 = TabularCPD('grade', 2, values=np.random.rand(2, 4), evidence=['diff', 'intel'], evidence_card=[2, 2]) self.graph.add_edges_from([('diff', 'grade'), ('intel', 'grade')]) self.graph.add_cpds(cpd1, cpd2, cpd3) self.graph.remove_cpds('diff') self.assertListEqual(self.graph.get_cpds(), [cpd2, cpd3]) def test_remove_multiple_cpds_string(self): cpd1 = TabularCPD('diff', 2, values=np.random.rand(2, 1)) cpd2 = TabularCPD('intel', 2, values=np.random.rand(2, 1)) cpd3 = TabularCPD('grade', 2, values=np.random.rand(2, 4), evidence=['diff', 'intel'], evidence_card=[2, 2]) self.graph.add_edges_from([('diff', 'grade'), ('intel', 'grade')]) self.graph.add_cpds(cpd1, cpd2, cpd3) self.graph.remove_cpds('diff', 'grade') self.assertListEqual(self.graph.get_cpds(), [cpd2]) def test_get_cpd_for_node(self): cpd1 = TabularCPD('diff', 2, values=np.random.rand(2, 1)) cpd2 = TabularCPD('intel', 2, values=np.random.rand(2, 1)) cpd3 = TabularCPD('grade', 2, values=np.random.rand(2, 4), evidence=['diff', 'intel'], evidence_card=[2, 2]) self.graph.add_edges_from([('diff', 'grade'), ('intel', 'grade')]) self.graph.add_cpds(cpd1, cpd2, cpd3) self.assertEqual(self.graph.get_cpds('diff'), cpd1) self.assertEqual(self.graph.get_cpds('intel'), cpd2) self.assertEqual(self.graph.get_cpds('grade'), cpd3) def test_get_cpd_raises_error(self): cpd1 = TabularCPD('diff', 2, values=np.random.rand(2, 1)) cpd2 = TabularCPD('intel', 2, values=np.random.rand(2, 1)) cpd3 = TabularCPD('grade', 2, values=np.random.rand(2, 4), evidence=['diff', 'intel'], evidence_card=[2, 2]) self.graph.add_edges_from([('diff', 'grade'), ('intel', 'grade')]) self.graph.add_cpds(cpd1, cpd2, cpd3) self.assertRaises(ValueError, self.graph.get_cpds, 'sat') def tearDown(self): del self.graph
mit
ch3ll0v3k/scikit-learn
examples/gaussian_process/gp_diabetes_dataset.py
223
1976
#!/usr/bin/python # -*- coding: utf-8 -*- """ ======================================================================== Gaussian Processes regression: goodness-of-fit on the 'diabetes' dataset ======================================================================== In this example, we fit a Gaussian Process model onto the diabetes dataset. We determine the correlation parameters with maximum likelihood estimation (MLE). We use an anisotropic squared exponential correlation model with a constant regression model. We also use a nugget of 1e-2 to account for the (strong) noise in the targets. We compute a cross-validation estimate of the coefficient of determination (R2) without reperforming MLE, using the set of correlation parameters found on the whole dataset. """ print(__doc__) # Author: Vincent Dubourg <[email protected]> # Licence: BSD 3 clause from sklearn import datasets from sklearn.gaussian_process import GaussianProcess from sklearn.cross_validation import cross_val_score, KFold # Load the dataset from scikit's data sets diabetes = datasets.load_diabetes() X, y = diabetes.data, diabetes.target # Instanciate a GP model gp = GaussianProcess(regr='constant', corr='absolute_exponential', theta0=[1e-4] * 10, thetaL=[1e-12] * 10, thetaU=[1e-2] * 10, nugget=1e-2, optimizer='Welch') # Fit the GP model to the data performing maximum likelihood estimation gp.fit(X, y) # Deactivate maximum likelihood estimation for the cross-validation loop gp.theta0 = gp.theta_ # Given correlation parameter = MLE gp.thetaL, gp.thetaU = None, None # None bounds deactivate MLE # Perform a cross-validation estimate of the coefficient of determination using # the cross_validation module using all CPUs available on the machine K = 20 # folds R2 = cross_val_score(gp, X, y=y, cv=KFold(y.size, K), n_jobs=1).mean() print("The %d-Folds estimate of the coefficient of determination is R2 = %s" % (K, R2))
bsd-3-clause
butala/pyrsss
pyrsss/emtf/e2hdf.py
1
9945
import sys import logging from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter import numpy as NP import pandas as PD from calc_e import apply_transfer_function as tf_1D from calc_e_3d import apply_transfer_function as tf_3D from ..mag.iaga2hdf import read_hdf, write_hdf from ..usarray_emtf.index import get_index from usgs_regions import get_region logger = logging.getLogger('pyrsss.emtf.e2hdf') def find_1D(header): """ Find and return the key associated with the Fernberg physiographic region at the location of the magnetometer as given in *header*. """ lat = header['geodetic_latitude'] lon = header['geodetic_longitude'] region = get_region(lat, lon) if region: region = region.replace('-', '_') return region def find_3D(index, header, max_distance, quality=5): """ Return the list of USArray 3-D EMTF keys (for repository :class:`Index` *index*) that are less than *max_distance* (in km) from the magnetometer location specified in *header*. Only include *quality* or greater sites. """ lat = header['geodetic_latitude'] lon = header['geodetic_longitude'] return index.quality_subset(min_quality=quality).by_distance(lat, lon, max_distance) def apply_emtf(df_E, df_B, emtf_key, index, extrapolate0=True): """ Apply the EMTF associated with *emtf_key* to magnetometer data found in *df_B* and store result to *df_E*. Use USArray .xml repository information :class:`Index` to process the 3-D EMTFs. """ logger.info('applying transfer function {}'.format(emtf_key)) interval = NP.diff(df_B.index.values[:2])[0] / NP.timedelta64(1, 's') Bx = df_B.B_X.values By = df_B.B_Y.values if emtf_key.startswith('USArray'): xml_fname = index[emtf_key][1] Ex, Ey = tf_3D(Bx, By, interval, xml_fname, extrapolate0=extrapolate0) else: Ex, Ey = tf_1D(Bx, By, interval, emtf_key) df_E[emtf_key + '_X'] = Ex df_E[emtf_key + '_Y'] = Ey return df_E def e2hdf(hdf_fname, source_key='B', key='E', replace=False, include=[], exclude=[], _3D=None, _1D=False, quality=5, verbose=True): """ Add modeled E columns to the :class:`DataFrame` record stored at *hdf_fname*. The input to the process (processed magnetometer B_X and B_Y) are found at *source_key* and the output (E_X and E_Y for various models) is stored associated with *key*. If *replace*, replace the *key* data record otherwise add to the data record. The following control which EMTFs are applied: - *include*: list of keys to always include - *exclude*: list of keys to never include - *_3D*: tuple of two values: 1) the maximum range (in km) from the measurement site to include USArray EMTF and 2) the path containing the repository of USArray EMTF .xml files - *_1D*: if True, include E generated by the 1-D Fernberg model for the physiographic region enclosing the magnetometer measurement point - *quality*: exclude USArray 3-D EMTFs with flagged at a quality index less than the specified values (5 being the highest) If *verbose*, then report the set of applied EMTFs to the logging facilities. """ # setup target DataFrame df, header = read_hdf(hdf_fname, source_key) def empty_record(): return PD.DataFrame(index=df.index) if replace: logger.info('creating new E record') df_e = empty_record() else: try: df_e, _ = read_hdf(hdf_fname, key) logger.info('appending to existing E record') except KeyError: logger.info('creating new E record') df_e = empty_record() # determine which EMTFs to use emtf_set = set(include) - set(exclude) if _1D: emtf_1D = find_1D(header) if emtf_1D is not None: emtf_set.add(emtf_1D) if _3D is not None: d_km, repository_path = _3D index = get_index(repository_path) for emtf_3D in find_3D(index, header, d_km): emtf_set.add(emtf_3D) else: index = None # apply EMTFs if verbose: logger.info('Applying EMTFs: {}'.format(', '.join(sorted(emtf_set)))) for emtf_key in sorted(emtf_set): df_e = apply_emtf(df_e, df, emtf_key, index) # output DataFrame write_hdf(hdf_fname, df_e, key, header) return hdf_fname def e2hdf_3D(hdf_fname, keys_3D, repository_path, source_key='B', key='E', replace=False): """ Add modeled E columns to the :class:`DataFrame` record stored at *hdf_fname*. The input to the process (processed magnetometer B_X and B_Y) are found at *source_key* and the output (E_X and E_Y for various models) is stored associated with *key*. If *replace*, replace the *key* data record otherwise add to the data record. Apply the 3-D transfer functions identified by the list *keys_3D*. Search for EMTF data records at *repository_path*. """ # setup target DataFrame df, header = read_hdf(hdf_fname, source_key) def empty_record(): return PD.DataFrame(index=df.index) if replace: logger.info('creating new E record') df_e = empty_record() else: try: df_e, _ = read_hdf(hdf_fname, key) logger.info('appending to existing E record') except KeyError: logger.info('creating new E record') df_e = empty_record() # determine which EMTFs to use emtf_list = [] index = get_index(repository_path) for key_3D in keys_3D: candidates = [x for x in index if key_3D in x] if len(candidates) == 1: emtf_list.append(candidates[0]) elif len(candidates) == 0: raise KeyError('could not find {} in index.pkl at {}'.format(key_3D, repository_path)) else: raise KeyError('could not unambiguously resolve {} in index.pkl at {} ({} are all candidates)'.format(key_3D, repository_path, ', '.join(candidates))) # apply EMTFs logger.info('Applying EMTFs: {}'.format(', '.join(sorted(emtf_list)))) for emtf_key in emtf_list: df_e = apply_emtf(df_e, df, emtf_key, index) # output DataFrame write_hdf(hdf_fname, df_e, key, header) return hdf_fname def float_or_str(x): """ Return *x* converted to float or *x* if that fails. """ try: return float(x) except: return x def main(argv=None): if argv is None: argv = sys.argv parser = ArgumentParser('Added modeled E field records to HDF file containing processed B field data.', formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument('hdf_fnames', type=str, nargs='*', metavar='hdf_fname', help='HDF file record to process') parser.add_argument('--source-key', '-s', type=str, default='B', help='') parser.add_argument('--key', '-k', type=str, default='E', help='key to associate with the processed records') parser.add_argument('--replace', '-r', action='store_true', help='replace modeled E field record (otherwise, append to the existing record)') parser.add_argument('--include', '-i', nargs='+', type=str, default=[], help='EMTFs to include') parser.add_argument('--exclude', '-e', nargs='+', type=str, default=[], help='EMTFs to exclude') parser.add_argument('--1D', action='store_true', help='include Fernberg 1-D model result for the physiographic region at the measurement location (if interior to a physiographic region)') parser.add_argument('--3D', type=float_or_str, nargs=2, help='two arguments: 1) include USArray 3-D model results within the specified geodetic distance (in km) from the measurement location and 2) the path to the USArray EMTF .xml repository') parser.add_argument('--quality', '-q', choices=range(6), type=int, default=5, help='minimum acceptable quality USArray EMTF (i.e., 0 means use all and 5 means use only highest flagged transfer functions)') args = parser.parse_args(argv[1:]) for hdf_fname in args.hdf_fnames: e2hdf(hdf_fname, source_key=args.source_key, key=args.key, replace=args.replace, include=args.include, exclude=args.exclude, _3D=getattr(args, '3D'), _1D=getattr(args, '1D'), quality=args.quality) if __name__ == '__main__': logging.basicConfig(level=logging.INFO) sys.exit(main())
mit
chrsrds/scikit-learn
examples/ensemble/plot_random_forest_embedding.py
73
3659
""" ========================================================= Hashing feature transformation using Totally Random Trees ========================================================= RandomTreesEmbedding provides a way to map data to a very high-dimensional, sparse representation, which might be beneficial for classification. The mapping is completely unsupervised and very efficient. This example visualizes the partitions given by several trees and shows how the transformation can also be used for non-linear dimensionality reduction or non-linear classification. Points that are neighboring often share the same leaf of a tree and therefore share large parts of their hashed representation. This allows to separate two concentric circles simply based on the principal components of the transformed data with truncated SVD. In high-dimensional spaces, linear classifiers often achieve excellent accuracy. For sparse binary data, BernoulliNB is particularly well-suited. The bottom row compares the decision boundary obtained by BernoulliNB in the transformed space with an ExtraTreesClassifier forests learned on the original data. """ import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_circles from sklearn.ensemble import RandomTreesEmbedding, ExtraTreesClassifier from sklearn.decomposition import TruncatedSVD from sklearn.naive_bayes import BernoulliNB # make a synthetic dataset X, y = make_circles(factor=0.5, random_state=0, noise=0.05) # use RandomTreesEmbedding to transform data hasher = RandomTreesEmbedding(n_estimators=10, random_state=0, max_depth=3) X_transformed = hasher.fit_transform(X) # Visualize result after dimensionality reduction using truncated SVD svd = TruncatedSVD(n_components=2) X_reduced = svd.fit_transform(X_transformed) # Learn a Naive Bayes classifier on the transformed data nb = BernoulliNB() nb.fit(X_transformed, y) # Learn an ExtraTreesClassifier for comparison trees = ExtraTreesClassifier(max_depth=3, n_estimators=10, random_state=0) trees.fit(X, y) # scatter plot of original and reduced data fig = plt.figure(figsize=(9, 8)) ax = plt.subplot(221) ax.scatter(X[:, 0], X[:, 1], c=y, s=50, edgecolor='k') ax.set_title("Original Data (2d)") ax.set_xticks(()) ax.set_yticks(()) ax = plt.subplot(222) ax.scatter(X_reduced[:, 0], X_reduced[:, 1], c=y, s=50, edgecolor='k') ax.set_title("Truncated SVD reduction (2d) of transformed data (%dd)" % X_transformed.shape[1]) ax.set_xticks(()) ax.set_yticks(()) # Plot the decision in original space. For that, we will assign a color # to each point in the mesh [x_min, x_max]x[y_min, y_max]. h = .01 x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) # transform grid using RandomTreesEmbedding transformed_grid = hasher.transform(np.c_[xx.ravel(), yy.ravel()]) y_grid_pred = nb.predict_proba(transformed_grid)[:, 1] ax = plt.subplot(223) ax.set_title("Naive Bayes on Transformed data") ax.pcolormesh(xx, yy, y_grid_pred.reshape(xx.shape)) ax.scatter(X[:, 0], X[:, 1], c=y, s=50, edgecolor='k') ax.set_ylim(-1.4, 1.4) ax.set_xlim(-1.4, 1.4) ax.set_xticks(()) ax.set_yticks(()) # transform grid using ExtraTreesClassifier y_grid_pred = trees.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1] ax = plt.subplot(224) ax.set_title("ExtraTrees predictions") ax.pcolormesh(xx, yy, y_grid_pred.reshape(xx.shape)) ax.scatter(X[:, 0], X[:, 1], c=y, s=50, edgecolor='k') ax.set_ylim(-1.4, 1.4) ax.set_xlim(-1.4, 1.4) ax.set_xticks(()) ax.set_yticks(()) plt.tight_layout() plt.show()
bsd-3-clause
MohammedWasim/scikit-learn
sklearn/metrics/tests/test_score_objects.py
138
14048
import pickle import numpy as np from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_raises_regexp from sklearn.utils.testing import assert_true from sklearn.utils.testing import ignore_warnings from sklearn.utils.testing import assert_not_equal from sklearn.base import BaseEstimator from sklearn.metrics import (f1_score, r2_score, roc_auc_score, fbeta_score, log_loss, precision_score, recall_score) from sklearn.metrics.cluster import adjusted_rand_score from sklearn.metrics.scorer import (check_scoring, _PredictScorer, _passthrough_scorer) from sklearn.metrics import make_scorer, get_scorer, SCORERS from sklearn.svm import LinearSVC from sklearn.pipeline import make_pipeline from sklearn.cluster import KMeans from sklearn.dummy import DummyRegressor from sklearn.linear_model import Ridge, LogisticRegression from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from sklearn.datasets import make_blobs from sklearn.datasets import make_classification from sklearn.datasets import make_multilabel_classification from sklearn.datasets import load_diabetes from sklearn.cross_validation import train_test_split, cross_val_score from sklearn.grid_search import GridSearchCV from sklearn.multiclass import OneVsRestClassifier REGRESSION_SCORERS = ['r2', 'mean_absolute_error', 'mean_squared_error', 'median_absolute_error'] CLF_SCORERS = ['accuracy', 'f1', 'f1_weighted', 'f1_macro', 'f1_micro', 'roc_auc', 'average_precision', 'precision', 'precision_weighted', 'precision_macro', 'precision_micro', 'recall', 'recall_weighted', 'recall_macro', 'recall_micro', 'log_loss', 'adjusted_rand_score' # not really, but works ] MULTILABEL_ONLY_SCORERS = ['precision_samples', 'recall_samples', 'f1_samples'] class EstimatorWithoutFit(object): """Dummy estimator to test check_scoring""" pass class EstimatorWithFit(BaseEstimator): """Dummy estimator to test check_scoring""" def fit(self, X, y): return self class EstimatorWithFitAndScore(object): """Dummy estimator to test check_scoring""" def fit(self, X, y): return self def score(self, X, y): return 1.0 class EstimatorWithFitAndPredict(object): """Dummy estimator to test check_scoring""" def fit(self, X, y): self.y = y return self def predict(self, X): return self.y class DummyScorer(object): """Dummy scorer that always returns 1.""" def __call__(self, est, X, y): return 1 def test_check_scoring(): # Test all branches of check_scoring estimator = EstimatorWithoutFit() pattern = (r"estimator should a be an estimator implementing 'fit' method," r" .* was passed") assert_raises_regexp(TypeError, pattern, check_scoring, estimator) estimator = EstimatorWithFitAndScore() estimator.fit([[1]], [1]) scorer = check_scoring(estimator) assert_true(scorer is _passthrough_scorer) assert_almost_equal(scorer(estimator, [[1]], [1]), 1.0) estimator = EstimatorWithFitAndPredict() estimator.fit([[1]], [1]) pattern = (r"If no scoring is specified, the estimator passed should have" r" a 'score' method\. The estimator .* does not\.") assert_raises_regexp(TypeError, pattern, check_scoring, estimator) scorer = check_scoring(estimator, "accuracy") assert_almost_equal(scorer(estimator, [[1]], [1]), 1.0) estimator = EstimatorWithFit() scorer = check_scoring(estimator, "accuracy") assert_true(isinstance(scorer, _PredictScorer)) estimator = EstimatorWithFit() scorer = check_scoring(estimator, allow_none=True) assert_true(scorer is None) def test_check_scoring_gridsearchcv(): # test that check_scoring works on GridSearchCV and pipeline. # slightly redundant non-regression test. grid = GridSearchCV(LinearSVC(), param_grid={'C': [.1, 1]}) scorer = check_scoring(grid, "f1") assert_true(isinstance(scorer, _PredictScorer)) pipe = make_pipeline(LinearSVC()) scorer = check_scoring(pipe, "f1") assert_true(isinstance(scorer, _PredictScorer)) # check that cross_val_score definitely calls the scorer # and doesn't make any assumptions about the estimator apart from having a # fit. scores = cross_val_score(EstimatorWithFit(), [[1], [2], [3]], [1, 0, 1], scoring=DummyScorer()) assert_array_equal(scores, 1) def test_make_scorer(): # Sanity check on the make_scorer factory function. f = lambda *args: 0 assert_raises(ValueError, make_scorer, f, needs_threshold=True, needs_proba=True) def test_classification_scores(): # Test classification scorers. X, y = make_blobs(random_state=0, centers=2) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = LinearSVC(random_state=0) clf.fit(X_train, y_train) for prefix, metric in [('f1', f1_score), ('precision', precision_score), ('recall', recall_score)]: score1 = get_scorer('%s_weighted' % prefix)(clf, X_test, y_test) score2 = metric(y_test, clf.predict(X_test), pos_label=None, average='weighted') assert_almost_equal(score1, score2) score1 = get_scorer('%s_macro' % prefix)(clf, X_test, y_test) score2 = metric(y_test, clf.predict(X_test), pos_label=None, average='macro') assert_almost_equal(score1, score2) score1 = get_scorer('%s_micro' % prefix)(clf, X_test, y_test) score2 = metric(y_test, clf.predict(X_test), pos_label=None, average='micro') assert_almost_equal(score1, score2) score1 = get_scorer('%s' % prefix)(clf, X_test, y_test) score2 = metric(y_test, clf.predict(X_test), pos_label=1) assert_almost_equal(score1, score2) # test fbeta score that takes an argument scorer = make_scorer(fbeta_score, beta=2) score1 = scorer(clf, X_test, y_test) score2 = fbeta_score(y_test, clf.predict(X_test), beta=2) assert_almost_equal(score1, score2) # test that custom scorer can be pickled unpickled_scorer = pickle.loads(pickle.dumps(scorer)) score3 = unpickled_scorer(clf, X_test, y_test) assert_almost_equal(score1, score3) # smoke test the repr: repr(fbeta_score) def test_regression_scorers(): # Test regression scorers. diabetes = load_diabetes() X, y = diabetes.data, diabetes.target X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = Ridge() clf.fit(X_train, y_train) score1 = get_scorer('r2')(clf, X_test, y_test) score2 = r2_score(y_test, clf.predict(X_test)) assert_almost_equal(score1, score2) def test_thresholded_scorers(): # Test scorers that take thresholds. X, y = make_blobs(random_state=0, centers=2) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = LogisticRegression(random_state=0) clf.fit(X_train, y_train) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, clf.decision_function(X_test)) score3 = roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1]) assert_almost_equal(score1, score2) assert_almost_equal(score1, score3) logscore = get_scorer('log_loss')(clf, X_test, y_test) logloss = log_loss(y_test, clf.predict_proba(X_test)) assert_almost_equal(-logscore, logloss) # same for an estimator without decision_function clf = DecisionTreeClassifier() clf.fit(X_train, y_train) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1]) assert_almost_equal(score1, score2) # test with a regressor (no decision_function) reg = DecisionTreeRegressor() reg.fit(X_train, y_train) score1 = get_scorer('roc_auc')(reg, X_test, y_test) score2 = roc_auc_score(y_test, reg.predict(X_test)) assert_almost_equal(score1, score2) # Test that an exception is raised on more than two classes X, y = make_blobs(random_state=0, centers=3) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf.fit(X_train, y_train) assert_raises(ValueError, get_scorer('roc_auc'), clf, X_test, y_test) def test_thresholded_scorers_multilabel_indicator_data(): # Test that the scorer work with multilabel-indicator format # for multilabel and multi-output multi-class classifier X, y = make_multilabel_classification(allow_unlabeled=False, random_state=0) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) # Multi-output multi-class predict_proba clf = DecisionTreeClassifier() clf.fit(X_train, y_train) y_proba = clf.predict_proba(X_test) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, np.vstack(p[:, -1] for p in y_proba).T) assert_almost_equal(score1, score2) # Multi-output multi-class decision_function # TODO Is there any yet? clf = DecisionTreeClassifier() clf.fit(X_train, y_train) clf._predict_proba = clf.predict_proba clf.predict_proba = None clf.decision_function = lambda X: [p[:, 1] for p in clf._predict_proba(X)] y_proba = clf.decision_function(X_test) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, np.vstack(p for p in y_proba).T) assert_almost_equal(score1, score2) # Multilabel predict_proba clf = OneVsRestClassifier(DecisionTreeClassifier()) clf.fit(X_train, y_train) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, clf.predict_proba(X_test)) assert_almost_equal(score1, score2) # Multilabel decision function clf = OneVsRestClassifier(LinearSVC(random_state=0)) clf.fit(X_train, y_train) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, clf.decision_function(X_test)) assert_almost_equal(score1, score2) def test_unsupervised_scorers(): # Test clustering scorers against gold standard labeling. # We don't have any real unsupervised Scorers yet. X, y = make_blobs(random_state=0, centers=2) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) km = KMeans(n_clusters=3) km.fit(X_train) score1 = get_scorer('adjusted_rand_score')(km, X_test, y_test) score2 = adjusted_rand_score(y_test, km.predict(X_test)) assert_almost_equal(score1, score2) @ignore_warnings def test_raises_on_score_list(): # Test that when a list of scores is returned, we raise proper errors. X, y = make_blobs(random_state=0) f1_scorer_no_average = make_scorer(f1_score, average=None) clf = DecisionTreeClassifier() assert_raises(ValueError, cross_val_score, clf, X, y, scoring=f1_scorer_no_average) grid_search = GridSearchCV(clf, scoring=f1_scorer_no_average, param_grid={'max_depth': [1, 2]}) assert_raises(ValueError, grid_search.fit, X, y) @ignore_warnings def test_scorer_sample_weight(): # Test that scorers support sample_weight or raise sensible errors # Unlike the metrics invariance test, in the scorer case it's harder # to ensure that, on the classifier output, weighted and unweighted # scores really should be unequal. X, y = make_classification(random_state=0) _, y_ml = make_multilabel_classification(n_samples=X.shape[0], random_state=0) split = train_test_split(X, y, y_ml, random_state=0) X_train, X_test, y_train, y_test, y_ml_train, y_ml_test = split sample_weight = np.ones_like(y_test) sample_weight[:10] = 0 # get sensible estimators for each metric sensible_regr = DummyRegressor(strategy='median') sensible_regr.fit(X_train, y_train) sensible_clf = DecisionTreeClassifier(random_state=0) sensible_clf.fit(X_train, y_train) sensible_ml_clf = DecisionTreeClassifier(random_state=0) sensible_ml_clf.fit(X_train, y_ml_train) estimator = dict([(name, sensible_regr) for name in REGRESSION_SCORERS] + [(name, sensible_clf) for name in CLF_SCORERS] + [(name, sensible_ml_clf) for name in MULTILABEL_ONLY_SCORERS]) for name, scorer in SCORERS.items(): if name in MULTILABEL_ONLY_SCORERS: target = y_ml_test else: target = y_test try: weighted = scorer(estimator[name], X_test, target, sample_weight=sample_weight) ignored = scorer(estimator[name], X_test[10:], target[10:]) unweighted = scorer(estimator[name], X_test, target) assert_not_equal(weighted, unweighted, msg="scorer {0} behaves identically when " "called with sample weights: {1} vs " "{2}".format(name, weighted, unweighted)) assert_almost_equal(weighted, ignored, err_msg="scorer {0} behaves differently when " "ignoring samples and setting sample_weight to" " 0: {1} vs {2}".format(name, weighted, ignored)) except TypeError as e: assert_true("sample_weight" in str(e), "scorer {0} raises unhelpful exception when called " "with sample weights: {1}".format(name, str(e)))
bsd-3-clause