repo_name
stringlengths 7
79
| path
stringlengths 4
179
| copies
stringlengths 1
3
| size
stringlengths 4
6
| content
stringlengths 959
798k
| license
stringclasses 15
values |
---|---|---|---|---|---|
jpautom/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
|
fmacias64/spyre
|
examples/d3_example.py
|
3
|
2432
|
# requires d3py library
# only tested with python 2.7
from spyre import server
import numpy as np
import pandas as pd
import d3py
import matplotlib.pyplot as plt
class FruitInventoryApp(server.App):
title = "Spyre Example With d3"
inputs = [{ "input_type":'dropdown',
"label": 'Type',
"options" : [ {"label": "Fruits", "value":"frt"},
{"label": "Vegetables", "value":"veg"},
{"label": "All", "value":"all"}],
"variable_name": 'type',
"value": "all",
"action_id":"submit_plot"}]
controls = [{ "control_type" : "hidden",
"label" : "show inventory",
"control_id" : "submit_plot"}]
outputs = [{ "output_type" : "plot",
"output_id" : "plot1",
"control_id" : "submit_plot",
"tab" : "Matplotlib_Plot",
"on_page_load" : True},
{ "output_type" : "d3",
"control_id" : "submit_plot",
"output_id" : "d3_output",
"tab" : "d3_Plot",
"on_page_load" : True}]
tabs = ["d3_Plot", "Matplotlib_Plot"]
def getData(self, params):
type_var = params['type']
if type_var=="frt":
count = [6,7,5,2]
item = ['Apples','Oranges','Bananas','Watermelons']
elif type_var=="veg":
count = [3,1,7,8,2]
item = ['Carrots','Spinach','Squash','Asparagus','Brocolli']
else:
count = [3,1,7,8,2,6,7,5,2]
item = ['Carrots','Spinach','Squash','Asparagus','Brocolli','Apples','Oranges','Bananas','Watermelons']
df = pd.DataFrame({'item':item, 'count':count})
df = df[['item','count']]
return df
def getPlot(self, params):
data = self.getData(params) # get data
fig = plt.figure() # make figure object
splt = fig.add_subplot(1,1,1)
ind = np.arange(len(data['item']))
width = 0.85
splt.bar(ind,data['count'], width)
splt.set_ylabel('Count')
splt.set_title('NBS Category Count')
xTickMarks = ['Group'+str(i) for i in range(1,6)]
splt.set_xticks(ind+width/2)
splt.set_xticklabels(data['item'].tolist())
fig.autofmt_xdate(rotation=45)
return fig
def getD3(self, xlabel="item", ylabel="count"):
df = pd.DataFrame({xlabel:[],ylabel:[]})
p = d3py.PandasFigure(df)
p += d3py.Bar(x = xlabel, y=ylabel)
# p += d3py.Line(x = xlabel, y=ylabel)
p += d3py.xAxis(x = xlabel)
p += d3py.yAxis(y = ylabel)
p.update()
p.js.merge(p.js_geoms)
d3 = {}
d3['js'] = p.js
d3['css'] = "%s\n%s"%(p.css, p.css_geoms)
return d3
if __name__ == '__main__':
app = FruitInventoryApp()
app.launch(port=9092)
|
mit
|
avkhadiev/polymer
|
plot/test_algorithms.py
|
1
|
3687
|
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from math import pi
import matplotlib.ticker as mticker
class MathTextSciFormatter(mticker.Formatter):
def __init__(self, fmt="%1.2e"):
self.fmt = fmt
def __call__(self, x, pos=None):
s = self.fmt % x
decimal_point = '.'
positive_sign = '+'
tup = s.split('e')
significand = tup[0].rstrip(decimal_point)
sign = tup[1][0].replace(positive_sign, '')
exponent = tup[1][1:].lstrip('0')
if exponent:
exponent = '10^{%s%s}' % (sign, exponent)
if significand and exponent:
s = r'%s{\times}%s' % (significand, exponent)
else:
s = r'%s%s' % (significand, exponent)
return "${}$".format(s)
def colname(name, k):
return "%s (k=%d)" % (name, k)
def mathenv(tex):
return "$" +tex + "$"
def search(key, value):
return key + "==" + "'" + value + "'"
def make_label(name, units):
return mathenv(name) + ", " + mathenv("\\left[" + units + "\\right]")
def make_title(sim, yl, ell):
return (sim + ": "
+ mathenv(yl + "\\left(" + "\\tau" + "\\right)") + ", "
+ mathenv("\\ell=" + "%5.3f" % ell))
sim_name = 'test'
sims = ['shove', 'plerp']#,'md']
lbls = ['Old Plerp', 'New Plerp']#,'MD']
fdir = "test/geodesic/"
outdir = "/Users/Arthur/stratt/lab_notebook/"
# xlabel, xunits
xl = "\\tau = \\ell^{(m)}/\\,\\ell^{\\mathrm{f}}"
xu = "1"
xr = [-0.01, 1.01]
fs = 14 # fontsize
observables = ['omega_norm']
# ylabels = ['\\hat{\\Omega} \\cdot \\hat{n}', '\\psi', '\\left|1 - \\left|\\hat{\\Omega}\\right|\\right|']
ylabels = ['\\left|1 - \\left|\\hat{\\Omega}\\right|\\right|']
yunits = ['1', '\\mathrm{rad}', '1']
yranges = [[-1.01, 1.01], [-0.2, pi + 0.2], [-0.1, 2.1]]
# indices = [1, 2] # only plot first link
colors = ['b', 'r', 'k']
styles = ['--', '--', '-']
for (obs, yl, yu, yr) in zip(observables, ylabels, yunits, yranges):
fig, ax = plt.subplots()
# plt.title(make_title(sim, yl, ell), fontsize = fs)
plt.xlabel(mathenv(xl), fontsize = fs + 2.5)
plt.ylabel(make_label(yl, yu), fontsize = fs + 2.5)
plt.xticks(fontsize=fs + 1.5)
plt.yticks(fontsize=fs + 1.5)
# plt.grid(True)
for (sim, c, l, lbl) in zip(sims, colors, styles, lbls):
data = pd.read_csv(fdir + sim_name + sim + "_inst_data.csv")
# meta = pd.read_csv(fdir + sim_name + sim + "_meta_data.csv")
lengths = data['ell'].values
ell = lengths[-1]
tau = lengths / ell # affine parameter
# select element in array closest to 0.1
idx = (np.abs(tau-1.0)).argmin()
plt.ylim(yr)
if ((sim == 'slerp') and (obs == 'delta_theta')):
plt.plot(tau[0:idx], np.zeros((tau[0:idx]).shape), color = c, linestyle = l, label = (lbl + " link"))
plt.plot(tau[0:idx], np.zeros((tau[0:idx]).shape), color = c, linestyle = l, label = (lbl + " link"))
elif ((obs == 'omega_norm') and ((sim != 'shove') and ((sim != 'plerp'))) ):
continue
else:
col = colname(obs, 2)
# tex = meta.query(search("short_name", col))['tex_name'].item() # wut label to use?
var = data[col].values
if (obs == 'omega_norm'):
plt.semilogy(tau[0:idx], abs(1 - var[0:idx]), color = c, linestyle = l, label = (lbl + " link"))
else:
plt.plot(tau[0:idx], var[0:idx], color = c, linestyle = l, label = (lbl + " link"))
plt.legend(prop={'size': fs})
plt.tight_layout()
plt.savefig(outdir + obs + ".png", dpi = 300)
plt.close(fig)
|
mit
|
huddlej/populations
|
genotype_frequencies.ipynb.py
|
1
|
1739
|
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
import random
# <markdowncell>
# Genotypes and phenotypes
# ========================
#
# Genotypes are biallelic in the form of (0, 1) where 0 is a recessive allele and 1 is a dominant allele. Each genotype is associated with a character of the organism (e.g., seed color) and recessive and dominant phenotypes (e.g., "green" and "yellow").
# <codecell>
def create_parental_population(n, is_dominant):
if is_dominant:
return np.ones((n, 2), dtype=np.integer)
else:
return np.zeros((n, 2), dtype=np.integer)
# <codecell>
n = 1000
# <codecell>
p1_dominant = create_parental_population(n, True)
# <codecell>
p1_recessive = create_parental_population(n, False)
# <codecell>
def cross_populations(population1, population2):
return np.array(
zip(
np.apply_along_axis(random.choice, 1, population1),
np.apply_along_axis(random.choice, 1, population2)
)
)
# <codecell>
f1 = cross_populations(p1_dominant, p1_recessive)
# <codecell>
f2 = cross_populations(f1, f1)
# <codecell>
def get_genotype_frequencies(population):
df = DataFrame(Series(np.apply_along_axis(sum, 1, population)), columns=["genotypes"])
counts = df.groupby("genotypes").count()
return counts.apply(lambda x: x / float(counts.sum()))
# <codecell>
get_genotype_frequencies(p1_recessive)
# <codecell>
get_genotype_frequencies(p1_dominant)
# <codecell>
get_genotype_frequencies(f1)
# <codecell>
get_genotype_frequencies(f2)
# <codecell>
f3 = cross_populations(f2, f2)
# <codecell>
get_genotype_frequencies(f3)
# <codecell>
|
mit
|
SpinStabilized/stem_station
|
p.py
|
1
|
20835
|
from __future__ import division
import argparse
import datetime
import json
import matplotlib.pyplot as plt
import numpy as np
import os.path
import pmt
import scipy.stats
import struct
import sys
from gnuradio.blocks import parse_file_metadata
from PIL import Image, ImageOps
from itertools import izip_longest
################################################################################
# Function Definitions
################################################################################
def grouper(n, iterable, fillvalue=None):
'''Collect data into fixed-length chunks or blocks
Breaks a list (iterable) into groups of n. The last list is filled with
fillvalue to get to the n size if it is less than n. Sourced from:
https://docs.python.org/2/library/itertools.html
Args:
n: Number of items in each resultant list
iterable: List of items to break into smaller lists
fillevalue: Optional parameter defines fill items for final list
Returns:
A list of lists where the input list is broken into lists of length n.
For example:
grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
'''
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
def scale_pixels(pixels, out_min=0, out_max=255):
in_max = max([max(line) for line in pixels])
in_min = min([min(line) for line in pixels])
for i, line in enumerate(pixels):
for j, pixel in enumerate(line):
pixels[i][j] = (pixel - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
pixels[i][j] = int(round(pixels[i][j]))
return pixels
def process_tlm(tlm_strip):
tlm = [int(round(sum(line)/len(line))) for line in tlm_strip]
deltas = []
for i, point in enumerate(tlm):
if i != 0:
difference = abs(tlm[i] - tlm[i-1])
else:
difference = 0
deltas.append(difference)
frame_center = np.argmax(deltas)
frame_start = frame_center - 64
frame_end = frame_start + 128
tlm_frame = tlm[frame_start:frame_end]
tlm_points = [int(sum(point)/len(point)) for point in grouper(8, tlm_frame, tlm_frame[-1])]
return tlm_points, tlm
def process_tlm2(tlm_strip):
# plt.imshow(tlm_strip)
# plt.show()
tlm = [sum(line)/len(line) for line in tlm_strip]
deltas = []
for i, point in enumerate(tlm):
if i != 0:
difference = abs(tlm[i] - tlm[i-1])
else:
difference = 0
deltas.append(difference)
frame_center = np.argmax(deltas)
frame_start = frame_center - 64
frame_end = frame_start + 128
tlm_frame = tlm[frame_start:frame_end]
tlm_points = [sum(point)/len(point) for point in grouper(8, tlm_frame, tlm_frame[-1])]
return tlm_points, tlm
def space_view(space_mark_strip):
raw_strips = [int(round(sum(line)/len(line))) for line in space_mark_strip]
# space_view_pixels = [pixel for line in space_mark_strip for pixel in line]
hist = np.histogram(raw_strips, bins=256)
hist_max = np.argmax(hist[0])
if hist_max > 127:
data = raw_strips
for i, point in enumerate(data):
if point < 127 and i is not 0:
data[i] = data[i-1]
else:
data = raw_strips
for i, point in enumerate(data):
if point > 127 and i is not 0:
data[i] = data[i-1]
data_avg = int(round(np.mean(data)))
return data_avg, data
def closest(val, l):
'''Determines the closest value from a list to a value
Args:
val: Value to determine the closest to a value in l
l: List of values
Returns:
Value from l closest to val. For example:
closest(0.8, [0, 0.25, 0.5, 0.75, 1]) --> 0.75
Source: http://goo.gl/kPeY0x
'''
return np.abs(np.array(l)-val).argmin()
def avhrr_prt_cal(x, a, eight_bits=True):
'''NOAA AVHRR PRT Calibration Formula
Args:
x: Raw counts value
a: PRT calibration table for a specific AVHRR
Returns:
Value of x as a temperature (Kelvin) for a specific AVHRR calibration
table provided in a.
'''
if eight_bits:
x = x * 4
return sum([a[j] * x ** j for j in range(0, 5)])
def avhrr_bb_temp(T, b):
'''NOAA AVHRR Blackbody Calibration Formula
Args:
T: List of PRT temperatures
b: BB PRT weighting table for a specific AVHRR
Returns:
Returns a blackbody temperature (Kelvin) based on the calibrated
weighting for a specific AVHRR.
'''
return sum([T[i] * b[i] for i in range(0, 4)])
def moving_average(l, window_size, pad=True):
smoothed = list(np.convolve(l, np.ones((window_size,))/window_size, mode='valid')[(window_size-1):])
if pad:
pad_data = [smoothed[0]] * ((window_size-1) * 2)
smoothed = pad_data + smoothed
return smoothed
def parse_gnuradio_header(header_file, verbose=False):
headers = []
index = 0
rx_time = datetime.timedelta(seconds = 0)
with open(header_file, 'rb') as handle:
file_length = os.path.getsize(header_file)
while True:
if file_length - handle.tell() < parse_file_metadata.HEADER_LENGTH:
break
header_str = handle.read(parse_file_metadata.HEADER_LENGTH)
try:
header = pmt.deserialize_str(header_str)
except RuntimeError:
break
info = parse_file_metadata.parse_header(header, verbose)
if info['nbytes'] == 0:
break
if(info['extra_len'] > 0):
extra_str = handle.read(info['extra_len'])
if(len(extra_str) == 0):
break
try:
extra = pmt.deserialize_str(extra_str)
except RuntimeError:
break
parse_file_metadata.parse_extra_dict(extra, info, verbose)
if len(headers) > 0:
last_rx_time = headers[-1]['rx_time']
samples_delta = headers[-1]['nitems'] / headers[-1]['rx_rate']
samples_delta = datetime.timedelta(seconds=samples_delta)
info['rx_time'] = last_rx_time + samples_delta
info['index'] = index
index = index + info['nitems']
else:
info['rx_time'] = datetime.timedelta(seconds=0.0)
info['index'] = 0
index = info['nitems']
headers.append(info)
return headers
################################################################################
# Define some constants and useful derived constants
################################################################################
PIXEL_MIN = 0
PIXEL_MAX = 255
SYNC_WIDTH = 39
SPACE_MARK_WIDTH = 47
IMAGE_WIDTH = 909
TLM_FRAME_WIDTH = 45
FULL_CHANNEL_WIDTH = SYNC_WIDTH + SPACE_MARK_WIDTH + IMAGE_WIDTH + TLM_FRAME_WIDTH
FULL_LINE_WIDTH = FULL_CHANNEL_WIDTH * 2
SYNC_RANGE = {'A':(0, SYNC_WIDTH),
'B':(FULL_CHANNEL_WIDTH, FULL_CHANNEL_WIDTH + SYNC_WIDTH)}
SPACE_MARK_RANGE = {'A':(SYNC_RANGE['A'][1], SYNC_RANGE['A'][1] + SPACE_MARK_WIDTH),
'B':(SYNC_RANGE['B'][1], SYNC_RANGE['B'][1] + SPACE_MARK_WIDTH)}
IMAGE_RANGE = {'A':(SPACE_MARK_RANGE['A'][1], SPACE_MARK_RANGE['A'][1] + IMAGE_WIDTH),
'B':(SPACE_MARK_RANGE['B'][1], SPACE_MARK_RANGE['B'][1] + IMAGE_WIDTH)}
TLM_FRAME_RANGE = {'A':(IMAGE_RANGE['A'][1], IMAGE_RANGE['A'][1] + TLM_FRAME_WIDTH),
'B':(IMAGE_RANGE['B'][1], IMAGE_RANGE['B'][1] + TLM_FRAME_WIDTH)}
BYTES_PER_FLOAT = 4
GRAYSCALE = 'L'
################################################################################
# Parse CLI Arguments
################################################################################
parser = argparse.ArgumentParser()
parser.add_argument('input_file', help='Raw APT demodulated data file')
parser.add_argument('-s', '--spacecraft', default='NOAA-19', help='Spacecraft captured (for calibration)')
parser.add_argument('-d', '--direction', default='north', help='Pass to the \'north\' or \'south\'')
parser.add_argument('-a', '--all', action='store_true', default=False, help='Show all data lines, not just aligned')
args = parser.parse_args()
input_file_directory = os.path.dirname(args.input_file) + '/'
input_filename_base, _ = os.path.splitext(os.path.basename(args.input_file))
header_file = input_file_directory + os.path.basename(args.input_file) + '.hdr'
with open('calibration/avhrr.json') as avhrr_cal_json:
avhrr_cal = json.load(avhrr_cal_json)
CAL_DATA = avhrr_cal['CAL_DATA']
AVHRR_CHANNELS = avhrr_cal['AVHRR_CHANNELS']
spacecraft = args.spacecraft
if spacecraft not in CAL_DATA:
print('Warning spacecraft {} not found in calibration data. Defaulting to NOAA-19'.format(spacecraft))
spacecraft = 'NOAA-19'
# Parse the header file to find the SyncA markers
has_header = os.path.isfile(header_file)
syncs = []
if has_header:
print('Opening {}'.format(header_file))
headers = parse_gnuradio_header(header_file)
start = datetime.datetime.now()
# time_marks = [start + header['rx_time'] for header in headers]
# for mark in time_marks:
# print mark
last_rx_time = headers[-1]['rx_time']
samples_delta = headers[-1]['nitems'] / headers[-1]['rx_rate']
samples_delta = datetime.timedelta(seconds=samples_delta)
end = start + (last_rx_time + samples_delta)
capture_duration = end - start
# print 'Capture Start: {}'.format(start)
# print 'Capture Finish: {}'.format(end)
# print 'Capture Duration: {}'.format(end - start)
syncs = headers
# debug = False
# current_position = 0
# with open(header_file, 'rb') as handle:
# file_length = os.path.getsize(header_file)
# while True:
#
# if (file_length - handle.tell()) < parse_file_metadata.HEADER_LENGTH:
# break
#
# header_str = handle.read(parse_file_metadata.HEADER_LENGTH)
#
# try:
# header = pmt.deserialize_str(header_str)
# except RuntimeError:
# sys.stderr.write('Could not deserialize header: invalid or corrupt data file.\n')
# sys.exit(1)
#
# info = parse_file_metadata.parse_header(header, debug)
# if info['nbytes'] == 0:
# break
#
# if(info['extra_len'] > 0):
# extra_str = handle.read(info['extra_len'])
# if(len(extra_str) == 0):
# break
#
# try:
# extra = pmt.deserialize_str(extra_str)
# except RuntimeError:
# sys.stderr.write('Could not deserialize extras: invalid or corrupt data file.\n')
# sys.exit(1)
#
# extra_info = parse_file_metadata.parse_extra_dict(extra, info, debug)
#
# if 'SyncA' in info:
# info['index'] = current_position - SYNC_WIDTH
# syncs.append(info)
#
# current_position = current_position + info['nitems']
else:
print('No Header File Found - Raw Processing')
# sys.exit(1)
print('Opening {}'.format(args.input_file))
with open(args.input_file, 'rb') as raw_data:
raw_bytes = bytearray(raw_data.read())
samples_found = len(raw_bytes) // BYTES_PER_FLOAT
unpack_format = '<' + ('f' * samples_found)
pixels = list(struct.unpack(unpack_format, raw_bytes))
file_duration = datetime.timedelta(seconds = len(pixels) / (FULL_LINE_WIDTH * 2))
print('Capture Duration: {}'.format(capture_duration))
print('Aligning Sync Signals')
sync_ratio = 0
if len(syncs):
pre_syncs = []
new_pixels = []
sync_lines = []
# print syncs[1]
# print next(header for header in syncs if 'SyncA' in header)
first_sync = next(header for header in syncs if 'SyncA' in header)
print first_sync
pre_syncs = pixels[0:first_sync['index']]
# pre_syncs = pixels[0:syncs[0]['index']]
additional_pixels = FULL_LINE_WIDTH - (len(pre_syncs) % FULL_LINE_WIDTH)
pre_syncs = ([0] * additional_pixels) + pre_syncs
pre_syncs = [list(line) for line in grouper(FULL_LINE_WIDTH, pre_syncs, 0)]
i = 0
for sync in syncs:
sync_lines.append(i)
pixel_set = pixels[sync['index']:sync['index'] + sync['nitems']]
pixel_set = [list(line) for line in grouper(FULL_LINE_WIDTH, pixel_set, pixel_set[-1])]
if all(x == pixel_set[-1][0] for x in pixel_set[-1]):
del pixel_set[-1]
i += len(pixel_set)
new_pixels.extend(pixel_set)
aligned_start = len(pre_syncs)
pixels = new_pixels
sync_ratio = len(syncs)/float(len(pixels))
if args.all:
pixels = pre_syncs + new_pixels
else:
print('No Syncs Found - Minimal Processing')
pixels = [list(line) for line in grouper(FULL_LINE_WIDTH, pixels, 0)]
pixels = scale_pixels(pixels)
plt.imshow(pixels)
plt.show()
sync_ratio = len(syncs)/float(len(pixels))
if sync_ratio > 0.05:
print('Telemetry Processing - Find Analog to Digital Range From Wedges'.format(spacecraft))
a_tlm = [line[TLM_FRAME_RANGE['A'][0]:TLM_FRAME_RANGE['A'][1]] for line in pixels]
b_tlm = [line[TLM_FRAME_RANGE['B'][0]:TLM_FRAME_RANGE['B'][1]] for line in pixels]
a_telemetry, _ = process_tlm2(a_tlm)
b_telemetry, _ = process_tlm2(b_tlm)
unified_tlm = [sum(x)/2 for x in zip(a_telemetry[0:14], b_telemetry[0:14])]
telemetry = {'wedges':unified_tlm[0:8], 'zero_mod':unified_tlm[8]}
print('Scaling to wedge calibration')
pixels = [np.clip(line, telemetry['zero_mod'], telemetry['wedges'][-1]) for line in pixels]
pixels = scale_pixels(pixels)
print('Reprocessing of Telemetry for {}'.format(spacecraft))
a_tlm = [line[TLM_FRAME_RANGE['A'][0]:TLM_FRAME_RANGE['A'][1]] for line in pixels]
b_tlm = [line[TLM_FRAME_RANGE['B'][0]:TLM_FRAME_RANGE['B'][1]] for line in pixels]
a_telemetry, tlm_a_strip = process_tlm(a_tlm)
b_telemetry, tlm_b_strip = process_tlm(b_tlm)
unified_tlm = [int(round(sum(x)/2)) for x in zip(a_telemetry[0:14], b_telemetry[0:14])]
telemetry = {'wedges':unified_tlm[0:8], 'zero_mod':unified_tlm[8],
'bb_thermistors':unified_tlm[9:13], 'patch_thermistor':unified_tlm[13],
'a_bb':a_telemetry[14], 'a_channel':a_telemetry[15], 'a_space':0,
'b_bb':b_telemetry[14], 'b_channel':b_telemetry[15], 'b_space':0}
ideal_curve = [int(255 * (i / len(telemetry['wedges']))) for i in range(len(telemetry['wedges'])+ 1)]
initial_curve = [telemetry['zero_mod']] + telemetry['wedges']
data_fit = scipy.stats.linregress(ideal_curve, initial_curve)
telemetry['a_channel'] = closest(telemetry['a_channel'], telemetry['wedges'])+1
telemetry['b_channel'] = closest(telemetry['b_channel'], telemetry['wedges'])+1
telemetry['prt_temps'] = [avhrr_prt_cal(telemetry['bb_thermistors'][j], CAL_DATA[spacecraft]['a'][j]) for j in range(0, 4)]
telemetry['bb_temp'] = avhrr_bb_temp(telemetry['prt_temps'], CAL_DATA[spacecraft]['b'])
telemetry['patch_temp'] = (0.124 * telemetry['patch_thermistor']) + 90.113
a_info = AVHRR_CHANNELS[str(telemetry['a_channel'])]
b_info = AVHRR_CHANNELS[str(telemetry['b_channel'])]
a_space_mark = [line[SPACE_MARK_RANGE['A'][0]:SPACE_MARK_RANGE['A'][1]] for line in pixels]
b_space_mark = [line[SPACE_MARK_RANGE['B'][0]:SPACE_MARK_RANGE['B'][1]] for line in pixels]
telemetry['a_space'], raw_a_space_mark_strip = space_view(a_space_mark)
telemetry['b_space'], raw_b_space_mark_strip = space_view(b_space_mark)
print('Image Information:')
print('\tFrame A: AVHRR Channel {} - {} - {}'.format(a_info['channel_id'], a_info['type'], a_info['description']))
print('\tFrame B: AVHRR Channel {} - {} - {}'.format(b_info['channel_id'], b_info['type'], b_info['description']))
print('\tWedges: {}'.format(telemetry['wedges']))
print('\tZero Mod Ref: {}'.format(telemetry['zero_mod']))
print('\tA Blackbody/Space: {:3} / {:3}'.format(telemetry['a_bb'], telemetry['a_space']))
print('\tB Blackbody/Space: {:3} / {:3}'.format(telemetry['b_bb'], telemetry['b_space']))
print('\tPRTs (counts): {}'.format(' '.join(['{:<9.0f}'.format(samp) for samp in telemetry['bb_thermistors']])))
print('\tPRTs (Kelvin): {}'.format(' '.join(['{:.2f} K'.format(temp) for temp in telemetry['prt_temps']])))
print('\tBlackbody Ref Temp: {:.2f} K'.format(telemetry['bb_temp']))
print('\tPatch Temp: {:.0f} cnts -- {:.2f} K'.format(telemetry['patch_thermistor'], telemetry['patch_temp']))
print('Image Reception Quality:')
print('\tSyncs ({})/Lines ({}) Ratio: {:.2%}'.format(len(syncs), len(pixels), sync_ratio))
print('\tCalibration Linearity: {:.4%}'.format(data_fit.rvalue))
print('Generating Calibration Curve Plots')
# plt.style.use('dark_background')
plt.suptitle(spacecraft, fontsize=15, fontweight='bold')
plt.figure(0, figsize=(8.5, 11))
plt.suptitle(spacecraft, fontsize=15, fontweight='bold')
# plt.subplot(411)
plt.subplot2grid((3,2), (0,1))
handle_ideal, = plt.plot(ideal_curve, ideal_curve, 'g-', label='Ideal')
handle_initial, _ = plt.plot(ideal_curve, initial_curve, 'r-', ideal_curve, initial_curve, 'r^', label='Received')
plt.axis([0, 255, 0, 255])
plt.xlabel('Ideal Curve Points')
plt.ylabel('Received Curve Points')
plt.title('Analog to Digital Cal Curve')
plt.legend(handles=[handle_ideal, handle_initial], loc=4)
plt.grid(b=True, which='major', color='grey', linestyle='--')
plt.xticks(ideal_curve)
plt.yticks(ideal_curve)
# plt.savefig(input_file_directory + 'plot_cal_curves.png')
# print('Generating Telemetry Text-Only Plot')
# plt.figure(3, figsize=(10, 5))
# plt.subplot(412)
plt.subplot2grid((3,2), (0,0))
plt.axis('off')
plt.text(0, 0.95, 'Frame A: AVHRR Channel {} - {} - {}'.format(a_info['channel_id'], a_info['type'], a_info['description']))
plt.text(0, 0.90, 'Frame B: AVHRR Channel {} - {} - {}'.format(b_info['channel_id'], b_info['type'], b_info['description']))
plt.text(0, 0.85, 'PRTs: {}'.format(' '.join(['{:.2f} K'.format(temp) for temp in telemetry['prt_temps']])))
plt.text(0, 0.80, 'Blackbody Ref Temp: {:.2f} K'.format(telemetry['bb_temp']))
plt.text(0, 0.75, 'Patch Temp: {:.2f} K'.format(telemetry['patch_temp']))
print('Generating Plot of Raw Telemetry Strips')
# plt.figure(1, figsize=(12, 5))
# plt.subplot(413)
plt.subplot2grid((3,2), (1,0), colspan=2)
plt.axis([0, max(len(tlm_a_strip), len(tlm_b_strip)), 0, 255])
plt.xlabel('Line Number')
plt.ylabel('Counts')
plt.title('Telemetry Strips')
plt.plot(tlm_a_strip, 'g', label='Channel A')
plt.plot(tlm_b_strip, 'b', label='Channel B')
plt.grid(b=True, which='major', color='grey', linestyle='--')
plt.xticks(np.arange(0, len(tlm_a_strip), 16*8))
plt.yticks(ideal_curve)
# plt.savefig(input_file_directory + 'plot_tlm_strips.png')
print('Generating Plot of Space View')
# plt.figure(2, figsize=(12, 5))
# plt.subplot(414)
plt.subplot2grid((3,2), (2,0), colspan=2)
plt.axis([0, max(len(tlm_a_strip), len(tlm_b_strip)), 0, 255])
plt.xlabel('Line Number')
plt.ylabel('Counts')
plt.title('Space View Strips')
raw_a_space_smoothed = moving_average(raw_a_space_mark_strip, 30)
raw_b_space_smoothed = moving_average(raw_b_space_mark_strip, 30)
plt.plot(raw_a_space_mark_strip, 'g', label='Channel A')
plt.plot(raw_a_space_smoothed, 'r--')
plt.plot(raw_b_space_mark_strip, 'b', label='Channel B')
plt.plot(raw_b_space_smoothed, 'r--')
plt.legend(loc='center right')
plt.xticks(np.arange(0, len(tlm_a_strip), 16*8))
plt.yticks(ideal_curve)
plt.grid(b=True, which='major', color='grey', linestyle='--')
# plt.savefig(input_file_directory + 'plot_space_view.png')
plt.savefig(input_file_directory + 'plot_telemetry.png')
# else:
raw_images = {}
raw_images['F'] = pixels
if len(syncs):
raw_images['A'] = [line[IMAGE_RANGE['A'][0]:IMAGE_RANGE['A'][1]] for line in pixels]
raw_images['B'] = [line[IMAGE_RANGE['B'][0]:IMAGE_RANGE['B'][1]] for line in pixels]
for image in raw_images:
lines = len(raw_images[image])
width = len(raw_images[image][0])
pixels = [item for sublist in raw_images[image] for item in sublist]
output_file = input_file_directory + input_filename_base + image + '.png'
image = Image.new(GRAYSCALE, (width, lines))
image.putdata(pixels)
if args.direction == 'north':
image = image.rotate(180)
if not len(syncs):
image = ImageOps.equalize(image)
image.save(output_file)
|
gpl-3.0
|
opoplawski/StarCluster
|
utils/scimage_13_04.py
|
19
|
17696
|
#!/usr/bin/env python
"""
This script is meant to be run inside of a ubuntu cloud image available at
uec-images.ubuntu.com::
$ EC2_UBUNTU_IMG_URL=http://uec-images.ubuntu.com/precise/current
$ wget $EC2_UBUNTU_IMG_URL/precise-server-cloudimg-amd64.tar.gz
or::
$ wget $EC2_UBUNTU_IMG_URL/precise-server-cloudimg-i386.tar.gz
After downloading a Ubuntu cloud image the next step is to extract the image::
$ tar xvzf precise-server-cloudimg-amd64.tar.gz
Then resize it to 10GB::
$ e2fsck -f precise-server-cloudimg-amd64.img
$ resize2fs precise-server-cloudimg-amd64.img 10G
Next you need to mount the image::
$ mkdir /tmp/img-mount
$ mount precise-server-cloudimg-amd64.img /tmp/img-mount
$ mount -t proc none /tmp/img-mount/proc
$ mount -t sysfs none /tmp/img-mount/sys
$ mount -o bind /dev /tmp/img-mount/dev
$ mount -t devpts none /tmp/img-mount/dev/pts
$ mount -o rbind /var/run/dbus /tmp/img-mount/var/run/dbus
Copy /etc/resolv.conf and /etc/mtab to the image::
$ mkdir -p /tmp/img-mount/var/run/resolvconf
$ cp /etc/resolv.conf /tmp/img-mount/var/run/resolvconf/resolv.conf
$ grep -v rootfs /etc/mtab > /tmp/img-mount/etc/mtab
Next copy this script inside the image::
$ cp /path/to/scimage.py /tmp/img-mount/root/scimage.py
Finally chroot inside the image and run this script:
$ chroot /tmp/img-mount /bin/bash
$ cd $HOME
$ python scimage.py
"""
import os
import sys
import glob
import shutil
import fileinput
import subprocess
import multiprocessing
SRC_DIR = "/usr/local/src"
APT_SOURCES_FILE = "/etc/apt/sources.list"
BUILD_UTILS_PKGS = "build-essential devscripts debconf debconf-utils dpkg-dev "
BUILD_UTILS_PKGS += "python-dev python-setuptools python-pip python-nose rar "
BUILD_UTILS_PKGS += "python-distutils-extra gfortran unzip unace cdbs patch "
GRID_SCHEDULER_GIT = 'git://github.com/jtriley/gridscheduler.git'
CLOUDERA_ARCHIVE_KEY = 'http://archive.cloudera.com/debian/archive.key'
CLOUDERA_APT = 'http://archive.cloudera.com/debian squeeze-cdh3u5 contrib'
PPAS = ["ppa:staticfloat/julia-deps", "ppa:justin-t-riley/starcluster",
"ppa:staticfloat/julianightlies"]
STARCLUSTER_MOTD = """\
#!/bin/sh
cat<<"EOF"
_ _ _
__/\_____| |_ __ _ _ __ ___| |_ _ ___| |_ ___ _ __
\ / __| __/ _` | '__/ __| | | | / __| __/ _ \ '__|
/_ _\__ \ || (_| | | | (__| | |_| \__ \ || __/ |
\/ |___/\__\__,_|_| \___|_|\__,_|___/\__\___|_|
StarCluster Ubuntu 13.04 AMI
Software Tools for Academics and Researchers (STAR)
Homepage: http://star.mit.edu/cluster
Documentation: http://star.mit.edu/cluster/docs/latest
Code: https://github.com/jtriley/StarCluster
Mailing list: http://star.mit.edu/cluster/mailinglist.html
This AMI Contains:
* Open Grid Scheduler (OGS - formerly SGE) queuing system
* Condor workload management system
* OpenMPI compiled with Open Grid Scheduler support
* OpenBLAS - Highly optimized Basic Linear Algebra Routines
* NumPy/SciPy linked against OpenBlas
* Pandas - Data Analysis Library
* IPython 1.1.0 with parallel and notebook support
* Julia 0.3pre
* and more! (use 'dpkg -l' to show all installed packages)
Open Grid Scheduler/Condor cheat sheet:
* qstat/condor_q - show status of batch jobs
* qhost/condor_status- show status of hosts, queues, and jobs
* qsub/condor_submit - submit batch jobs (e.g. qsub -cwd ./job.sh)
* qdel/condor_rm - delete batch jobs (e.g. qdel 7)
* qconf - configure Open Grid Scheduler system
Current System Stats:
EOF
landscape-sysinfo | grep -iv 'graph this data'
"""
def run_command(cmd, ignore_failure=False, failure_callback=None,
get_output=False):
kwargs = {}
if get_output:
kwargs.update(dict(stdout=subprocess.PIPE, stderr=subprocess.PIPE))
p = subprocess.Popen(cmd, shell=True, **kwargs)
output = []
if get_output:
line = None
while line != '':
line = p.stdout.readline()
if line != '':
output.append(line)
print line,
for line in p.stderr.readlines():
if line != '':
output.append(line)
print line,
retval = p.wait()
if retval != 0:
errmsg = "command '%s' failed with status %d" % (cmd, retval)
if failure_callback:
ignore_failure = failure_callback(retval)
if not ignore_failure:
raise Exception(errmsg)
else:
sys.stderr.write(errmsg + '\n')
if get_output:
return retval, ''.join(output)
return retval
def apt_command(cmd):
dpkg_opts = "Dpkg::Options::='--force-confnew'"
cmd = "apt-get -o %s -y --force-yes %s" % (dpkg_opts, cmd)
cmd = "DEBIAN_FRONTEND='noninteractive' " + cmd
run_command(cmd)
def apt_install(pkgs):
apt_command('install %s' % pkgs)
def chdir(directory):
opts = glob.glob(directory)
isdirlist = [o for o in opts if os.path.isdir(o)]
if len(isdirlist) > 1:
raise Exception("more than one dir matches: %s" % directory)
os.chdir(isdirlist[0])
def _fix_atlas_rules(rules_file='debian/rules'):
for line in fileinput.input(rules_file, inplace=1):
if 'ATLAS=None' not in line:
print line,
def configure_apt_sources():
srcfile = open(APT_SOURCES_FILE)
contents = srcfile.readlines()
srcfile.close()
srclines = []
for line in contents:
if not line.strip() or line.startswith('#'):
continue
parts = line.split()
if parts[0] == 'deb':
parts[0] = 'deb-src'
srclines.append(' '.join(parts).strip())
with open(APT_SOURCES_FILE, 'w') as srcfile:
srcfile.write(''.join(contents))
srcfile.write('\n'.join(srclines) + '\n')
with open('/etc/apt/sources.list.d/cloudera-hadoop.list', 'w') as srcfile:
srcfile.write('deb %s\n' % CLOUDERA_APT)
srcfile.write('deb-src %s\n' % CLOUDERA_APT)
run_command('gpg --keyserver keyserver.ubuntu.com --recv-keys 0F932C9C')
run_command('curl -s %s | sudo apt-key add -' % CLOUDERA_ARCHIVE_KEY)
apt_install('debian-archive-keyring')
for ppa in PPAS:
run_command('add-apt-repository %s -y -s' % ppa)
def upgrade_packages():
apt_command('update')
apt_command('upgrade')
def install_build_utils():
"""docstring for configure_build"""
apt_install(BUILD_UTILS_PKGS)
def install_gridscheduler():
chdir(SRC_DIR)
apt_command('build-dep gridengine')
if os.path.isfile('gridscheduler-scbuild.tar.gz'):
run_command('tar xvzf gridscheduler-scbuild.tar.gz')
run_command('mv gridscheduler /opt/sge6-fresh')
return
run_command('git clone %s' % GRID_SCHEDULER_GIT)
sts, out = run_command('readlink -f `which java`', get_output=True)
java_home = out.strip().split('/jre')[0]
chdir(os.path.join(SRC_DIR, 'gridscheduler', 'source'))
run_command('git checkout -t -b develop origin/develop')
env = 'JAVA_HOME=%s' % java_home
run_command('%s ./aimk -only-depend' % env)
run_command('%s scripts/zerodepend' % env)
run_command('%s ./aimk depend' % env)
run_command('%s ./aimk -no-secure -no-gui-inst -man' % env)
sge_root = '/opt/sge6-fresh'
os.mkdir(sge_root)
env += ' SGE_ROOT=%s' % sge_root
run_command('%s scripts/distinst -all -local -noexit -y -- man' % env)
def install_condor():
chdir(SRC_DIR)
run_command("rm -f /var/lock")
#apt_install('condor=7.7.2-1')
#run_command('echo condor hold | dpkg --set-selections')
#run_command('ln -s /etc/condor/condor_config /etc/condor_config.local')
#run_command('mkdir /var/lib/condor/log')
#run_command('mkdir /var/lib/condor/run')
#run_command('chown -R condor:condor /var/lib/condor/log')
#run_command('chown -R condor:condor /var/lib/condor/run')
apt_install('condor')
def install_pydrmaa():
chdir(SRC_DIR)
run_command('pip install drmaa')
def install_atlas():
"""docstring for install_atlas"""
chdir(SRC_DIR)
apt_command('build-dep atlas')
if glob.glob("*atlas*.deb"):
run_command('dpkg -i *atlas*.deb')
return
apt_command('source atlas')
chdir('atlas-*')
run_command('fakeroot debian/rules custom')
run_command('dpkg -i ../*atlas*.deb')
def install_openblas():
"""docstring for install_openblas"""
chdir(SRC_DIR)
apt_command('build-dep libopenblas-dev')
if glob.glob("*openblas*.deb"):
run_command('dpkg -i *openblas*.deb')
else:
apt_command('source libopenblas-dev')
chdir('openblas-*')
rule_file = open('Makefile.rule', 'a')
# NO_AFFINITY=1 is required to utilize all cores on all non
# cluster-compute/GPU instance types due to the shared virtualization
# layer not supporting processor affinity properly. However, Cluster
# Compute/GPU instance types use a near-bare-metal hypervisor which
# *does* support processor affinity. From minimal testing it appears
# that there is a ~20% increase in performance when using affinity on
# cc1/cg1 types implying NO_AFFINITY=1 should *not* be set for cluster
# compute/GPU AMIs.
lines = ['DYNAMIC_ARCH=1', 'NUM_THREADS=64', 'NO_LAPACK=1',
'NO_AFFINITY=1']
rule_file.write('\n'.join(lines))
rule_file.close()
run_command('fakeroot debian/rules custom')
run_command('dpkg -i ../*openblas*.deb')
run_command('echo libopenblas-base hold | dpkg --set-selections')
run_command('echo libopenblas-dev hold | dpkg --set-selections')
run_command("ldconfig")
def install_python_packages():
install_pydrmaa()
install_numpy_scipy()
install_pandas()
install_ipython()
apt_command('build-dep python-imaging')
pkgs = "virtualenv pillow boto matplotlib django mpi4py ctypes Cython "
pkgs += "pudb supervisor "
run_command("pip install %s" % pkgs)
def install_numpy_scipy():
"""docstring for install_numpy"""
chdir(SRC_DIR)
apt_command('build-dep python-numpy')
apt_command('build-dep python-scipy')
run_command('pip install -d . numpy')
run_command('tar xvzf numpy*.tar.gz')
run_command("sed -i 's/return None #/pass #/' numpy*/numpy/core/setup.py")
run_command("cd numpy* && python setup.py install")
run_command('pip install scipy')
def install_pandas():
"""docstring for install_pandas"""
chdir(SRC_DIR)
apt_command('build-dep pandas')
run_command('pip install pandas')
def install_openmpi():
chdir(SRC_DIR)
apt_command('build-dep openmpi')
apt_install('blcr-util')
if glob.glob('*openmpi*.deb'):
run_command('dpkg -i *openmpi*.deb')
else:
apt_command('source openmpi')
chdir('openmpi*')
for line in fileinput.input('debian/rules', inplace=1):
print line,
if '--enable-heterogeneous' in line:
print ' --with-sge \\'
def _deb_failure_callback(retval):
if not glob.glob('../*openmpi*.deb'):
return False
return True
run_command('dch --local=\'+custom\' '
'"custom build on: `uname -s -r -v -m -p -i -o`"')
run_command('dpkg-buildpackage -rfakeroot -b',
failure_callback=_deb_failure_callback)
run_command('dpkg -i ../*openmpi*.deb')
sts, out = run_command('ompi_info | grep -i grid', get_output=True)
if 'gridengine' not in out:
raise Exception("failed to build OpenMPI with "
"Open Grid Scheduler support")
run_command('echo libopenmpi1.3 hold | dpkg --set-selections')
run_command('echo libopenmpi-dev hold | dpkg --set-selections')
run_command('echo libopenmpi-dbg hold | dpkg --set-selections')
run_command('echo openmpi-bin hold | dpkg --set-selections')
run_command('echo openmpi-checkpoint hold | dpkg --set-selections')
run_command('echo openmpi-common hold | dpkg --set-selections')
run_command('echo openmpi-doc hold | dpkg --set-selections')
run_command('ldconfig')
def install_hadoop():
chdir(SRC_DIR)
hadoop_pkgs = ['namenode', 'datanode', 'tasktracker', 'jobtracker',
'secondarynamenode']
pkgs = ['hadoop-0.20'] + ['hadoop-0.20-%s' % pkg for pkg in hadoop_pkgs]
apt_install(' '.join(pkgs))
run_command('easy_install dumbo')
def install_ipython():
chdir(SRC_DIR)
apt_install('libzmq-dev')
run_command('pip install ipython[parallel,notebook]')
# This is broken in IPy 1.1.0
#mjax_install = 'from IPython.external.mathjax import install_mathjax'
#mjax_install += '; install_mathjax()'
#run_command("python -c '%s'" % mjax_install)
def install_julia():
#chdir(SRC_DIR)
#apt_install('zlib1g-dev patchelf llvm-3.3-dev libsuitesparse-dev '
# 'libncurses5-dev libopenblas-dev liblapack-dev '
# 'libarpack2-dev libfftw3-dev libgmp-dev libpcre3-dev '
# 'libunwind8-dev libreadline-dev libdouble-conversion-dev '
# 'libopenlibm-dev librmath-dev libmpfr-dev')
#run_command('git clone git://github.com/JuliaLang/julia.git')
#buildopts = 'LLVM_CONFIG=llvm-config-3.3 VERBOSE=1 USE_BLAS64=0 '
#libs = ['LLVM', 'ZLIB', 'SUITESPARSE', 'ARPACK', 'BLAS', 'FFTW', 'LAPACK',
# 'GMP', 'MPFR', 'PCRE', 'LIBUNWIND', 'READLINE', 'GRISU',
# 'OPENLIBM', 'RMATH']
#buildopts += ' '.join(['USE_SYSTEM_%s=1' % lib for lib in libs])
#run_command('cd julia && make %s PREFIX=/usr install' % buildopts)
apt_install("julia")
def configure_motd():
for f in glob.glob('/etc/update-motd.d/*'):
os.unlink(f)
motd = open('/etc/update-motd.d/00-starcluster', 'w')
motd.write(STARCLUSTER_MOTD)
motd.close()
os.chmod(motd.name, 0755)
def configure_bash():
completion_line_found = False
for line in fileinput.input('/etc/bash.bashrc', inplace=1):
if 'bash_completion' in line and line.startswith('#'):
print line.replace('#', ''),
completion_line_found = True
elif completion_line_found:
print line.replace('#', ''),
completion_line_found = False
else:
print line,
aliasfile = open('/root/.bash_aliases', 'w')
aliasfile.write("alias ..='cd ..'\n")
aliasfile.close()
def setup_environ():
num_cpus = multiprocessing.cpu_count()
os.environ['MAKEFLAGS'] = '-j%d' % (num_cpus + 1)
os.environ['DEBIAN_FRONTEND'] = "noninteractive"
if os.path.isfile('/sbin/initctl') and not os.path.islink('/sbin/initctl'):
run_command('mv /sbin/initctl /sbin/initctl.bak')
run_command('ln -s /bin/true /sbin/initctl')
def install_nfs():
chdir(SRC_DIR)
run_command('initctl reload-configuration')
apt_install('nfs-kernel-server')
run_command('ln -s /etc/init.d/nfs-kernel-server /etc/init.d/nfs')
def install_default_packages():
# stop mysql for interactively asking for password
preseedf = '/tmp/mysql-preseed.txt'
mysqlpreseed = open(preseedf, 'w')
preseeds = """\
mysql-server mysql-server/root_password select
mysql-server mysql-server/root_password seen true
mysql-server mysql-server/root_password_again select
mysql-server mysql-server/root_password_again seen true
"""
mysqlpreseed.write(preseeds)
mysqlpreseed.close()
run_command('debconf-set-selections < %s' % mysqlpreseed.name)
run_command('rm %s' % mysqlpreseed.name)
pkgs = "git vim mercurial subversion cvs encfs keychain screen tmux zsh "
pkgs += "ksh csh tcsh ec2-api-tools ec2-ami-tools mysql-server "
pkgs += "mysql-client apache2 libapache2-mod-wsgi nginx sysv-rc-conf "
pkgs += "pssh emacs irssi htop vim-scripts mosh default-jdk mpich2 xvfb "
pkgs += "openmpi-bin libopenmpi-dev libopenblas-dev liblapack-dev julia"
apt_install(pkgs)
def configure_init():
scripts = ['nfs-kernel-server', 'hadoop', 'condor', 'apache', 'mysql',
'nginx']
for script in scripts:
run_command('find /etc/rc* -iname \*%s\* -delete' % script)
def cleanup():
run_command('rm -rf /run/resolvconf')
run_command('rm -f /etc/mtab')
run_command('rm -rf /root/*')
exclude = ['/root/.bashrc', '/root/.profile', '/root/.bash_aliases']
for dot in glob.glob("/root/.*"):
if dot not in exclude:
run_command('rm -rf %s' % dot)
for path in glob.glob('/usr/local/src/*'):
if os.path.isdir(path):
shutil.rmtree(path)
run_command('rm -f /var/cache/apt/archives/*.deb')
run_command('rm -f /var/cache/apt/archives/partial/*')
for f in glob.glob('/etc/profile.d'):
if 'byobu' in f:
run_command('rm -f %s' % f)
if os.path.islink('/sbin/initctl') and os.path.isfile('/sbin/initctl.bak'):
run_command('mv -f /sbin/initctl.bak /sbin/initctl')
def main():
"""docstring for main"""
if os.getuid() != 0:
sys.stderr.write('you must be root to run this script\n')
return
setup_environ()
configure_motd()
configure_bash()
configure_apt_sources()
upgrade_packages()
install_build_utils()
install_nfs()
install_default_packages()
install_python_packages()
# Only use these to build the packages locally
# These should normally be installed from the PPAs
#install_openblas()
#install_openmpi()
#install_julia()
install_gridscheduler()
install_condor()
install_hadoop()
configure_init()
cleanup()
if __name__ == '__main__':
main()
|
gpl-3.0
|
widdowquinn/pyani
|
tests/conftest.py
|
1
|
8808
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# (c) The University of Strathclude 2019-2020
# Author: Leighton Pritchard
#
# Contact:
# [email protected]
#
# Leighton Pritchard,
# Strathclyde Institute of Pharmaceutical and Biomedical Sciences
# The University of Strathclyde
# 161 Cathedral Street
# Glasgow
# G4 0RE
# Scotland,
# UK
#
# The MIT License
#
# (c) The University of Strathclude 2019-2020
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Pytest configuration file."""
import copy
import subprocess
from argparse import Namespace
from pathlib import Path
from typing import Dict, List, NamedTuple, Tuple
import pandas as pd
import pytest
from pyani import download
from pyani.download import ASMIDs, DLStatus, get_ncbi_esummary
from pyani.pyani_config import (
BLASTALL_DEFAULT,
BLASTN_DEFAULT,
NUCMER_DEFAULT,
FRAGSIZE,
)
from pyani.scripts import genbank_get_genomes_by_taxon
# Path to tests, contains tests and data subdirectories
# This conftest.py file should be found in the top directory of the tests
# module. The fixture data should be in a subdirectory named fixtures
TESTSPATH = Path(__file__).parents[0]
FIXTUREPATH = TESTSPATH / "fixtures"
@pytest.fixture
def blastall_available():
"""Returns True if blastall can be run, False otherwise."""
cmd = str(BLASTALL_DEFAULT)
# Can't use check=True, as blastall without arguments returns 1!
try:
result = subprocess.run(
cmd,
shell=False,
check=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
except OSError:
return False
return result.stdout[1:9] == b"blastall"
@pytest.fixture
def blastn_available():
"""Returns True if blastn can be run, False otherwise."""
cmd = [str(BLASTN_DEFAULT), "-version"]
try:
result = subprocess.run(
cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True
)
except OSError:
return False
return result.stdout[:6] == b"blastn"
@pytest.fixture
def dir_anib_in():
"""Input files for ANIb tests."""
return FIXTUREPATH / "anib"
@pytest.fixture
def dir_anim_in():
"""Input files for ANIm tests."""
return FIXTUREPATH / "anim"
@pytest.fixture
def dir_graphics_in():
"""Input files for graphics tests."""
return FIXTUREPATH / "graphics"
@pytest.fixture
def dir_seq():
"""Sequence files for tests."""
return FIXTUREPATH / "sequences"
@pytest.fixture
def dir_targets():
"""Target files for output comparisons."""
return FIXTUREPATH / "targets"
@pytest.fixture
def dir_tgt_fragments(dir_targets):
"""Target files for FASTA file fragmentation."""
return dir_targets / "fragments"
@pytest.fixture
def email_address():
"""Dummy email address."""
return "[email protected]"
@pytest.fixture
def fragment_length():
"""Fragment size for ANIb-related analyses."""
return FRAGSIZE
@pytest.fixture
def nucmer_available():
"""Test that nucmer is available."""
cmd = [str(NUCMER_DEFAULT), "--version"]
try:
result = subprocess.run(
cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True
)
except OSError:
return False
return result.stderr[:6] == b"nucmer"
@pytest.fixture
def path_file_two():
"""Path to two arbitrary filenames."""
return [Path(f"file{_:d}.fna") for _ in range(1, 3)]
@pytest.fixture
def path_file_four():
"""Path to four arbitrary filenames."""
return [Path(f"file{_:d}.fna") for _ in range(1, 5)]
@pytest.fixture
def path_fixtures_base():
"""Base path to fixture data folders."""
return FIXTUREPATH
@pytest.fixture
def path_fna(dir_seq):
"""Path to one .fna sequence file from dir_seq."""
fnapaths = [_ for _ in dir_seq.iterdir() if _.is_file() and _.suffix == ".fna"]
return fnapaths[0]
@pytest.fixture
def path_fna_two(dir_seq):
"""Paths to two .fna sequence file in dir_seq."""
fnapaths = [_ for _ in dir_seq.iterdir() if _.is_file() and _.suffix == ".fna"]
return fnapaths[:2]
@pytest.fixture
def path_fna_all(dir_seq):
"""Paths to all .fna sequence file in dir_seq."""
return [_ for _ in dir_seq.iterdir() if _.is_file() and _.suffix == ".fna"]
@pytest.fixture(autouse=True)
def skip_by_unavailable_executable(
request, blastall_available, blastn_available, nucmer_available
):
"""Skip test if executable is unavailable.
Use with @pytest.mark.skip_if_exe_missing("executable") decorator.
"""
if request.node.get_closest_marker("skip_if_exe_missing"):
exe_name = request.node.get_closest_marker("skip_if_exe_missing").args[0]
tests = {
"blastall": blastall_available,
"blastn": blastn_available,
"nucmer": nucmer_available,
}
try:
if not tests[exe_name]:
pytest.skip(f"Skipped as {exe_name} not available")
except KeyError: # Unknown executables are ignored
pytest.skip(f"Executable {exe_name} not recognised")
@pytest.fixture
def mock_single_genome_dl(monkeypatch):
"""Mocks remote database calls for single-genome downloads.
This masks calls to the download module, for safe testing.
"""
def mock_asmuids(*args, **kwargs):
"""Mock download.get_asm_uids()."""
return ASMIDs("txid218491[Organism:exp]", 1, ["32728"])
def mock_ncbi_esummary(*args, **kwargs):
"""Mock download.get_ncbi_esummary()."""
return (
{
"Taxid": "218491",
"SpeciesTaxid": "29471",
"AssemblyAccession": "GCF_000011605.1",
"AssemblyName": "ASM1160v1",
"SpeciesName": "Pectobacterium atrosepticum",
},
"GCF_000011605.1_ASM1160v1",
)
def mock_genome_hash(*args, **kwargs):
"""Mock download.retrieve_genome_and_hash()."""
return DLStatus(
"ftp://ftp.ncbi.nlm.nih.gov/dummy_genomic.fna.gz",
"ftp://ftp.ncbi.nlm.nih.gov/dummy/md5checksums.txt",
FIXTUREPATH
/ "single_genome_download"
/ "GCF_000011605.1_ASM1160v1_genomic.fna.gz",
FIXTUREPATH / "single_genome_download/GCF_000011605.1_ASM1160v1_hashes.txt",
False,
None,
)
monkeypatch.setattr(download, "get_asm_uids", mock_asmuids)
monkeypatch.setattr(download, "get_ncbi_esummary", mock_ncbi_esummary)
monkeypatch.setattr(download, "retrieve_genome_and_hash", mock_genome_hash)
@pytest.fixture
def mock_legacy_single_genome_dl(monkeypatch):
"""Mocks remote database calls for single-genome downloads.
This masks calls to functions in genbank_get_genomes_by_taxon, for safe testing.
This will be deprecated once the genbank_get_genomes_by_taxon.py script is
converted to use the pyani.download module.
"""
def mock_asmuids(*args, **kwargs):
"""Mock genbank_get_genomes_by_taxon.get_asm_uids()."""
return ["32728"]
def mock_ncbi_asm(*args, **kwargs):
"""Mock genbank_get_genomes_by_taxon.get_ncbi_asm()."""
return (
Path(
"tests/test_output/legacy_scripts/C_blochmannia_legacy/GCF_000011605.1_ASM1160v1_genomic.fna"
),
"8b0cab310cb638c977d453ff06eceb64\tGCF_000011605.1_ASM1160v1_genomic\tPectobacterium atrosepticum",
"8b0cab310cb638c977d453ff06eceb64\tGCF_000011605.1_ASM1160v1_genomic\tP. atrosepticum SCRI1043",
"GCF_000011605.1",
)
monkeypatch.setattr(genbank_get_genomes_by_taxon, "get_asm_uids", mock_asmuids)
monkeypatch.setattr(genbank_get_genomes_by_taxon, "get_ncbi_asm", mock_ncbi_asm)
|
mit
|
Neurita/boyle
|
scripts/convert_sav.py
|
1
|
2722
|
#!/usr/bin/env python
from __future__ import unicode_literals
import os
import baker
from path import path
from boyle.storage import (sav_to_pandas_rpy2,
sav_to_pandas_savreader)
from boyle.files.names import add_extension_if_needed
@baker.command(name='sav',
params={"inputfile": "Path to the .sav file to be transformed",
"outputfile": "Path to the output file",
"otype": """Output file type. Choices: 'csv', 'hdf',
'stata', 'json',
'pickle' 'excel',
'html'. Default: 'csv'""",
"method": """Which conversion method to use.
Choices: 'rpy2' to use Pandas Rpy2 wrapper
or 'savread' to use savReaderWriter"""},
shortopts={'inputfile': 'i', 'outputfile': 'o',
'method': 'm', 'otype': 't'})
def convert_sav(inputfile, outputfile=None, method='rpy2', otype='csv'):
""" Transforms the input .sav SPSS file into other format.
If you don't specify an outputfile, it will use the
inputfile and change its extension to .csv
"""
assert(os.path.isfile(inputfile))
assert(method=='rpy2' or method=='savread')
if method == 'rpy2':
df = sav_to_pandas_rpy2(inputfile)
elif method == 'savread':
df = sav_to_pandas_savreader(inputfile)
otype_exts = {'csv': '.csv',
'hdf': '.h5',
'stata': '.dta',
'json': '.json',
'pickle': '.pickle',
'excel': '.xls',
'html': '.html'}
if outputfile is None:
outputfile = inputfile.replace(path(inputfile).ext, '')
outputfile = add_extension_if_needed(outputfile, otype_exts[otype])
if otype == 'csv':
df.to_csv(outputfile)
elif otype == 'hdf':
df.to_hdf(outputfile, os.path.basename(outputfile))
elif otype == 'stata':
df.to_stata(outputfile)
elif otype == 'json':
df.to_json(outputfile)
elif otype == 'pickle':
df.to_pickle(outputfile)
elif otype == 'excel':
df.to_excel(outputfile)
elif otype == 'html':
df.to_html(outputfile)
else:
df.to_csv(outputfile)
if __name__ == '__main__':
baker.run()
# import os
# wd = '/home/alexandre/Dropbox/Documents/projects/santiago'
# f = 'datos_clinicos_140221.sav'
# outf = f.replace('.sav', '.csv')
# sav2csv(os.path.join(wd, f), os.path.join(wd, outf))
|
bsd-3-clause
|
brvnl/master
|
parser/Dataset.py
|
1
|
2927
|
import sys, logging, os.path
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.sys.path.insert(0,parentdir)
import pandas as pd
class BaseDataset(object):
def __init__(self, X=None, Y=None, test=0.2, featureSelection=None, fromFile=None, balance=False):
self.logger = logging.getLogger(self.__class__.__name__)
logging.basicConfig(format='%(asctime)s %(levelname)s* %(message)s', level=logging.INFO)
if (fromFile is not None):
hdf = pd.HDFStore(fromFile)
self.X = hdf['X']
self.Y = hdf['Y']
hdf.close()
else:
intersection = X.index.intersection(Y.index)
self.X = X.loc[intersection]
self.Y = Y.loc[intersection]
totalrecords = len(self.X.index)
self.logger.info("Using %d timestamps from the intersection of X(%d) and Y(%d)." %(totalrecords , len(X.index), len(Y.index)))
if (totalrecords < 2):
raise ValueError('Not enough valid records on the dataset.')
self.nRecordsTest = int(totalrecords * test)
self.nRecordsTrain = totalrecords - self.nRecordsTest
self.logger.info("Using %d rows for training and %d for testing." %(self.nRecordsTrain, self.nRecordsTest))
self.logger.info("Series starting at %s, ending at %s." \
%(self.Y.first('1D').index.strftime("%Y-%m-%d").item(), \
self.Y.last('1D').index.strftime("%Y-%m-%d").item()))
if (featureSelection is not None):
self.X = featureSelection.process(self.X)
def size(self):
return (self.nRecordsTest + self.nRecordsTrain)
def persist(self, path):
hdf = pd.HDFStore(path)
hdf['X'] = pd.DataFrame(self.X)
hdf['Y'] = pd.DataFrame(self.Y)
hdf.close()
def getStatistics(self):
train = self.getYTrain().value_counts(sort=False)
test = self.getYTest().value_counts(sort=False)
total = self.Y.value_counts(sort=False)
df = pd.DataFrame({"train": train,
"test": test,
"total": total})
return df
def getXCVTrainIndexes(self):
df_xtrain = self.getXTrain()
p = 0.25
t = len(df_xtrain)
n = int(t * p)
#return df_xtrain.head(n).index.values.astype(int)
return df_xtrain.head(n).index.values.to_datetime()
def getXCVTestIndexes(self):
df_xtrain = self.getXTrain()
p = 0.25
t = len(df_xtrain)
n = t - int(t * p)
return df_xtrain.tail(n).index.values.to_datetime()
def getXTrain(self):
return self.X.head(self.nRecordsTrain)
def getYTrain(self):
return self.Y.head(self.nRecordsTrain)
def getXTest(self):
return self.X.tail(self.nRecordsTest)
def getYTest(self):
return self.Y.tail(self.nRecordsTest)
|
gpl-3.0
|
olafhauk/mne-python
|
mne/evoked.py
|
3
|
49843
|
# -*- coding: utf-8 -*-
# Authors: Alexandre Gramfort <[email protected]>
# Matti Hämäläinen <[email protected]>
# Denis Engemann <[email protected]>
# Andrew Dykstra <[email protected]>
# Mads Jensen <[email protected]>
# Jona Sassenhagen <[email protected]>
#
# License: BSD (3-clause)
from copy import deepcopy
import numpy as np
from .baseline import rescale
from .channels.channels import (ContainsMixin, UpdateChannelsMixin,
SetChannelsMixin, InterpolationMixin)
from .channels.layout import _merge_ch_data, _pair_grad_sensors
from .defaults import _EXTRAPOLATE_DEFAULT, _BORDER_DEFAULT
from .filter import detrend, FilterMixin
from .utils import (check_fname, logger, verbose, _time_mask, warn, sizeof_fmt,
SizeMixin, copy_function_doc_to_method_doc, _validate_type,
fill_doc, _check_option, ShiftTimeMixin, _build_data_frame,
_check_pandas_installed, _check_pandas_index_arguments,
_convert_times, _scale_dataframe_data, _check_time_format)
from .viz import (plot_evoked, plot_evoked_topomap, plot_evoked_field,
plot_evoked_image, plot_evoked_topo)
from .viz.evoked import plot_evoked_white, plot_evoked_joint
from .viz.topomap import _topomap_animation
from .io.constants import FIFF
from .io.open import fiff_open
from .io.tag import read_tag
from .io.tree import dir_tree_find
from .io.pick import pick_types, _picks_to_idx, _FNIRS_CH_TYPES_SPLIT
from .io.meas_info import read_meas_info, write_meas_info
from .io.proj import ProjMixin
from .io.write import (start_file, start_block, end_file, end_block,
write_int, write_string, write_float_matrix,
write_id, write_float, write_complex_float_matrix)
from .io.base import TimeMixin, _check_maxshield
_aspect_dict = {
'average': FIFF.FIFFV_ASPECT_AVERAGE,
'standard_error': FIFF.FIFFV_ASPECT_STD_ERR,
'single_epoch': FIFF.FIFFV_ASPECT_SINGLE,
'partial_average': FIFF.FIFFV_ASPECT_SUBAVERAGE,
'alternating_subaverage': FIFF.FIFFV_ASPECT_ALTAVERAGE,
'sample_cut_out_by_graph': FIFF.FIFFV_ASPECT_SAMPLE,
'power_density_spectrum': FIFF.FIFFV_ASPECT_POWER_DENSITY,
'dipole_amplitude_cuvre': FIFF.FIFFV_ASPECT_DIPOLE_WAVE,
'squid_modulation_lower_bound': FIFF.FIFFV_ASPECT_IFII_LOW,
'squid_modulation_upper_bound': FIFF.FIFFV_ASPECT_IFII_HIGH,
'squid_gate_setting': FIFF.FIFFV_ASPECT_GATE,
}
_aspect_rev = {val: key for key, val in _aspect_dict.items()}
@fill_doc
class Evoked(ProjMixin, ContainsMixin, UpdateChannelsMixin, SetChannelsMixin,
InterpolationMixin, FilterMixin, TimeMixin, SizeMixin,
ShiftTimeMixin):
"""Evoked data.
Parameters
----------
fname : str
Name of evoked/average FIF file to load.
If None no data is loaded.
condition : int, or str
Dataset ID number (int) or comment/name (str). Optional if there is
only one data set in file.
proj : bool, optional
Apply SSP projection vectors.
kind : str
Either 'average' or 'standard_error'. The type of data to read.
Only used if 'condition' is a str.
allow_maxshield : bool | str (default False)
If True, allow loading of data that has been recorded with internal
active compensation (MaxShield). Data recorded with MaxShield should
generally not be loaded directly, but should first be processed using
SSS/tSSS to remove the compensation signals that may also affect brain
activity. Can also be "yes" to load without eliciting a warning.
%(verbose)s
Attributes
----------
info : dict
Measurement info.
ch_names : list of str
List of channels' names.
nave : int
Number of averaged epochs.
kind : str
Type of data, either average or standard_error.
comment : str
Comment on dataset. Can be the condition.
data : array of shape (n_channels, n_times)
Evoked response.
first : int
First time sample.
last : int
Last time sample.
tmin : float
The first time point in seconds.
tmax : float
The last time point in seconds.
times : array
Time vector in seconds. Goes from ``tmin`` to ``tmax``. Time interval
between consecutive time samples is equal to the inverse of the
sampling frequency.
%(verbose)s
Notes
-----
Evoked objects contain a single condition only.
"""
@verbose
def __init__(self, fname, condition=None, proj=True,
kind='average', allow_maxshield=False,
verbose=None): # noqa: D102
_validate_type(proj, bool, "'proj'")
# Read the requested data
self.info, self.nave, self._aspect_kind, self.comment, self.times, \
self.data = _read_evoked(fname, condition, kind, allow_maxshield)
self._update_first_last()
self.verbose = verbose
self.preload = True
# project and baseline correct
if proj:
self.apply_proj()
@property
def kind(self):
"""The data kind."""
return _aspect_rev[self._aspect_kind]
@kind.setter
def kind(self, kind):
_check_option('kind', kind, list(_aspect_dict.keys()))
self._aspect_kind = _aspect_dict[kind]
@property
def data(self):
"""The data matrix."""
return self._data
@data.setter
def data(self, data):
"""Set the data matrix."""
self._data = data
@verbose
def apply_baseline(self, baseline=(None, 0), *, verbose=None):
"""Baseline correct evoked data.
Parameters
----------
%(baseline_evoked)s
Defaults to ``(None, 0)``, i.e. beginning of the the data until
time point zero.
%(verbose_meth)s
Returns
-------
evoked : instance of Evoked
The baseline-corrected Evoked object.
Notes
-----
Baseline correction can be done multiple times.
.. versionadded:: 0.13.0
"""
self.data = rescale(self.data, self.times, baseline, copy=False)
return self
def save(self, fname):
"""Save dataset to file.
Parameters
----------
fname : str
The name of the file, which should end with -ave.fif or
-ave.fif.gz.
Notes
-----
To write multiple conditions into a single file, use
:func:`mne.write_evokeds`.
"""
write_evokeds(fname, self)
def __repr__(self): # noqa: D105
s = "'%s' (%s, N=%s)" % (self.comment, self.kind, self.nave)
s += ", [%0.5g, %0.5g] sec" % (self.times[0], self.times[-1])
s += ", %s ch" % self.data.shape[0]
s += ", ~%s" % (sizeof_fmt(self._size),)
return "<Evoked | %s>" % s
@property
def ch_names(self):
"""Channel names."""
return self.info['ch_names']
@property
def tmin(self):
"""First time point.
.. versionadded:: 0.21
"""
return self.times[0]
@property
def tmax(self):
"""Last time point.
.. versionadded:: 0.21
"""
return self.times[-1]
@fill_doc
def crop(self, tmin=None, tmax=None, include_tmax=True, verbose=None):
"""Crop data to a given time interval.
Parameters
----------
tmin : float | None
Start time of selection in seconds.
tmax : float | None
End time of selection in seconds.
%(include_tmax)s
%(verbose_meth)s
Returns
-------
evoked : instance of Evoked
The cropped Evoked object, modified in-place.
Notes
-----
%(notes_tmax_included_by_default)s
"""
mask = _time_mask(self.times, tmin, tmax, sfreq=self.info['sfreq'],
include_tmax=include_tmax)
self.times = self.times[mask]
self._update_first_last()
self.data = self.data[:, mask]
return self
@verbose
def decimate(self, decim, offset=0, verbose=None):
"""Decimate the evoked data.
Parameters
----------
%(decim)s
%(decim_offset)s
%(verbose_meth)s
Returns
-------
evoked : instance of Evoked
The decimated Evoked object.
See Also
--------
Epochs.decimate
Epochs.resample
mne.io.Raw.resample
Notes
-----
%(decim_notes)s
.. versionadded:: 0.13.0
"""
decim, offset, new_sfreq = _check_decim(self.info, decim, offset)
start_idx = int(round(self.times[0] * (self.info['sfreq'] * decim)))
i_start = start_idx % decim + offset
decim_slice = slice(i_start, None, decim)
self.info['sfreq'] = new_sfreq
self.data = self.data[:, decim_slice].copy()
self.times = self.times[decim_slice].copy()
self._update_first_last()
return self
@copy_function_doc_to_method_doc(plot_evoked)
def plot(self, picks=None, exclude='bads', unit=True, show=True, ylim=None,
xlim='tight', proj=False, hline=None, units=None, scalings=None,
titles=None, axes=None, gfp=False, window_title=None,
spatial_colors=False, zorder='unsorted', selectable=True,
noise_cov=None, time_unit='s', sphere=None, verbose=None):
return plot_evoked(
self, picks=picks, exclude=exclude, unit=unit, show=show,
ylim=ylim, proj=proj, xlim=xlim, hline=hline, units=units,
scalings=scalings, titles=titles, axes=axes, gfp=gfp,
window_title=window_title, spatial_colors=spatial_colors,
zorder=zorder, selectable=selectable, noise_cov=noise_cov,
time_unit=time_unit, sphere=sphere, verbose=verbose)
@copy_function_doc_to_method_doc(plot_evoked_image)
def plot_image(self, picks=None, exclude='bads', unit=True, show=True,
clim=None, xlim='tight', proj=False, units=None,
scalings=None, titles=None, axes=None, cmap='RdBu_r',
colorbar=True, mask=None, mask_style=None,
mask_cmap='Greys', mask_alpha=.25, time_unit='s',
show_names=None, group_by=None, sphere=None):
return plot_evoked_image(
self, picks=picks, exclude=exclude, unit=unit, show=show,
clim=clim, xlim=xlim, proj=proj, units=units, scalings=scalings,
titles=titles, axes=axes, cmap=cmap, colorbar=colorbar, mask=mask,
mask_style=mask_style, mask_cmap=mask_cmap, mask_alpha=mask_alpha,
time_unit=time_unit, show_names=show_names, group_by=group_by,
sphere=sphere)
@copy_function_doc_to_method_doc(plot_evoked_topo)
def plot_topo(self, layout=None, layout_scale=0.945, color=None,
border='none', ylim=None, scalings=None, title=None,
proj=False, vline=[0.0], fig_background=None,
merge_grads=False, legend=True, axes=None,
background_color='w', noise_cov=None, show=True):
"""
Notes
-----
.. versionadded:: 0.10.0
"""
return plot_evoked_topo(
self, layout=layout, layout_scale=layout_scale, color=color,
border=border, ylim=ylim, scalings=scalings, title=title,
proj=proj, vline=vline, fig_background=fig_background,
merge_grads=merge_grads, legend=legend, axes=axes,
background_color=background_color, noise_cov=noise_cov, show=show)
@copy_function_doc_to_method_doc(plot_evoked_topomap)
def plot_topomap(self, times="auto", ch_type=None, vmin=None,
vmax=None, cmap=None, sensors=True, colorbar=True,
scalings=None, units=None, res=64,
size=1, cbar_fmt="%3.1f",
time_unit='s', time_format=None,
proj=False, show=True, show_names=False, title=None,
mask=None, mask_params=None, outlines='head',
contours=6, image_interp='bilinear', average=None,
axes=None, extrapolate=_EXTRAPOLATE_DEFAULT, sphere=None,
border=_BORDER_DEFAULT, nrows=1, ncols='auto'):
return plot_evoked_topomap(
self, times=times, ch_type=ch_type, vmin=vmin,
vmax=vmax, cmap=cmap, sensors=sensors, colorbar=colorbar,
scalings=scalings, units=units, res=res,
size=size, cbar_fmt=cbar_fmt, time_unit=time_unit,
time_format=time_format, proj=proj, show=show,
show_names=show_names, title=title, mask=mask,
mask_params=mask_params, outlines=outlines, contours=contours,
image_interp=image_interp, average=average,
axes=axes, extrapolate=extrapolate, sphere=sphere, border=border,
nrows=nrows, ncols=ncols)
@copy_function_doc_to_method_doc(plot_evoked_field)
def plot_field(self, surf_maps, time=None, time_label='t = %0.0f ms',
n_jobs=1, fig=None, vmax=None, n_contours=21, verbose=None):
return plot_evoked_field(self, surf_maps, time=time,
time_label=time_label, n_jobs=n_jobs,
fig=fig, vmax=vmax, n_contours=n_contours,
verbose=verbose)
@copy_function_doc_to_method_doc(plot_evoked_white)
def plot_white(self, noise_cov, show=True, rank=None, time_unit='s',
sphere=None, axes=None, verbose=None):
return plot_evoked_white(
self, noise_cov=noise_cov, rank=rank, show=show,
time_unit=time_unit, sphere=sphere, axes=axes, verbose=verbose)
@copy_function_doc_to_method_doc(plot_evoked_joint)
def plot_joint(self, times="peaks", title='', picks=None,
exclude='bads', show=True, ts_args=None,
topomap_args=None):
return plot_evoked_joint(self, times=times, title=title, picks=picks,
exclude=exclude, show=show, ts_args=ts_args,
topomap_args=topomap_args)
@fill_doc
def animate_topomap(self, ch_type=None, times=None, frame_rate=None,
butterfly=False, blit=True, show=True, time_unit='s',
sphere=None, *, extrapolate=_EXTRAPOLATE_DEFAULT,
verbose=None):
"""Make animation of evoked data as topomap timeseries.
The animation can be paused/resumed with left mouse button.
Left and right arrow keys can be used to move backward or forward
in time.
Parameters
----------
ch_type : str | None
Channel type to plot. Accepted data types: 'mag', 'grad', 'eeg',
'hbo', 'hbr', 'fnirs_cw_amplitude',
'fnirs_fd_ac_amplitude', 'fnirs_fd_phase', and 'fnirs_od'.
If None, first available channel type from the above list is used.
Defaults to None.
times : array of float | None
The time points to plot. If None, 10 evenly spaced samples are
calculated over the evoked time series. Defaults to None.
frame_rate : int | None
Frame rate for the animation in Hz. If None,
frame rate = sfreq / 10. Defaults to None.
butterfly : bool
Whether to plot the data as butterfly plot under the topomap.
Defaults to False.
blit : bool
Whether to use blit to optimize drawing. In general, it is
recommended to use blit in combination with ``show=True``. If you
intend to save the animation it is better to disable blit.
Defaults to True.
show : bool
Whether to show the animation. Defaults to True.
time_unit : str
The units for the time axis, can be "ms" (default in 0.16)
or "s" (will become the default in 0.17).
.. versionadded:: 0.16
%(topomap_sphere_auto)s
%(topomap_extrapolate)s
.. versionadded:: 0.22
%(verbose_meth)s
Returns
-------
fig : instance of matplotlib.figure.Figure
The figure.
anim : instance of matplotlib.animation.FuncAnimation
Animation of the topomap.
Notes
-----
.. versionadded:: 0.12.0
"""
return _topomap_animation(
self, ch_type=ch_type, times=times, frame_rate=frame_rate,
butterfly=butterfly, blit=blit, show=show, time_unit=time_unit,
sphere=sphere, extrapolate=extrapolate, verbose=verbose)
def as_type(self, ch_type='grad', mode='fast'):
"""Compute virtual evoked using interpolated fields.
.. Warning:: Using virtual evoked to compute inverse can yield
unexpected results. The virtual channels have ``'_v'`` appended
at the end of the names to emphasize that the data contained in
them are interpolated.
Parameters
----------
ch_type : str
The destination channel type. It can be 'mag' or 'grad'.
mode : str
Either ``'accurate'`` or ``'fast'``, determines the quality of the
Legendre polynomial expansion used. ``'fast'`` should be sufficient
for most applications.
Returns
-------
evoked : instance of mne.Evoked
The transformed evoked object containing only virtual channels.
Notes
-----
This method returns a copy and does not modify the data it
operates on. It also returns an EvokedArray instance.
.. versionadded:: 0.9.0
"""
from .forward import _as_meg_type_inst
return _as_meg_type_inst(self, ch_type=ch_type, mode=mode)
@fill_doc
def detrend(self, order=1, picks=None):
"""Detrend data.
This function operates in-place.
Parameters
----------
order : int
Either 0 or 1, the order of the detrending. 0 is a constant
(DC) detrend, 1 is a linear detrend.
%(picks_good_data)s
Returns
-------
evoked : instance of Evoked
The detrended evoked object.
"""
picks = _picks_to_idx(self.info, picks)
self.data[picks] = detrend(self.data[picks], order, axis=-1)
return self
def copy(self):
"""Copy the instance of evoked.
Returns
-------
evoked : instance of Evoked
A copy of the object.
"""
evoked = deepcopy(self)
return evoked
def __neg__(self):
"""Negate channel responses.
Returns
-------
evoked_neg : instance of Evoked
The Evoked instance with channel data negated and '-'
prepended to the comment.
"""
out = self.copy()
out.data *= -1
out.comment = '-' + (out.comment or 'unknown')
return out
def get_peak(self, ch_type=None, tmin=None, tmax=None,
mode='abs', time_as_index=False, merge_grads=False,
return_amplitude=False):
"""Get location and latency of peak amplitude.
Parameters
----------
ch_type : str | None
The channel type to use. Defaults to None. If more than one sensor
Type is present in the data the channel type has to be explicitly
set.
tmin : float | None
The minimum point in time to be considered for peak getting.
If None (default), the beginning of the data is used.
tmax : float | None
The maximum point in time to be considered for peak getting.
If None (default), the end of the data is used.
mode : {'pos', 'neg', 'abs'}
How to deal with the sign of the data. If 'pos' only positive
values will be considered. If 'neg' only negative values will
be considered. If 'abs' absolute values will be considered.
Defaults to 'abs'.
time_as_index : bool
Whether to return the time index instead of the latency in seconds.
merge_grads : bool
If True, compute peak from merged gradiometer data.
return_amplitude : bool
If True, return also the amplitude at the maximum response.
.. versionadded:: 0.16
Returns
-------
ch_name : str
The channel exhibiting the maximum response.
latency : float | int
The time point of the maximum response, either latency in seconds
or index.
amplitude : float
The amplitude of the maximum response. Only returned if
return_amplitude is True.
.. versionadded:: 0.16
""" # noqa: E501
supported = ('mag', 'grad', 'eeg', 'seeg', 'ecog', 'misc',
'None') + _FNIRS_CH_TYPES_SPLIT
types_used = self.get_channel_types(unique=True, only_data_chs=True)
_check_option('ch_type', str(ch_type), supported)
if ch_type is not None and ch_type not in types_used:
raise ValueError('Channel type `{ch_type}` not found in this '
'evoked object.'.format(ch_type=ch_type))
elif len(types_used) > 1 and ch_type is None:
raise RuntimeError('More than one sensor type found. `ch_type` '
'must not be `None`, pass a sensor type '
'value instead')
if merge_grads:
if ch_type != 'grad':
raise ValueError('Channel type must be grad for merge_grads')
elif mode == 'neg':
raise ValueError('Negative mode (mode=neg) does not make '
'sense with merge_grads=True')
meg = eeg = misc = seeg = ecog = fnirs = False
picks = None
if ch_type in ('mag', 'grad'):
meg = ch_type
elif ch_type == 'eeg':
eeg = True
elif ch_type == 'misc':
misc = True
elif ch_type == 'seeg':
seeg = True
elif ch_type == 'ecog':
ecog = True
elif ch_type in _FNIRS_CH_TYPES_SPLIT:
fnirs = ch_type
if ch_type is not None:
if merge_grads:
picks = _pair_grad_sensors(self.info, topomap_coords=False)
else:
picks = pick_types(self.info, meg=meg, eeg=eeg, misc=misc,
seeg=seeg, ecog=ecog, ref_meg=False,
fnirs=fnirs)
data = self.data
ch_names = self.ch_names
if picks is not None:
data = data[picks]
ch_names = [ch_names[k] for k in picks]
if merge_grads:
data, _ = _merge_ch_data(data, ch_type, [])
ch_names = [ch_name[:-1] + 'X' for ch_name in ch_names[::2]]
ch_idx, time_idx, max_amp = _get_peak(data, self.times, tmin,
tmax, mode)
out = (ch_names[ch_idx], time_idx if time_as_index else
self.times[time_idx])
if return_amplitude:
out += (max_amp,)
return out
@fill_doc
def to_data_frame(self, picks=None, index=None,
scalings=None, copy=True, long_format=False,
time_format='ms'):
"""Export data in tabular structure as a pandas DataFrame.
Channels are converted to columns in the DataFrame. By default,
an additional column "time" is added, unless ``index='time'``
(in which case time values form the DataFrame's index).
Parameters
----------
%(picks_all)s
%(df_index_evk)s
Defaults to ``None``.
%(df_scalings)s
%(df_copy)s
%(df_longform_raw)s
%(df_time_format)s
.. versionadded:: 0.20
Returns
-------
%(df_return)s
"""
# check pandas once here, instead of in each private utils function
pd = _check_pandas_installed() # noqa
# arg checking
valid_index_args = ['time']
valid_time_formats = ['ms', 'timedelta']
index = _check_pandas_index_arguments(index, valid_index_args)
time_format = _check_time_format(time_format, valid_time_formats)
# get data
picks = _picks_to_idx(self.info, picks, 'all', exclude=())
data = self.data[picks, :]
times = self.times
data = data.T
if copy:
data = data.copy()
data = _scale_dataframe_data(self, data, picks, scalings)
# prepare extra columns / multiindex
mindex = list()
times = _convert_times(self, times, time_format)
mindex.append(('time', times))
# build DataFrame
df = _build_data_frame(self, data, picks, long_format, mindex, index,
default_index=['time'])
return df
def _check_decim(info, decim, offset):
"""Check decimation parameters."""
if decim < 1 or decim != int(decim):
raise ValueError('decim must be an integer > 0')
decim = int(decim)
new_sfreq = info['sfreq'] / float(decim)
lowpass = info['lowpass']
if decim > 1 and lowpass is None:
warn('The measurement information indicates data is not low-pass '
'filtered. The decim=%i parameter will result in a sampling '
'frequency of %g Hz, which can cause aliasing artifacts.'
% (decim, new_sfreq))
elif decim > 1 and new_sfreq < 3 * lowpass:
warn('The measurement information indicates a low-pass frequency '
'of %g Hz. The decim=%i parameter will result in a sampling '
'frequency of %g Hz, which can cause aliasing artifacts.'
% (lowpass, decim, new_sfreq)) # > 50% nyquist lim
offset = int(offset)
if not 0 <= offset < decim:
raise ValueError('decim must be at least 0 and less than %s, got '
'%s' % (decim, offset))
return decim, offset, new_sfreq
@fill_doc
class EvokedArray(Evoked):
"""Evoked object from numpy array.
Parameters
----------
data : array of shape (n_channels, n_times)
The channels' evoked response. See notes for proper units of measure.
info : instance of Info
Info dictionary. Consider using ``create_info`` to populate
this structure.
tmin : float
Start time before event. Defaults to 0.
comment : str
Comment on dataset. Can be the condition. Defaults to ''.
nave : int
Number of averaged epochs. Defaults to 1.
kind : str
Type of data, either average or standard_error. Defaults to 'average'.
%(verbose)s
See Also
--------
EpochsArray, io.RawArray, create_info
Notes
-----
Proper units of measure:
* V: eeg, eog, seeg, emg, ecg, bio, ecog
* T: mag
* T/m: grad
* M: hbo, hbr
* Am: dipole
* AU: misc
"""
@verbose
def __init__(self, data, info, tmin=0., comment='', nave=1, kind='average',
verbose=None): # noqa: D102
dtype = np.complex128 if np.iscomplexobj(data) else np.float64
data = np.asanyarray(data, dtype=dtype)
if data.ndim != 2:
raise ValueError('Data must be a 2D array of shape (n_channels, '
'n_samples), got shape %s' % (data.shape,))
if len(info['ch_names']) != np.shape(data)[0]:
raise ValueError('Info (%s) and data (%s) must have same number '
'of channels.' % (len(info['ch_names']),
np.shape(data)[0]))
self.data = data
self.first = int(round(tmin * info['sfreq']))
self.last = self.first + np.shape(data)[-1] - 1
self.times = np.arange(self.first, self.last + 1,
dtype=np.float64) / info['sfreq']
self.info = info.copy() # do not modify original info
self.nave = nave
self.kind = kind
self.comment = comment
self.picks = None
self.verbose = verbose
self.preload = True
self._projector = None
_validate_type(self.kind, "str", "kind")
if self.kind not in _aspect_dict:
raise ValueError('unknown kind "%s", should be "average" or '
'"standard_error"' % (self.kind,))
self._aspect_kind = _aspect_dict[self.kind]
def _get_entries(fid, evoked_node, allow_maxshield=False):
"""Get all evoked entries."""
comments = list()
aspect_kinds = list()
for ev in evoked_node:
for k in range(ev['nent']):
my_kind = ev['directory'][k].kind
pos = ev['directory'][k].pos
if my_kind == FIFF.FIFF_COMMENT:
tag = read_tag(fid, pos)
comments.append(tag.data)
my_aspect = _get_aspect(ev, allow_maxshield)[0]
for k in range(my_aspect['nent']):
my_kind = my_aspect['directory'][k].kind
pos = my_aspect['directory'][k].pos
if my_kind == FIFF.FIFF_ASPECT_KIND:
tag = read_tag(fid, pos)
aspect_kinds.append(int(tag.data))
comments = np.atleast_1d(comments)
aspect_kinds = np.atleast_1d(aspect_kinds)
if len(comments) != len(aspect_kinds) or len(comments) == 0:
fid.close()
raise ValueError('Dataset names in FIF file '
'could not be found.')
t = [_aspect_rev[a] for a in aspect_kinds]
t = ['"' + c + '" (' + tt + ')' for tt, c in zip(t, comments)]
t = '\n'.join(t)
return comments, aspect_kinds, t
def _get_aspect(evoked, allow_maxshield):
"""Get Evoked data aspect."""
is_maxshield = False
aspect = dir_tree_find(evoked, FIFF.FIFFB_ASPECT)
if len(aspect) == 0:
_check_maxshield(allow_maxshield)
aspect = dir_tree_find(evoked, FIFF.FIFFB_IAS_ASPECT)
is_maxshield = True
if len(aspect) > 1:
logger.info('Multiple data aspects found. Taking first one.')
return aspect[0], is_maxshield
def _get_evoked_node(fname):
"""Get info in evoked file."""
f, tree, _ = fiff_open(fname)
with f as fid:
_, meas = read_meas_info(fid, tree, verbose=False)
evoked_node = dir_tree_find(meas, FIFF.FIFFB_EVOKED)
return evoked_node
def _check_evokeds_ch_names_times(all_evoked):
evoked = all_evoked[0]
ch_names = evoked.ch_names
for ii, ev in enumerate(all_evoked[1:]):
if ev.ch_names != ch_names:
if set(ev.ch_names) != set(ch_names):
raise ValueError(
"%s and %s do not contain the same channels." % (evoked,
ev))
else:
warn("Order of channels differs, reordering channels ...")
ev = ev.copy()
ev.reorder_channels(ch_names)
all_evoked[ii + 1] = ev
if not np.max(np.abs(ev.times - evoked.times)) < 1e-7:
raise ValueError("%s and %s do not contain the same time instants"
% (evoked, ev))
return all_evoked
def combine_evoked(all_evoked, weights):
"""Merge evoked data by weighted addition or subtraction.
Each `~mne.Evoked` in ``all_evoked`` should have the same channels and the
same time instants. Subtraction can be performed by passing
``weights=[1, -1]``.
.. Warning::
Other than cases like simple subtraction mentioned above (where all
weights are -1 or 1), if you provide numeric weights instead of using
``'equal'`` or ``'nave'``, the resulting `~mne.Evoked` object's
``.nave`` attribute (which is used to scale noise covariance when
applying the inverse operator) may not be suitable for inverse imaging.
Parameters
----------
all_evoked : list of Evoked
The evoked datasets.
weights : list of float | 'equal' | 'nave'
The weights to apply to the data of each evoked instance, or a string
describing the weighting strategy to apply: ``'nave'`` computes
sum-to-one weights proportional to each object's ``nave`` attribute;
``'equal'`` weights each `~mne.Evoked` by ``1 / len(all_evoked)``.
Returns
-------
evoked : Evoked
The new evoked data.
Notes
-----
.. versionadded:: 0.9.0
"""
naves = np.array([evk.nave for evk in all_evoked], float)
if isinstance(weights, str):
_check_option('weights', weights, ['nave', 'equal'])
if weights == 'nave':
weights = naves / naves.sum()
else:
weights = np.ones_like(naves) / len(naves)
else:
weights = np.array(weights, float)
if weights.ndim != 1 or weights.size != len(all_evoked):
raise ValueError('weights must be the same size as all_evoked')
# cf. https://en.wikipedia.org/wiki/Weighted_arithmetic_mean, section on
# "weighted sample variance". The variance of a weighted sample mean is:
#
# σ² = w₁² σ₁² + w₂² σ₂² + ... + wₙ² σₙ²
#
# We estimate the variance of each evoked instance as 1 / nave to get:
#
# σ² = w₁² / nave₁ + w₂² / nave₂ + ... + wₙ² / naveₙ
#
# And our resulting nave is the reciprocal of this:
new_nave = 1. / np.sum(weights ** 2 / naves)
# This general formula is equivalent to formulae in Matti's manual
# (pp 128-129), where:
# new_nave = sum(naves) when weights='nave' and
# new_nave = 1. / sum(1. / naves) when weights are all 1.
all_evoked = _check_evokeds_ch_names_times(all_evoked)
evoked = all_evoked[0].copy()
# use union of bad channels
bads = list(set(b for e in all_evoked for b in e.info['bads']))
evoked.info['bads'] = bads
evoked.data = sum(w * e.data for w, e in zip(weights, all_evoked))
evoked.nave = new_nave
evoked.comment = ' + '.join(f'{w:0.3f} × {e.comment or "unknown"}'
for w, e in zip(weights, all_evoked))
return evoked
@verbose
def read_evokeds(fname, condition=None, baseline=None, kind='average',
proj=True, allow_maxshield=False, verbose=None):
"""Read evoked dataset(s).
Parameters
----------
fname : str
The file name, which should end with -ave.fif or -ave.fif.gz.
condition : int or str | list of int or str | None
The index or list of indices of the evoked dataset to read. FIF files
can contain multiple datasets. If None, all datasets are returned as a
list.
%(baseline_evoked)s
Defaults to ``None``, i.e. no baseline correction.
kind : str
Either 'average' or 'standard_error', the type of data to read.
proj : bool
If False, available projectors won't be applied to the data.
allow_maxshield : bool | str (default False)
If True, allow loading of data that has been recorded with internal
active compensation (MaxShield). Data recorded with MaxShield should
generally not be loaded directly, but should first be processed using
SSS/tSSS to remove the compensation signals that may also affect brain
activity. Can also be "yes" to load without eliciting a warning.
%(verbose)s
Returns
-------
evoked : Evoked or list of Evoked
The evoked dataset(s); one Evoked if condition is int or str,
or list of Evoked if condition is None or list.
See Also
--------
write_evokeds
"""
check_fname(fname, 'evoked', ('-ave.fif', '-ave.fif.gz',
'_ave.fif', '_ave.fif.gz'))
logger.info('Reading %s ...' % fname)
return_list = True
if condition is None:
evoked_node = _get_evoked_node(fname)
condition = range(len(evoked_node))
elif not isinstance(condition, list):
condition = [condition]
return_list = False
out = [Evoked(fname, c, kind=kind, proj=proj,
allow_maxshield=allow_maxshield,
verbose=verbose).apply_baseline(baseline)
for c in condition]
return out if return_list else out[0]
def _read_evoked(fname, condition=None, kind='average', allow_maxshield=False):
"""Read evoked data from a FIF file."""
if fname is None:
raise ValueError('No evoked filename specified')
f, tree, _ = fiff_open(fname)
with f as fid:
# Read the measurement info
info, meas = read_meas_info(fid, tree, clean_bads=True)
# Locate the data of interest
processed = dir_tree_find(meas, FIFF.FIFFB_PROCESSED_DATA)
if len(processed) == 0:
raise ValueError('Could not find processed data')
evoked_node = dir_tree_find(meas, FIFF.FIFFB_EVOKED)
if len(evoked_node) == 0:
raise ValueError('Could not find evoked data')
# find string-based entry
if isinstance(condition, str):
if kind not in _aspect_dict.keys():
raise ValueError('kind must be "average" or '
'"standard_error"')
comments, aspect_kinds, t = _get_entries(fid, evoked_node,
allow_maxshield)
goods = (np.in1d(comments, [condition]) &
np.in1d(aspect_kinds, [_aspect_dict[kind]]))
found_cond = np.where(goods)[0]
if len(found_cond) != 1:
raise ValueError('condition "%s" (%s) not found, out of '
'found datasets:\n%s'
% (condition, kind, t))
condition = found_cond[0]
elif condition is None:
if len(evoked_node) > 1:
_, _, conditions = _get_entries(fid, evoked_node,
allow_maxshield)
raise TypeError("Evoked file has more than one "
"condition, the condition parameters "
"must be specified from:\n%s" % conditions)
else:
condition = 0
if condition >= len(evoked_node) or condition < 0:
raise ValueError('Data set selector out of range')
my_evoked = evoked_node[condition]
# Identify the aspects
my_aspect, info['maxshield'] = _get_aspect(my_evoked, allow_maxshield)
# Now find the data in the evoked block
nchan = 0
sfreq = -1
chs = []
comment = last = first = first_time = nsamp = None
for k in range(my_evoked['nent']):
my_kind = my_evoked['directory'][k].kind
pos = my_evoked['directory'][k].pos
if my_kind == FIFF.FIFF_COMMENT:
tag = read_tag(fid, pos)
comment = tag.data
elif my_kind == FIFF.FIFF_FIRST_SAMPLE:
tag = read_tag(fid, pos)
first = int(tag.data)
elif my_kind == FIFF.FIFF_LAST_SAMPLE:
tag = read_tag(fid, pos)
last = int(tag.data)
elif my_kind == FIFF.FIFF_NCHAN:
tag = read_tag(fid, pos)
nchan = int(tag.data)
elif my_kind == FIFF.FIFF_SFREQ:
tag = read_tag(fid, pos)
sfreq = float(tag.data)
elif my_kind == FIFF.FIFF_CH_INFO:
tag = read_tag(fid, pos)
chs.append(tag.data)
elif my_kind == FIFF.FIFF_FIRST_TIME:
tag = read_tag(fid, pos)
first_time = float(tag.data)
elif my_kind == FIFF.FIFF_NO_SAMPLES:
tag = read_tag(fid, pos)
nsamp = int(tag.data)
if comment is None:
comment = 'No comment'
# Local channel information?
if nchan > 0:
if chs is None:
raise ValueError('Local channel information was not found '
'when it was expected.')
if len(chs) != nchan:
raise ValueError('Number of channels and number of '
'channel definitions are different')
info['chs'] = chs
logger.info(' Found channel information in evoked data. '
'nchan = %d' % nchan)
if sfreq > 0:
info['sfreq'] = sfreq
# Read the data in the aspect block
nave = 1
epoch = []
for k in range(my_aspect['nent']):
kind = my_aspect['directory'][k].kind
pos = my_aspect['directory'][k].pos
if kind == FIFF.FIFF_COMMENT:
tag = read_tag(fid, pos)
comment = tag.data
elif kind == FIFF.FIFF_ASPECT_KIND:
tag = read_tag(fid, pos)
aspect_kind = int(tag.data)
elif kind == FIFF.FIFF_NAVE:
tag = read_tag(fid, pos)
nave = int(tag.data)
elif kind == FIFF.FIFF_EPOCH:
tag = read_tag(fid, pos)
epoch.append(tag)
nepoch = len(epoch)
if nepoch != 1 and nepoch != info['nchan']:
raise ValueError('Number of epoch tags is unreasonable '
'(nepoch = %d nchan = %d)'
% (nepoch, info['nchan']))
if nepoch == 1:
# Only one epoch
data = epoch[0].data
# May need a transpose if the number of channels is one
if data.shape[1] == 1 and info['nchan'] == 1:
data = data.T
else:
# Put the old style epochs together
data = np.concatenate([e.data[None, :] for e in epoch], axis=0)
if np.isrealobj(data):
data = data.astype(np.float64)
else:
data = data.astype(np.complex128)
if first_time is not None and nsamp is not None:
times = first_time + np.arange(nsamp) / info['sfreq']
elif first is not None:
nsamp = last - first + 1
times = np.arange(first, last + 1) / info['sfreq']
else:
raise RuntimeError('Could not read time parameters')
del first, last
if nsamp is not None and data.shape[1] != nsamp:
raise ValueError('Incorrect number of samples (%d instead of '
' %d)' % (data.shape[1], nsamp))
logger.info(' Found the data of interest:')
logger.info(' t = %10.2f ... %10.2f ms (%s)'
% (1000 * times[0], 1000 * times[-1], comment))
if info['comps'] is not None:
logger.info(' %d CTF compensation matrices available'
% len(info['comps']))
logger.info(' nave = %d - aspect type = %d'
% (nave, aspect_kind))
# Calibrate
cals = np.array([info['chs'][k]['cal'] *
info['chs'][k].get('scale', 1.0)
for k in range(info['nchan'])])
data *= cals[:, np.newaxis]
return info, nave, aspect_kind, comment, times, data
def write_evokeds(fname, evoked):
"""Write an evoked dataset to a file.
Parameters
----------
fname : str
The file name, which should end with -ave.fif or -ave.fif.gz.
evoked : Evoked instance, or list of Evoked instances
The evoked dataset, or list of evoked datasets, to save in one file.
Note that the measurement info from the first evoked instance is used,
so be sure that information matches.
See Also
--------
read_evokeds
"""
_write_evokeds(fname, evoked)
def _write_evokeds(fname, evoked, check=True):
"""Write evoked data."""
from .epochs import _compare_epochs_infos
if check:
check_fname(fname, 'evoked', ('-ave.fif', '-ave.fif.gz',
'_ave.fif', '_ave.fif.gz'))
if not isinstance(evoked, list):
evoked = [evoked]
warned = False
# Create the file and save the essentials
with start_file(fname) as fid:
start_block(fid, FIFF.FIFFB_MEAS)
write_id(fid, FIFF.FIFF_BLOCK_ID)
if evoked[0].info['meas_id'] is not None:
write_id(fid, FIFF.FIFF_PARENT_BLOCK_ID, evoked[0].info['meas_id'])
# Write measurement info
write_meas_info(fid, evoked[0].info)
# One or more evoked data sets
start_block(fid, FIFF.FIFFB_PROCESSED_DATA)
for ei, e in enumerate(evoked):
if ei:
_compare_epochs_infos(evoked[0].info, e.info, f'evoked[{ei}]')
start_block(fid, FIFF.FIFFB_EVOKED)
# Comment is optional
if e.comment is not None and len(e.comment) > 0:
write_string(fid, FIFF.FIFF_COMMENT, e.comment)
# First time, num. samples, first and last sample
write_float(fid, FIFF.FIFF_FIRST_TIME, e.times[0])
write_int(fid, FIFF.FIFF_NO_SAMPLES, len(e.times))
write_int(fid, FIFF.FIFF_FIRST_SAMPLE, e.first)
write_int(fid, FIFF.FIFF_LAST_SAMPLE, e.last)
# The epoch itself
if e.info.get('maxshield'):
aspect = FIFF.FIFFB_IAS_ASPECT
else:
aspect = FIFF.FIFFB_ASPECT
start_block(fid, aspect)
write_int(fid, FIFF.FIFF_ASPECT_KIND, e._aspect_kind)
# convert nave to integer to comply with FIFF spec
nave_int = int(round(e.nave))
if nave_int != e.nave and not warned:
warn('converting "nave" to integer before saving evoked; this '
'can have a minor effect on the scale of source '
'estimates that are computed using "nave".')
warned = True
write_int(fid, FIFF.FIFF_NAVE, nave_int)
del nave_int
decal = np.zeros((e.info['nchan'], 1))
for k in range(e.info['nchan']):
decal[k] = 1.0 / (e.info['chs'][k]['cal'] *
e.info['chs'][k].get('scale', 1.0))
if np.iscomplexobj(e.data):
write_function = write_complex_float_matrix
else:
write_function = write_float_matrix
write_function(fid, FIFF.FIFF_EPOCH, decal * e.data)
end_block(fid, aspect)
end_block(fid, FIFF.FIFFB_EVOKED)
end_block(fid, FIFF.FIFFB_PROCESSED_DATA)
end_block(fid, FIFF.FIFFB_MEAS)
end_file(fid)
def _get_peak(data, times, tmin=None, tmax=None, mode='abs'):
"""Get feature-index and time of maximum signal from 2D array.
Note. This is a 'getter', not a 'finder'. For non-evoked type
data and continuous signals, please use proper peak detection algorithms.
Parameters
----------
data : instance of numpy.ndarray (n_locations, n_times)
The data, either evoked in sensor or source space.
times : instance of numpy.ndarray (n_times)
The times in seconds.
tmin : float | None
The minimum point in time to be considered for peak getting.
tmax : float | None
The maximum point in time to be considered for peak getting.
mode : {'pos', 'neg', 'abs'}
How to deal with the sign of the data. If 'pos' only positive
values will be considered. If 'neg' only negative values will
be considered. If 'abs' absolute values will be considered.
Defaults to 'abs'.
Returns
-------
max_loc : int
The index of the feature with the maximum value.
max_time : int
The time point of the maximum response, index.
max_amp : float
Amplitude of the maximum response.
"""
_check_option('mode', mode, ['abs', 'neg', 'pos'])
if tmin is None:
tmin = times[0]
if tmax is None:
tmax = times[-1]
if tmin < times.min():
raise ValueError('The tmin value is out of bounds. It must be '
'within {} and {}'.format(times.min(), times.max()))
if tmax > times.max():
raise ValueError('The tmax value is out of bounds. It must be '
'within {} and {}'.format(times.min(), times.max()))
if tmin > tmax:
raise ValueError('The tmin must be smaller or equal to tmax')
time_win = (times >= tmin) & (times <= tmax)
mask = np.ones_like(data).astype(bool)
mask[:, time_win] = False
maxfun = np.argmax
if mode == 'pos':
if not np.any(data > 0):
raise ValueError('No positive values encountered. Cannot '
'operate in pos mode.')
elif mode == 'neg':
if not np.any(data < 0):
raise ValueError('No negative values encountered. Cannot '
'operate in neg mode.')
maxfun = np.argmin
masked_index = np.ma.array(np.abs(data) if mode == 'abs' else data,
mask=mask)
max_loc, max_time = np.unravel_index(maxfun(masked_index), data.shape)
return max_loc, max_time, data[max_loc, max_time]
|
bsd-3-clause
|
fbagirov/scikit-learn
|
benchmarks/bench_plot_approximate_neighbors.py
|
244
|
6011
|
"""
Benchmark for approximate nearest neighbor search using
locality sensitive hashing forest.
There are two types of benchmarks.
First, accuracy of LSHForest queries are measured for various
hyper-parameters and index sizes.
Second, speed up of LSHForest queries compared to brute force
method in exact nearest neighbors is measures for the
aforementioned settings. In general, speed up is increasing as
the index size grows.
"""
from __future__ import division
import numpy as np
from tempfile import gettempdir
from time import time
from sklearn.neighbors import NearestNeighbors
from sklearn.neighbors.approximate import LSHForest
from sklearn.datasets import make_blobs
from sklearn.externals.joblib import Memory
m = Memory(cachedir=gettempdir())
@m.cache()
def make_data(n_samples, n_features, n_queries, random_state=0):
"""Create index and query data."""
print('Generating random blob-ish data')
X, _ = make_blobs(n_samples=n_samples + n_queries,
n_features=n_features, centers=100,
shuffle=True, random_state=random_state)
# Keep the last samples as held out query vectors: note since we used
# shuffle=True we have ensured that index and query vectors are
# samples from the same distribution (a mixture of 100 gaussians in this
# case)
return X[:n_samples], X[n_samples:]
def calc_exact_neighbors(X, queries, n_queries, n_neighbors):
"""Measures average times for exact neighbor queries."""
print ('Building NearestNeighbors for %d samples in %d dimensions' %
(X.shape[0], X.shape[1]))
nbrs = NearestNeighbors(algorithm='brute', metric='cosine').fit(X)
average_time = 0
t0 = time()
neighbors = nbrs.kneighbors(queries, n_neighbors=n_neighbors,
return_distance=False)
average_time = (time() - t0) / n_queries
return neighbors, average_time
def calc_accuracy(X, queries, n_queries, n_neighbors, exact_neighbors,
average_time_exact, **lshf_params):
"""Calculates accuracy and the speed up of LSHForest."""
print('Building LSHForest for %d samples in %d dimensions' %
(X.shape[0], X.shape[1]))
lshf = LSHForest(**lshf_params)
t0 = time()
lshf.fit(X)
lshf_build_time = time() - t0
print('Done in %0.3fs' % lshf_build_time)
accuracy = 0
t0 = time()
approx_neighbors = lshf.kneighbors(queries, n_neighbors=n_neighbors,
return_distance=False)
average_time_approx = (time() - t0) / n_queries
for i in range(len(queries)):
accuracy += np.in1d(approx_neighbors[i], exact_neighbors[i]).mean()
accuracy /= n_queries
speed_up = average_time_exact / average_time_approx
print('Average time for lshf neighbor queries: %0.3fs' %
average_time_approx)
print ('Average time for exact neighbor queries: %0.3fs' %
average_time_exact)
print ('Average Accuracy : %0.2f' % accuracy)
print ('Speed up: %0.1fx' % speed_up)
return speed_up, accuracy
if __name__ == '__main__':
import matplotlib.pyplot as plt
# Initialize index sizes
n_samples = [int(1e3), int(1e4), int(1e5), int(1e6)]
n_features = int(1e2)
n_queries = 100
n_neighbors = 10
X_index, X_query = make_data(np.max(n_samples), n_features, n_queries,
random_state=0)
params_list = [{'n_estimators': 3, 'n_candidates': 50},
{'n_estimators': 5, 'n_candidates': 70},
{'n_estimators': 10, 'n_candidates': 100}]
accuracies = np.zeros((len(n_samples), len(params_list)), dtype=float)
speed_ups = np.zeros((len(n_samples), len(params_list)), dtype=float)
for i, sample_size in enumerate(n_samples):
print ('==========================================================')
print ('Sample size: %i' % sample_size)
print ('------------------------')
exact_neighbors, average_time_exact = calc_exact_neighbors(
X_index[:sample_size], X_query, n_queries, n_neighbors)
for j, params in enumerate(params_list):
print ('LSHF parameters: n_estimators = %i, n_candidates = %i' %
(params['n_estimators'], params['n_candidates']))
speed_ups[i, j], accuracies[i, j] = calc_accuracy(
X_index[:sample_size], X_query, n_queries, n_neighbors,
exact_neighbors, average_time_exact, random_state=0, **params)
print ('')
print ('==========================================================')
# Set labels for LSHForest parameters
colors = ['c', 'm', 'y']
legend_rects = [plt.Rectangle((0, 0), 0.1, 0.1, fc=color)
for color in colors]
legend_labels = ['n_estimators={n_estimators}, '
'n_candidates={n_candidates}'.format(**p)
for p in params_list]
# Plot precision
plt.figure()
plt.legend(legend_rects, legend_labels,
loc='upper left')
for i in range(len(params_list)):
plt.scatter(n_samples, accuracies[:, i], c=colors[i])
plt.plot(n_samples, accuracies[:, i], c=colors[i])
plt.ylim([0, 1.3])
plt.xlim(np.min(n_samples), np.max(n_samples))
plt.semilogx()
plt.ylabel("Precision@10")
plt.xlabel("Index size")
plt.grid(which='both')
plt.title("Precision of first 10 neighbors with index size")
# Plot speed up
plt.figure()
plt.legend(legend_rects, legend_labels,
loc='upper left')
for i in range(len(params_list)):
plt.scatter(n_samples, speed_ups[:, i], c=colors[i])
plt.plot(n_samples, speed_ups[:, i], c=colors[i])
plt.ylim(0, np.max(speed_ups))
plt.xlim(np.min(n_samples), np.max(n_samples))
plt.semilogx()
plt.ylabel("Speed up")
plt.xlabel("Index size")
plt.grid(which='both')
plt.title("Relationship between Speed up and index size")
plt.show()
|
bsd-3-clause
|
with-git/tensorflow
|
tensorflow/examples/learn/text_classification_character_cnn.py
|
29
|
5666
|
# 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.
"""Example of using convolutional networks over characters for DBpedia dataset.
This model is similar to one described in this paper:
"Character-level Convolutional Networks for Text Classification"
http://arxiv.org/abs/1509.01626
and is somewhat alternative to the Lua code from here:
https://github.com/zhangxiangxiao/Crepe
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import sys
import numpy as np
import pandas
from sklearn import metrics
import tensorflow as tf
FLAGS = None
MAX_DOCUMENT_LENGTH = 100
N_FILTERS = 10
FILTER_SHAPE1 = [20, 256]
FILTER_SHAPE2 = [20, N_FILTERS]
POOLING_WINDOW = 4
POOLING_STRIDE = 2
MAX_LABEL = 15
CHARS_FEATURE = 'chars' # Name of the input character feature.
def char_cnn_model(features, labels, mode):
"""Character level convolutional neural network model to predict classes."""
features_onehot = tf.one_hot(features[CHARS_FEATURE], 256)
input_layer = tf.reshape(
features_onehot, [-1, MAX_DOCUMENT_LENGTH, 256, 1])
with tf.variable_scope('CNN_Layer1'):
# Apply Convolution filtering on input sequence.
conv1 = tf.layers.conv2d(
input_layer,
filters=N_FILTERS,
kernel_size=FILTER_SHAPE1,
padding='VALID',
# Add a ReLU for non linearity.
activation=tf.nn.relu)
# Max pooling across output of Convolution+Relu.
pool1 = tf.layers.max_pooling2d(
conv1,
pool_size=POOLING_WINDOW,
strides=POOLING_STRIDE,
padding='SAME')
# Transpose matrix so that n_filters from convolution becomes width.
pool1 = tf.transpose(pool1, [0, 1, 3, 2])
with tf.variable_scope('CNN_Layer2'):
# Second level of convolution filtering.
conv2 = tf.layers.conv2d(
pool1,
filters=N_FILTERS,
kernel_size=FILTER_SHAPE2,
padding='VALID')
# Max across each filter to get useful features for classification.
pool2 = tf.squeeze(tf.reduce_max(conv2, 1), squeeze_dims=[1])
# Apply regular WX + B and classification.
logits = tf.layers.dense(pool2, MAX_LABEL, activation=None)
predicted_classes = tf.argmax(logits, 1)
if mode == tf.estimator.ModeKeys.PREDICT:
return tf.estimator.EstimatorSpec(
mode=mode,
predictions={
'class': predicted_classes,
'prob': tf.nn.softmax(logits)
})
onehot_labels = tf.one_hot(labels, MAX_LABEL, 1, 0)
loss = tf.losses.softmax_cross_entropy(
onehot_labels=onehot_labels, logits=logits)
if mode == tf.estimator.ModeKeys.TRAIN:
optimizer = tf.train.AdamOptimizer(learning_rate=0.01)
train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step())
return tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op)
eval_metric_ops = {
'accuracy': tf.metrics.accuracy(
labels=labels, predictions=predicted_classes)
}
return tf.estimator.EstimatorSpec(
mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)
def main(unused_argv):
# Prepare training and testing data
dbpedia = tf.contrib.learn.datasets.load_dataset(
'dbpedia', test_with_fake_data=FLAGS.test_with_fake_data, size='large')
x_train = pandas.DataFrame(dbpedia.train.data)[1]
y_train = pandas.Series(dbpedia.train.target)
x_test = pandas.DataFrame(dbpedia.test.data)[1]
y_test = pandas.Series(dbpedia.test.target)
# Process vocabulary
char_processor = tf.contrib.learn.preprocessing.ByteProcessor(
MAX_DOCUMENT_LENGTH)
x_train = np.array(list(char_processor.fit_transform(x_train)))
x_test = np.array(list(char_processor.transform(x_test)))
x_train = x_train.reshape([-1, MAX_DOCUMENT_LENGTH, 1, 1])
x_test = x_test.reshape([-1, MAX_DOCUMENT_LENGTH, 1, 1])
# Build model
classifier = tf.estimator.Estimator(model_fn=char_cnn_model)
# Train.
train_input_fn = tf.estimator.inputs.numpy_input_fn(
x={CHARS_FEATURE: x_train},
y=y_train,
batch_size=len(x_train),
num_epochs=None,
shuffle=True)
classifier.train(input_fn=train_input_fn, steps=100)
# Predict.
test_input_fn = tf.estimator.inputs.numpy_input_fn(
x={CHARS_FEATURE: x_test},
y=y_test,
num_epochs=1,
shuffle=False)
predictions = classifier.predict(input_fn=test_input_fn)
y_predicted = np.array(list(p['class'] for p in predictions))
y_predicted = y_predicted.reshape(np.array(y_test).shape)
# Score with sklearn.
score = metrics.accuracy_score(y_test, y_predicted)
print('Accuracy (sklearn): {0:f}'.format(score))
# Score with tensorflow.
scores = classifier.evaluate(input_fn=test_input_fn)
print('Accuracy (tensorflow): {0:f}'.format(scores['accuracy']))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--test_with_fake_data',
default=False,
help='Test the example code with fake data.',
action='store_true')
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
|
apache-2.0
|
mne-tools/mne-tools.github.io
|
0.22/_downloads/39d3358b9f252f10b2df9727fa455345/plot_label_activation_from_stc.py
|
62
|
1949
|
"""
==================================================
Extracting time course from source_estimate object
==================================================
Load a SourceEstimate object from stc files and
extract the time course of activation in
individual labels, as well as in a complex label
formed through merging two labels.
"""
# Author: Christian Brodbeck <[email protected]>
#
# License: BSD (3-clause)
import os
import mne
from mne.datasets import sample
import matplotlib.pyplot as plt
print(__doc__)
data_path = sample.data_path()
os.environ['SUBJECTS_DIR'] = data_path + '/subjects'
meg_path = data_path + '/MEG/sample'
# load the stc
stc = mne.read_source_estimate(meg_path + '/sample_audvis-meg')
# load the labels
aud_lh = mne.read_label(meg_path + '/labels/Aud-lh.label')
aud_rh = mne.read_label(meg_path + '/labels/Aud-rh.label')
# extract the time course for different labels from the stc
stc_lh = stc.in_label(aud_lh)
stc_rh = stc.in_label(aud_rh)
stc_bh = stc.in_label(aud_lh + aud_rh)
# calculate center of mass and transform to mni coordinates
vtx, _, t_lh = stc_lh.center_of_mass('sample')
mni_lh = mne.vertex_to_mni(vtx, 0, 'sample')[0]
vtx, _, t_rh = stc_rh.center_of_mass('sample')
mni_rh = mne.vertex_to_mni(vtx, 1, 'sample')[0]
# plot the activation
plt.figure()
plt.axes([.1, .275, .85, .625])
hl = plt.plot(stc.times, stc_lh.data.mean(0), 'b')[0]
hr = plt.plot(stc.times, stc_rh.data.mean(0), 'g')[0]
hb = plt.plot(stc.times, stc_bh.data.mean(0), 'r')[0]
plt.xlabel('Time (s)')
plt.ylabel('Source amplitude (dSPM)')
plt.xlim(stc.times[0], stc.times[-1])
# add a legend including center-of-mass mni coordinates to the plot
labels = ['LH: center of mass = %s' % mni_lh.round(2),
'RH: center of mass = %s' % mni_rh.round(2),
'Combined LH & RH']
plt.figlegend([hl, hr, hb], labels, 'lower center')
plt.suptitle('Average activation in auditory cortex labels', fontsize=20)
plt.show()
|
bsd-3-clause
|
ElDeveloper/scikit-learn
|
sklearn/cross_decomposition/tests/test_pls.py
|
23
|
14318
|
import numpy as np
from sklearn.utils.testing import (assert_array_almost_equal,
assert_array_equal, assert_true,
assert_raise_message)
from sklearn.datasets import load_linnerud
from sklearn.cross_decomposition import pls_, CCA
from nose.tools import assert_equal
def test_pls():
d = load_linnerud()
X = d.data
Y = d.target
# 1) Canonical (symmetric) PLS (PLS 2 blocks canonical mode A)
# ===========================================================
# Compare 2 algo.: nipals vs. svd
# ------------------------------
pls_bynipals = pls_.PLSCanonical(n_components=X.shape[1])
pls_bynipals.fit(X, Y)
pls_bysvd = pls_.PLSCanonical(algorithm="svd", n_components=X.shape[1])
pls_bysvd.fit(X, Y)
# check equalities of loading (up to the sign of the second column)
assert_array_almost_equal(
pls_bynipals.x_loadings_,
pls_bysvd.x_loadings_, decimal=5,
err_msg="nipals and svd implementations lead to different x loadings")
assert_array_almost_equal(
pls_bynipals.y_loadings_,
pls_bysvd.y_loadings_, decimal=5,
err_msg="nipals and svd implementations lead to different y loadings")
# Check PLS properties (with n_components=X.shape[1])
# ---------------------------------------------------
plsca = pls_.PLSCanonical(n_components=X.shape[1])
plsca.fit(X, Y)
T = plsca.x_scores_
P = plsca.x_loadings_
Wx = plsca.x_weights_
U = plsca.y_scores_
Q = plsca.y_loadings_
Wy = plsca.y_weights_
def check_ortho(M, err_msg):
K = np.dot(M.T, M)
assert_array_almost_equal(K, np.diag(np.diag(K)), err_msg=err_msg)
# Orthogonality of weights
# ~~~~~~~~~~~~~~~~~~~~~~~~
check_ortho(Wx, "x weights are not orthogonal")
check_ortho(Wy, "y weights are not orthogonal")
# Orthogonality of latent scores
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
check_ortho(T, "x scores are not orthogonal")
check_ortho(U, "y scores are not orthogonal")
# Check X = TP' and Y = UQ' (with (p == q) components)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# center scale X, Y
Xc, Yc, x_mean, y_mean, x_std, y_std =\
pls_._center_scale_xy(X.copy(), Y.copy(), scale=True)
assert_array_almost_equal(Xc, np.dot(T, P.T), err_msg="X != TP'")
assert_array_almost_equal(Yc, np.dot(U, Q.T), err_msg="Y != UQ'")
# Check that rotations on training data lead to scores
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Xr = plsca.transform(X)
assert_array_almost_equal(Xr, plsca.x_scores_,
err_msg="rotation on X failed")
Xr, Yr = plsca.transform(X, Y)
assert_array_almost_equal(Xr, plsca.x_scores_,
err_msg="rotation on X failed")
assert_array_almost_equal(Yr, plsca.y_scores_,
err_msg="rotation on Y failed")
# "Non regression test" on canonical PLS
# --------------------------------------
# The results were checked against the R-package plspm
pls_ca = pls_.PLSCanonical(n_components=X.shape[1])
pls_ca.fit(X, Y)
x_weights = np.array(
[[-0.61330704, 0.25616119, -0.74715187],
[-0.74697144, 0.11930791, 0.65406368],
[-0.25668686, -0.95924297, -0.11817271]])
# x_weights_sign_flip holds columns of 1 or -1, depending on sign flip
# between R and python
x_weights_sign_flip = pls_ca.x_weights_ / x_weights
x_rotations = np.array(
[[-0.61330704, 0.41591889, -0.62297525],
[-0.74697144, 0.31388326, 0.77368233],
[-0.25668686, -0.89237972, -0.24121788]])
x_rotations_sign_flip = pls_ca.x_rotations_ / x_rotations
y_weights = np.array(
[[+0.58989127, 0.7890047, 0.1717553],
[+0.77134053, -0.61351791, 0.16920272],
[-0.23887670, -0.03267062, 0.97050016]])
y_weights_sign_flip = pls_ca.y_weights_ / y_weights
y_rotations = np.array(
[[+0.58989127, 0.7168115, 0.30665872],
[+0.77134053, -0.70791757, 0.19786539],
[-0.23887670, -0.00343595, 0.94162826]])
y_rotations_sign_flip = pls_ca.y_rotations_ / y_rotations
# x_weights = X.dot(x_rotation)
# Hence R/python sign flip should be the same in x_weight and x_rotation
assert_array_almost_equal(x_rotations_sign_flip, x_weights_sign_flip)
# This test that R / python give the same result up to colunm
# sign indeterminacy
assert_array_almost_equal(np.abs(x_rotations_sign_flip), 1, 4)
assert_array_almost_equal(np.abs(x_weights_sign_flip), 1, 4)
assert_array_almost_equal(y_rotations_sign_flip, y_weights_sign_flip)
assert_array_almost_equal(np.abs(y_rotations_sign_flip), 1, 4)
assert_array_almost_equal(np.abs(y_weights_sign_flip), 1, 4)
# 2) Regression PLS (PLS2): "Non regression test"
# ===============================================
# The results were checked against the R-packages plspm, misOmics and pls
pls_2 = pls_.PLSRegression(n_components=X.shape[1])
pls_2.fit(X, Y)
x_weights = np.array(
[[-0.61330704, -0.00443647, 0.78983213],
[-0.74697144, -0.32172099, -0.58183269],
[-0.25668686, 0.94682413, -0.19399983]])
x_weights_sign_flip = pls_2.x_weights_ / x_weights
x_loadings = np.array(
[[-0.61470416, -0.24574278, 0.78983213],
[-0.65625755, -0.14396183, -0.58183269],
[-0.51733059, 1.00609417, -0.19399983]])
x_loadings_sign_flip = pls_2.x_loadings_ / x_loadings
y_weights = np.array(
[[+0.32456184, 0.29892183, 0.20316322],
[+0.42439636, 0.61970543, 0.19320542],
[-0.13143144, -0.26348971, -0.17092916]])
y_weights_sign_flip = pls_2.y_weights_ / y_weights
y_loadings = np.array(
[[+0.32456184, 0.29892183, 0.20316322],
[+0.42439636, 0.61970543, 0.19320542],
[-0.13143144, -0.26348971, -0.17092916]])
y_loadings_sign_flip = pls_2.y_loadings_ / y_loadings
# x_loadings[:, i] = Xi.dot(x_weights[:, i]) \forall i
assert_array_almost_equal(x_loadings_sign_flip, x_weights_sign_flip, 4)
assert_array_almost_equal(np.abs(x_loadings_sign_flip), 1, 4)
assert_array_almost_equal(np.abs(x_weights_sign_flip), 1, 4)
assert_array_almost_equal(y_loadings_sign_flip, y_weights_sign_flip, 4)
assert_array_almost_equal(np.abs(y_loadings_sign_flip), 1, 4)
assert_array_almost_equal(np.abs(y_weights_sign_flip), 1, 4)
# 3) Another non-regression test of Canonical PLS on random dataset
# =================================================================
# The results were checked against the R-package plspm
n = 500
p_noise = 10
q_noise = 5
# 2 latents vars:
np.random.seed(11)
l1 = np.random.normal(size=n)
l2 = np.random.normal(size=n)
latents = np.array([l1, l1, l2, l2]).T
X = latents + np.random.normal(size=4 * n).reshape((n, 4))
Y = latents + np.random.normal(size=4 * n).reshape((n, 4))
X = np.concatenate(
(X, np.random.normal(size=p_noise * n).reshape(n, p_noise)), axis=1)
Y = np.concatenate(
(Y, np.random.normal(size=q_noise * n).reshape(n, q_noise)), axis=1)
np.random.seed(None)
pls_ca = pls_.PLSCanonical(n_components=3)
pls_ca.fit(X, Y)
x_weights = np.array(
[[0.65803719, 0.19197924, 0.21769083],
[0.7009113, 0.13303969, -0.15376699],
[0.13528197, -0.68636408, 0.13856546],
[0.16854574, -0.66788088, -0.12485304],
[-0.03232333, -0.04189855, 0.40690153],
[0.1148816, -0.09643158, 0.1613305],
[0.04792138, -0.02384992, 0.17175319],
[-0.06781, -0.01666137, -0.18556747],
[-0.00266945, -0.00160224, 0.11893098],
[-0.00849528, -0.07706095, 0.1570547],
[-0.00949471, -0.02964127, 0.34657036],
[-0.03572177, 0.0945091, 0.3414855],
[0.05584937, -0.02028961, -0.57682568],
[0.05744254, -0.01482333, -0.17431274]])
x_weights_sign_flip = pls_ca.x_weights_ / x_weights
x_loadings = np.array(
[[0.65649254, 0.1847647, 0.15270699],
[0.67554234, 0.15237508, -0.09182247],
[0.19219925, -0.67750975, 0.08673128],
[0.2133631, -0.67034809, -0.08835483],
[-0.03178912, -0.06668336, 0.43395268],
[0.15684588, -0.13350241, 0.20578984],
[0.03337736, -0.03807306, 0.09871553],
[-0.06199844, 0.01559854, -0.1881785],
[0.00406146, -0.00587025, 0.16413253],
[-0.00374239, -0.05848466, 0.19140336],
[0.00139214, -0.01033161, 0.32239136],
[-0.05292828, 0.0953533, 0.31916881],
[0.04031924, -0.01961045, -0.65174036],
[0.06172484, -0.06597366, -0.1244497]])
x_loadings_sign_flip = pls_ca.x_loadings_ / x_loadings
y_weights = np.array(
[[0.66101097, 0.18672553, 0.22826092],
[0.69347861, 0.18463471, -0.23995597],
[0.14462724, -0.66504085, 0.17082434],
[0.22247955, -0.6932605, -0.09832993],
[0.07035859, 0.00714283, 0.67810124],
[0.07765351, -0.0105204, -0.44108074],
[-0.00917056, 0.04322147, 0.10062478],
[-0.01909512, 0.06182718, 0.28830475],
[0.01756709, 0.04797666, 0.32225745]])
y_weights_sign_flip = pls_ca.y_weights_ / y_weights
y_loadings = np.array(
[[0.68568625, 0.1674376, 0.0969508],
[0.68782064, 0.20375837, -0.1164448],
[0.11712173, -0.68046903, 0.12001505],
[0.17860457, -0.6798319, -0.05089681],
[0.06265739, -0.0277703, 0.74729584],
[0.0914178, 0.00403751, -0.5135078],
[-0.02196918, -0.01377169, 0.09564505],
[-0.03288952, 0.09039729, 0.31858973],
[0.04287624, 0.05254676, 0.27836841]])
y_loadings_sign_flip = pls_ca.y_loadings_ / y_loadings
assert_array_almost_equal(x_loadings_sign_flip, x_weights_sign_flip, 4)
assert_array_almost_equal(np.abs(x_weights_sign_flip), 1, 4)
assert_array_almost_equal(np.abs(x_loadings_sign_flip), 1, 4)
assert_array_almost_equal(y_loadings_sign_flip, y_weights_sign_flip, 4)
assert_array_almost_equal(np.abs(y_weights_sign_flip), 1, 4)
assert_array_almost_equal(np.abs(y_loadings_sign_flip), 1, 4)
# Orthogonality of weights
# ~~~~~~~~~~~~~~~~~~~~~~~~
check_ortho(pls_ca.x_weights_, "x weights are not orthogonal")
check_ortho(pls_ca.y_weights_, "y weights are not orthogonal")
# Orthogonality of latent scores
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
check_ortho(pls_ca.x_scores_, "x scores are not orthogonal")
check_ortho(pls_ca.y_scores_, "y scores are not orthogonal")
def test_PLSSVD():
# Let's check the PLSSVD doesn't return all possible component but just
# the specificied number
d = load_linnerud()
X = d.data
Y = d.target
n_components = 2
for clf in [pls_.PLSSVD, pls_.PLSRegression, pls_.PLSCanonical]:
pls = clf(n_components=n_components)
pls.fit(X, Y)
assert_equal(n_components, pls.y_scores_.shape[1])
def test_univariate_pls_regression():
# Ensure 1d Y is correctly interpreted
d = load_linnerud()
X = d.data
Y = d.target
clf = pls_.PLSRegression()
# Compare 1d to column vector
model1 = clf.fit(X, Y[:, 0]).coef_
model2 = clf.fit(X, Y[:, :1]).coef_
assert_array_almost_equal(model1, model2)
def test_predict_transform_copy():
# check that the "copy" keyword works
d = load_linnerud()
X = d.data
Y = d.target
clf = pls_.PLSCanonical()
X_copy = X.copy()
Y_copy = Y.copy()
clf.fit(X, Y)
# check that results are identical with copy
assert_array_almost_equal(clf.predict(X), clf.predict(X.copy(), copy=False))
assert_array_almost_equal(clf.transform(X), clf.transform(X.copy(), copy=False))
# check also if passing Y
assert_array_almost_equal(clf.transform(X, Y),
clf.transform(X.copy(), Y.copy(), copy=False))
# check that copy doesn't destroy
# we do want to check exact equality here
assert_array_equal(X_copy, X)
assert_array_equal(Y_copy, Y)
# also check that mean wasn't zero before (to make sure we didn't touch it)
assert_true(np.all(X.mean(axis=0) != 0))
def test_scale_and_stability():
# We test scale=True parameter
# This allows to check numerical stability over platforms as well
d = load_linnerud()
X1 = d.data
Y1 = d.target
# causes X[:, -1].std() to be zero
X1[:, -1] = 1.0
# From bug #2821
# Test with X2, T2 s.t. clf.x_score[:, 1] == 0, clf.y_score[:, 1] == 0
# This test robustness of algorithm when dealing with value close to 0
X2 = np.array([[0., 0., 1.],
[1., 0., 0.],
[2., 2., 2.],
[3., 5., 4.]])
Y2 = np.array([[0.1, -0.2],
[0.9, 1.1],
[6.2, 5.9],
[11.9, 12.3]])
for (X, Y) in [(X1, Y1), (X2, Y2)]:
X_std = X.std(axis=0, ddof=1)
X_std[X_std == 0] = 1
Y_std = Y.std(axis=0, ddof=1)
Y_std[Y_std == 0] = 1
X_s = (X - X.mean(axis=0)) / X_std
Y_s = (Y - Y.mean(axis=0)) / Y_std
for clf in [CCA(), pls_.PLSCanonical(), pls_.PLSRegression(),
pls_.PLSSVD()]:
clf.set_params(scale=True)
X_score, Y_score = clf.fit_transform(X, Y)
clf.set_params(scale=False)
X_s_score, Y_s_score = clf.fit_transform(X_s, Y_s)
assert_array_almost_equal(X_s_score, X_score)
assert_array_almost_equal(Y_s_score, Y_score)
# Scaling should be idempotent
clf.set_params(scale=True)
X_score, Y_score = clf.fit_transform(X_s, Y_s)
assert_array_almost_equal(X_s_score, X_score)
assert_array_almost_equal(Y_s_score, Y_score)
def test_pls_errors():
d = load_linnerud()
X = d.data
Y = d.target
for clf in [pls_.PLSCanonical(), pls_.PLSRegression(),
pls_.PLSSVD()]:
clf.n_components = 4
assert_raise_message(ValueError, "Invalid number of components", clf.fit, X, Y)
|
bsd-3-clause
|
saiwing-yeung/scikit-learn
|
sklearn/linear_model/tests/test_least_angle.py
|
42
|
20925
|
from nose.tools import assert_equal
import numpy as np
from scipy import linalg
from sklearn.model_selection import train_test_split
from sklearn.utils.testing import assert_array_almost_equal
from sklearn.utils.testing import assert_true
from sklearn.utils.testing import assert_less
from sklearn.utils.testing import assert_greater
from sklearn.utils.testing import assert_raises
from sklearn.utils.testing import ignore_warnings
from sklearn.utils.testing import assert_no_warnings, assert_warns
from sklearn.utils.testing import TempMemmap
from sklearn.exceptions import ConvergenceWarning
from sklearn import linear_model, datasets
from sklearn.linear_model.least_angle import _lars_path_residues
diabetes = datasets.load_diabetes()
X, y = diabetes.data, diabetes.target
# TODO: use another dataset that has multiple drops
def test_simple():
# Principle of Lars is to keep covariances tied and decreasing
# also test verbose output
from sklearn.externals.six.moves import cStringIO as StringIO
import sys
old_stdout = sys.stdout
try:
sys.stdout = StringIO()
alphas_, active, coef_path_ = linear_model.lars_path(
diabetes.data, diabetes.target, method="lar", verbose=10)
sys.stdout = old_stdout
for (i, coef_) in enumerate(coef_path_.T):
res = y - np.dot(X, coef_)
cov = np.dot(X.T, res)
C = np.max(abs(cov))
eps = 1e-3
ocur = len(cov[C - eps < abs(cov)])
if i < X.shape[1]:
assert_true(ocur == i + 1)
else:
# no more than max_pred variables can go into the active set
assert_true(ocur == X.shape[1])
finally:
sys.stdout = old_stdout
def test_simple_precomputed():
# The same, with precomputed Gram matrix
G = np.dot(diabetes.data.T, diabetes.data)
alphas_, active, coef_path_ = linear_model.lars_path(
diabetes.data, diabetes.target, Gram=G, method="lar")
for i, coef_ in enumerate(coef_path_.T):
res = y - np.dot(X, coef_)
cov = np.dot(X.T, res)
C = np.max(abs(cov))
eps = 1e-3
ocur = len(cov[C - eps < abs(cov)])
if i < X.shape[1]:
assert_true(ocur == i + 1)
else:
# no more than max_pred variables can go into the active set
assert_true(ocur == X.shape[1])
def test_all_precomputed():
# Test that lars_path with precomputed Gram and Xy gives the right answer
X, y = diabetes.data, diabetes.target
G = np.dot(X.T, X)
Xy = np.dot(X.T, y)
for method in 'lar', 'lasso':
output = linear_model.lars_path(X, y, method=method)
output_pre = linear_model.lars_path(X, y, Gram=G, Xy=Xy, method=method)
for expected, got in zip(output, output_pre):
assert_array_almost_equal(expected, got)
def test_lars_lstsq():
# Test that Lars gives least square solution at the end
# of the path
X1 = 3 * diabetes.data # use un-normalized dataset
clf = linear_model.LassoLars(alpha=0.)
clf.fit(X1, y)
coef_lstsq = np.linalg.lstsq(X1, y)[0]
assert_array_almost_equal(clf.coef_, coef_lstsq)
def test_lasso_gives_lstsq_solution():
# Test that Lars Lasso gives least square solution at the end
# of the path
alphas_, active, coef_path_ = linear_model.lars_path(X, y, method="lasso")
coef_lstsq = np.linalg.lstsq(X, y)[0]
assert_array_almost_equal(coef_lstsq, coef_path_[:, -1])
def test_collinearity():
# Check that lars_path is robust to collinearity in input
X = np.array([[3., 3., 1.],
[2., 2., 0.],
[1., 1., 0]])
y = np.array([1., 0., 0])
f = ignore_warnings
_, _, coef_path_ = f(linear_model.lars_path)(X, y, alpha_min=0.01)
assert_true(not np.isnan(coef_path_).any())
residual = np.dot(X, coef_path_[:, -1]) - y
assert_less((residual ** 2).sum(), 1.) # just make sure it's bounded
n_samples = 10
X = np.random.rand(n_samples, 5)
y = np.zeros(n_samples)
_, _, coef_path_ = linear_model.lars_path(X, y, Gram='auto', copy_X=False,
copy_Gram=False, alpha_min=0.,
method='lasso', verbose=0,
max_iter=500)
assert_array_almost_equal(coef_path_, np.zeros_like(coef_path_))
def test_no_path():
# Test that the ``return_path=False`` option returns the correct output
alphas_, active_, coef_path_ = linear_model.lars_path(
diabetes.data, diabetes.target, method="lar")
alpha_, active, coef = linear_model.lars_path(
diabetes.data, diabetes.target, method="lar", return_path=False)
assert_array_almost_equal(coef, coef_path_[:, -1])
assert_true(alpha_ == alphas_[-1])
def test_no_path_precomputed():
# Test that the ``return_path=False`` option with Gram remains correct
G = np.dot(diabetes.data.T, diabetes.data)
alphas_, active_, coef_path_ = linear_model.lars_path(
diabetes.data, diabetes.target, method="lar", Gram=G)
alpha_, active, coef = linear_model.lars_path(
diabetes.data, diabetes.target, method="lar", Gram=G,
return_path=False)
assert_array_almost_equal(coef, coef_path_[:, -1])
assert_true(alpha_ == alphas_[-1])
def test_no_path_all_precomputed():
# Test that the ``return_path=False`` option with Gram and Xy remains
# correct
X, y = 3 * diabetes.data, diabetes.target
G = np.dot(X.T, X)
Xy = np.dot(X.T, y)
alphas_, active_, coef_path_ = linear_model.lars_path(
X, y, method="lasso", Gram=G, Xy=Xy, alpha_min=0.9)
print("---")
alpha_, active, coef = linear_model.lars_path(
X, y, method="lasso", Gram=G, Xy=Xy, alpha_min=0.9, return_path=False)
assert_array_almost_equal(coef, coef_path_[:, -1])
assert_true(alpha_ == alphas_[-1])
def test_singular_matrix():
# Test when input is a singular matrix
X1 = np.array([[1, 1.], [1., 1.]])
y1 = np.array([1, 1])
alphas, active, coef_path = linear_model.lars_path(X1, y1)
assert_array_almost_equal(coef_path.T, [[0, 0], [1, 0]])
def test_rank_deficient_design():
# consistency test that checks that LARS Lasso is handling rank
# deficient input data (with n_features < rank) in the same way
# as coordinate descent Lasso
y = [5, 0, 5]
for X in ([[5, 0],
[0, 5],
[10, 10]],
[[10, 10, 0],
[1e-32, 0, 0],
[0, 0, 1]],
):
# To be able to use the coefs to compute the objective function,
# we need to turn off normalization
lars = linear_model.LassoLars(.1, normalize=False)
coef_lars_ = lars.fit(X, y).coef_
obj_lars = (1. / (2. * 3.)
* linalg.norm(y - np.dot(X, coef_lars_)) ** 2
+ .1 * linalg.norm(coef_lars_, 1))
coord_descent = linear_model.Lasso(.1, tol=1e-6, normalize=False)
coef_cd_ = coord_descent.fit(X, y).coef_
obj_cd = ((1. / (2. * 3.)) * linalg.norm(y - np.dot(X, coef_cd_)) ** 2
+ .1 * linalg.norm(coef_cd_, 1))
assert_less(obj_lars, obj_cd * (1. + 1e-8))
def test_lasso_lars_vs_lasso_cd(verbose=False):
# Test that LassoLars and Lasso using coordinate descent give the
# same results.
X = 3 * diabetes.data
alphas, _, lasso_path = linear_model.lars_path(X, y, method='lasso')
lasso_cd = linear_model.Lasso(fit_intercept=False, tol=1e-8)
for c, a in zip(lasso_path.T, alphas):
if a == 0:
continue
lasso_cd.alpha = a
lasso_cd.fit(X, y)
error = linalg.norm(c - lasso_cd.coef_)
assert_less(error, 0.01)
# similar test, with the classifiers
for alpha in np.linspace(1e-2, 1 - 1e-2, 20):
clf1 = linear_model.LassoLars(alpha=alpha, normalize=False).fit(X, y)
clf2 = linear_model.Lasso(alpha=alpha, tol=1e-8,
normalize=False).fit(X, y)
err = linalg.norm(clf1.coef_ - clf2.coef_)
assert_less(err, 1e-3)
# same test, with normalized data
X = diabetes.data
alphas, _, lasso_path = linear_model.lars_path(X, y, method='lasso')
lasso_cd = linear_model.Lasso(fit_intercept=False, normalize=True,
tol=1e-8)
for c, a in zip(lasso_path.T, alphas):
if a == 0:
continue
lasso_cd.alpha = a
lasso_cd.fit(X, y)
error = linalg.norm(c - lasso_cd.coef_)
assert_less(error, 0.01)
def test_lasso_lars_vs_lasso_cd_early_stopping(verbose=False):
# Test that LassoLars and Lasso using coordinate descent give the
# same results when early stopping is used.
# (test : before, in the middle, and in the last part of the path)
alphas_min = [10, 0.9, 1e-4]
for alphas_min in alphas_min:
alphas, _, lasso_path = linear_model.lars_path(X, y, method='lasso',
alpha_min=0.9)
lasso_cd = linear_model.Lasso(fit_intercept=False, tol=1e-8)
lasso_cd.alpha = alphas[-1]
lasso_cd.fit(X, y)
error = linalg.norm(lasso_path[:, -1] - lasso_cd.coef_)
assert_less(error, 0.01)
alphas_min = [10, 0.9, 1e-4]
# same test, with normalization
for alphas_min in alphas_min:
alphas, _, lasso_path = linear_model.lars_path(X, y, method='lasso',
alpha_min=0.9)
lasso_cd = linear_model.Lasso(fit_intercept=True, normalize=True,
tol=1e-8)
lasso_cd.alpha = alphas[-1]
lasso_cd.fit(X, y)
error = linalg.norm(lasso_path[:, -1] - lasso_cd.coef_)
assert_less(error, 0.01)
def test_lasso_lars_path_length():
# Test that the path length of the LassoLars is right
lasso = linear_model.LassoLars()
lasso.fit(X, y)
lasso2 = linear_model.LassoLars(alpha=lasso.alphas_[2])
lasso2.fit(X, y)
assert_array_almost_equal(lasso.alphas_[:3], lasso2.alphas_)
# Also check that the sequence of alphas is always decreasing
assert_true(np.all(np.diff(lasso.alphas_) < 0))
def test_lasso_lars_vs_lasso_cd_ill_conditioned():
# Test lasso lars on a very ill-conditioned design, and check that
# it does not blow up, and stays somewhat close to a solution given
# by the coordinate descent solver
# Also test that lasso_path (using lars_path output style) gives
# the same result as lars_path and previous lasso output style
# under these conditions.
rng = np.random.RandomState(42)
# Generate data
n, m = 70, 100
k = 5
X = rng.randn(n, m)
w = np.zeros((m, 1))
i = np.arange(0, m)
rng.shuffle(i)
supp = i[:k]
w[supp] = np.sign(rng.randn(k, 1)) * (rng.rand(k, 1) + 1)
y = np.dot(X, w)
sigma = 0.2
y += sigma * rng.rand(*y.shape)
y = y.squeeze()
lars_alphas, _, lars_coef = linear_model.lars_path(X, y, method='lasso')
_, lasso_coef2, _ = linear_model.lasso_path(X, y,
alphas=lars_alphas,
tol=1e-6,
fit_intercept=False)
assert_array_almost_equal(lars_coef, lasso_coef2, decimal=1)
def test_lasso_lars_vs_lasso_cd_ill_conditioned2():
# Create an ill-conditioned situation in which the LARS has to go
# far in the path to converge, and check that LARS and coordinate
# descent give the same answers
# Note it used to be the case that Lars had to use the drop for good
# strategy for this but this is no longer the case with the
# equality_tolerance checks
X = [[1e20, 1e20, 0],
[-1e-32, 0, 0],
[1, 1, 1]]
y = [10, 10, 1]
alpha = .0001
def objective_function(coef):
return (1. / (2. * len(X)) * linalg.norm(y - np.dot(X, coef)) ** 2
+ alpha * linalg.norm(coef, 1))
lars = linear_model.LassoLars(alpha=alpha, normalize=False)
assert_warns(ConvergenceWarning, lars.fit, X, y)
lars_coef_ = lars.coef_
lars_obj = objective_function(lars_coef_)
coord_descent = linear_model.Lasso(alpha=alpha, tol=1e-4, normalize=False)
cd_coef_ = coord_descent.fit(X, y).coef_
cd_obj = objective_function(cd_coef_)
assert_less(lars_obj, cd_obj * (1. + 1e-8))
def test_lars_add_features():
# assure that at least some features get added if necessary
# test for 6d2b4c
# Hilbert matrix
n = 5
H = 1. / (np.arange(1, n + 1) + np.arange(n)[:, np.newaxis])
clf = linear_model.Lars(fit_intercept=False).fit(
H, np.arange(n))
assert_true(np.all(np.isfinite(clf.coef_)))
def test_lars_n_nonzero_coefs(verbose=False):
lars = linear_model.Lars(n_nonzero_coefs=6, verbose=verbose)
lars.fit(X, y)
assert_equal(len(lars.coef_.nonzero()[0]), 6)
# The path should be of length 6 + 1 in a Lars going down to 6
# non-zero coefs
assert_equal(len(lars.alphas_), 7)
@ignore_warnings
def test_multitarget():
# Assure that estimators receiving multidimensional y do the right thing
X = diabetes.data
Y = np.vstack([diabetes.target, diabetes.target ** 2]).T
n_targets = Y.shape[1]
for estimator in (linear_model.LassoLars(), linear_model.Lars()):
estimator.fit(X, Y)
Y_pred = estimator.predict(X)
Y_dec = assert_warns(DeprecationWarning, estimator.decision_function, X)
assert_array_almost_equal(Y_pred, Y_dec)
alphas, active, coef, path = (estimator.alphas_, estimator.active_,
estimator.coef_, estimator.coef_path_)
for k in range(n_targets):
estimator.fit(X, Y[:, k])
y_pred = estimator.predict(X)
assert_array_almost_equal(alphas[k], estimator.alphas_)
assert_array_almost_equal(active[k], estimator.active_)
assert_array_almost_equal(coef[k], estimator.coef_)
assert_array_almost_equal(path[k], estimator.coef_path_)
assert_array_almost_equal(Y_pred[:, k], y_pred)
def test_lars_cv():
# Test the LassoLarsCV object by checking that the optimal alpha
# increases as the number of samples increases.
# This property is not actually guaranteed in general and is just a
# property of the given dataset, with the given steps chosen.
old_alpha = 0
lars_cv = linear_model.LassoLarsCV()
for length in (400, 200, 100):
X = diabetes.data[:length]
y = diabetes.target[:length]
lars_cv.fit(X, y)
np.testing.assert_array_less(old_alpha, lars_cv.alpha_)
old_alpha = lars_cv.alpha_
def test_lasso_lars_ic():
# Test the LassoLarsIC object by checking that
# - some good features are selected.
# - alpha_bic > alpha_aic
# - n_nonzero_bic < n_nonzero_aic
lars_bic = linear_model.LassoLarsIC('bic')
lars_aic = linear_model.LassoLarsIC('aic')
rng = np.random.RandomState(42)
X = diabetes.data
y = diabetes.target
X = np.c_[X, rng.randn(X.shape[0], 4)] # add 4 bad features
lars_bic.fit(X, y)
lars_aic.fit(X, y)
nonzero_bic = np.where(lars_bic.coef_)[0]
nonzero_aic = np.where(lars_aic.coef_)[0]
assert_greater(lars_bic.alpha_, lars_aic.alpha_)
assert_less(len(nonzero_bic), len(nonzero_aic))
assert_less(np.max(nonzero_bic), diabetes.data.shape[1])
# test error on unknown IC
lars_broken = linear_model.LassoLarsIC('<unknown>')
assert_raises(ValueError, lars_broken.fit, X, y)
def test_no_warning_for_zero_mse():
# LassoLarsIC should not warn for log of zero MSE.
y = np.arange(10, dtype=float)
X = y.reshape(-1, 1)
lars = linear_model.LassoLarsIC(normalize=False)
assert_no_warnings(lars.fit, X, y)
assert_true(np.any(np.isinf(lars.criterion_)))
def test_lars_path_readonly_data():
# When using automated memory mapping on large input, the
# fold data is in read-only mode
# This is a non-regression test for:
# https://github.com/scikit-learn/scikit-learn/issues/4597
splitted_data = train_test_split(X, y, random_state=42)
with TempMemmap(splitted_data) as (X_train, X_test, y_train, y_test):
# The following should not fail despite copy=False
_lars_path_residues(X_train, y_train, X_test, y_test, copy=False)
def test_lars_path_positive_constraint():
# this is the main test for the positive parameter on the lars_path method
# the estimator classes just make use of this function
# we do the test on the diabetes dataset
# ensure that we get negative coefficients when positive=False
# and all positive when positive=True
# for method 'lar' (default) and lasso
for method in ['lar', 'lasso']:
alpha, active, coefs = \
linear_model.lars_path(diabetes['data'], diabetes['target'],
return_path=True, method=method,
positive=False)
assert_true(coefs.min() < 0)
alpha, active, coefs = \
linear_model.lars_path(diabetes['data'], diabetes['target'],
return_path=True, method=method,
positive=True)
assert_true(coefs.min() >= 0)
# now we gonna test the positive option for all estimator classes
default_parameter = {'fit_intercept': False}
estimator_parameter_map = {'Lars': {'n_nonzero_coefs': 5},
'LassoLars': {'alpha': 0.1},
'LarsCV': {},
'LassoLarsCV': {},
'LassoLarsIC': {}}
def test_estimatorclasses_positive_constraint():
# testing the transmissibility for the positive option of all estimator
# classes in this same function here
for estname in estimator_parameter_map:
params = default_parameter.copy()
params.update(estimator_parameter_map[estname])
estimator = getattr(linear_model, estname)(positive=False, **params)
estimator.fit(diabetes['data'], diabetes['target'])
assert_true(estimator.coef_.min() < 0)
estimator = getattr(linear_model, estname)(positive=True, **params)
estimator.fit(diabetes['data'], diabetes['target'])
assert_true(min(estimator.coef_) >= 0)
def test_lasso_lars_vs_lasso_cd_positive(verbose=False):
# Test that LassoLars and Lasso using coordinate descent give the
# same results when using the positive option
# This test is basically a copy of the above with additional positive
# option. However for the middle part, the comparison of coefficient values
# for a range of alphas, we had to make an adaptations. See below.
# not normalized data
X = 3 * diabetes.data
alphas, _, lasso_path = linear_model.lars_path(X, y, method='lasso',
positive=True)
lasso_cd = linear_model.Lasso(fit_intercept=False, tol=1e-8, positive=True)
for c, a in zip(lasso_path.T, alphas):
if a == 0:
continue
lasso_cd.alpha = a
lasso_cd.fit(X, y)
error = linalg.norm(c - lasso_cd.coef_)
assert_less(error, 0.01)
# The range of alphas chosen for coefficient comparison here is restricted
# as compared with the above test without the positive option. This is due
# to the circumstance that the Lars-Lasso algorithm does not converge to
# the least-squares-solution for small alphas, see 'Least Angle Regression'
# by Efron et al 2004. The coefficients are typically in congruence up to
# the smallest alpha reached by the Lars-Lasso algorithm and start to
# diverge thereafter. See
# https://gist.github.com/michigraber/7e7d7c75eca694c7a6ff
for alpha in np.linspace(6e-1, 1 - 1e-2, 20):
clf1 = linear_model.LassoLars(fit_intercept=False, alpha=alpha,
normalize=False, positive=True).fit(X, y)
clf2 = linear_model.Lasso(fit_intercept=False, alpha=alpha, tol=1e-8,
normalize=False, positive=True).fit(X, y)
err = linalg.norm(clf1.coef_ - clf2.coef_)
assert_less(err, 1e-3)
# normalized data
X = diabetes.data
alphas, _, lasso_path = linear_model.lars_path(X, y, method='lasso',
positive=True)
lasso_cd = linear_model.Lasso(fit_intercept=False, normalize=True,
tol=1e-8, positive=True)
for c, a in zip(lasso_path.T[:-1], alphas[:-1]): # don't include alpha=0
lasso_cd.alpha = a
lasso_cd.fit(X, y)
error = linalg.norm(c - lasso_cd.coef_)
assert_less(error, 0.01)
|
bsd-3-clause
|
adammenges/statsmodels
|
statsmodels/examples/tsa/ex_var.py
|
33
|
1280
|
from __future__ import print_function
import numpy as np
import statsmodels.api as sm
from statsmodels.tsa.api import VAR
# some example data
mdata = sm.datasets.macrodata.load().data
mdata = mdata[['realgdp','realcons','realinv']]
names = mdata.dtype.names
data = mdata.view((float,3))
use_growthrate = False #True #False
if use_growthrate:
data = 100 * 4 * np.diff(np.log(data), axis=0)
model = VAR(data, names=names)
res = model.fit(4)
nobs_all = data.shape[0]
#in-sample 1-step ahead forecasts
fc_in = np.array([np.squeeze(res.forecast(model.y[t-20:t], 1))
for t in range(nobs_all-6,nobs_all)])
print(fc_in - res.fittedvalues[-6:])
#out-of-sample 1-step ahead forecasts
fc_out = np.array([np.squeeze(VAR(data[:t]).fit(2).forecast(data[t-20:t], 1))
for t in range(nobs_all-6,nobs_all)])
print(fc_out - data[nobs_all-6:nobs_all])
print(fc_out - res.fittedvalues[-6:])
#out-of-sample h-step ahead forecasts
h = 2
fc_out = np.array([VAR(data[:t]).fit(2).forecast(data[t-20:t], h)[-1]
for t in range(nobs_all-6-h+1,nobs_all-h+1)])
print(fc_out - data[nobs_all-6:nobs_all]) #out-of-sample forecast error
print(fc_out - res.fittedvalues[-6:])
import matplotlib.pyplot as plt
res.plot_forecast(20)
#plt.show()
|
bsd-3-clause
|
iulian787/spack
|
var/spack/repos/builtin/packages/py-petastorm/package.py
|
5
|
1414
|
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class PyPetastorm(PythonPackage):
"""Petastorm is a library enabling the use of Parquet storage from
Tensorflow, Pytorch, and other Python-based ML training frameworks."""
homepage = "https://github.com/uber/petastorm"
url = "https://pypi.io/packages/source/p/petastorm/petastorm-0.8.2.tar.gz"
maintainers = ['adamjstewart']
version('0.8.2', sha256='7782c315e1ee8d15c7741e3eea41e77b9efce661cf58aa0220a801db64f52f91')
depends_on('py-setuptools', type='build')
depends_on('[email protected]:', type=('build', 'run'))
depends_on('[email protected]:', type=('build', 'run'))
depends_on('[email protected]:', type=('build', 'run'))
depends_on('[email protected]:', type=('build', 'run'), when='^python@:2')
depends_on('[email protected]:', type=('build', 'run'))
depends_on('[email protected]:', type=('build', 'run'))
depends_on('[email protected]:', type=('build', 'run'))
depends_on('[email protected]:', type=('build', 'run'))
depends_on('[email protected]:', type=('build', 'run'))
depends_on('[email protected]:', type=('build', 'run'))
depends_on('[email protected]:', type=('build', 'run'))
depends_on('[email protected]:', type=('build', 'run'))
|
lgpl-2.1
|
TissueMAPS/TmLibrary
|
tmlib/tools/aggregation.py
|
1
|
1470
|
# TmLibrary - TissueMAPS library for distibuted image analysis routines.
# Copyright (C) 2016 Markus D. Herrmann, University of Zurich and Robin Hafen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import numpy as np
import pandas as pd
import logging
import tmlib.models as tm
from tmlib.utils import same_docstring_as
from tmlib.tools.base import Tool
logger = logging.getLogger(__name__)
class Aggregation(Tool):
__icon__ = 'AGG'
__description__ = '''
Aggregates feature values of all mapobjects of a given type that
fall within larger mapobjects of a different type.
'''
@same_docstring_as(Tool.__init__)
def __init__(self, experiment_id):
super(Aggregation, self).__init__(experiment_id)
@same_docstring_as(Tool.process_request)
def process_request(self, submission_id, payload):
pass
|
agpl-3.0
|
ndingwall/scikit-learn
|
sklearn/feature_selection/tests/test_chi2.py
|
19
|
2987
|
"""
Tests for chi2, currently the only feature selection function designed
specifically to work with sparse matrices.
"""
import warnings
import numpy as np
import pytest
from scipy.sparse import coo_matrix, csr_matrix
import scipy.stats
from sklearn.feature_selection import SelectKBest, chi2
from sklearn.feature_selection._univariate_selection import _chisquare
from sklearn.utils._testing import assert_array_almost_equal
from sklearn.utils._testing import assert_array_equal
# Feature 0 is highly informative for class 1;
# feature 1 is the same everywhere;
# feature 2 is a bit informative for class 2.
X = [[2, 1, 2],
[9, 1, 1],
[6, 1, 2],
[0, 1, 2]]
y = [0, 1, 2, 2]
def mkchi2(k):
"""Make k-best chi2 selector"""
return SelectKBest(chi2, k=k)
def test_chi2():
# Test Chi2 feature extraction
chi2 = mkchi2(k=1).fit(X, y)
chi2 = mkchi2(k=1).fit(X, y)
assert_array_equal(chi2.get_support(indices=True), [0])
assert_array_equal(chi2.transform(X), np.array(X)[:, [0]])
chi2 = mkchi2(k=2).fit(X, y)
assert_array_equal(sorted(chi2.get_support(indices=True)), [0, 2])
Xsp = csr_matrix(X, dtype=np.float64)
chi2 = mkchi2(k=2).fit(Xsp, y)
assert_array_equal(sorted(chi2.get_support(indices=True)), [0, 2])
Xtrans = chi2.transform(Xsp)
assert_array_equal(Xtrans.shape, [Xsp.shape[0], 2])
# == doesn't work on scipy.sparse matrices
Xtrans = Xtrans.toarray()
Xtrans2 = mkchi2(k=2).fit_transform(Xsp, y).toarray()
assert_array_almost_equal(Xtrans, Xtrans2)
def test_chi2_coo():
# Check that chi2 works with a COO matrix
# (as returned by CountVectorizer, DictVectorizer)
Xcoo = coo_matrix(X)
mkchi2(k=2).fit_transform(Xcoo, y)
# if we got here without an exception, we're safe
def test_chi2_negative():
# Check for proper error on negative numbers in the input X.
X, y = [[0, 1], [-1e-20, 1]], [0, 1]
for X in (X, np.array(X), csr_matrix(X)):
with pytest.raises(ValueError):
chi2(X, y)
def test_chi2_unused_feature():
# Unused feature should evaluate to NaN
# and should issue no runtime warning
with warnings.catch_warnings(record=True) as warned:
warnings.simplefilter('always')
chi, p = chi2([[1, 0], [0, 0]], [1, 0])
for w in warned:
if 'divide by zero' in repr(w):
raise AssertionError('Found unexpected warning %s' % w)
assert_array_equal(chi, [1, np.nan])
assert_array_equal(p[1], np.nan)
def test_chisquare():
# Test replacement for scipy.stats.chisquare against the original.
obs = np.array([[2., 2.],
[1., 1.]])
exp = np.array([[1.5, 1.5],
[1.5, 1.5]])
# call SciPy first because our version overwrites obs
chi_scp, p_scp = scipy.stats.chisquare(obs, exp)
chi_our, p_our = _chisquare(obs, exp)
assert_array_almost_equal(chi_scp, chi_our)
assert_array_almost_equal(p_scp, p_our)
|
bsd-3-clause
|
neale/CS-program
|
434-MachineLearning/final_project/linearClassifier/sklearn/decomposition/nmf.py
|
6
|
46993
|
""" Non-negative matrix factorization
"""
# Author: Vlad Niculae
# Lars Buitinck
# Mathieu Blondel <[email protected]>
# Tom Dupre la Tour
# Author: Chih-Jen Lin, National Taiwan University (original projected gradient
# NMF implementation)
# Author: Anthony Di Franco (Projected gradient, Python and NumPy port)
# License: BSD 3 clause
from __future__ import division, print_function
from math import sqrt
import warnings
import numbers
import numpy as np
import scipy.sparse as sp
from ..externals import six
from ..base import BaseEstimator, TransformerMixin
from ..utils import check_random_state, check_array
from ..utils.extmath import randomized_svd, safe_sparse_dot, squared_norm
from ..utils.extmath import fast_dot
from ..utils.validation import check_is_fitted, check_non_negative
from ..utils import deprecated
from ..exceptions import ConvergenceWarning
from .cdnmf_fast import _update_cdnmf_fast
def safe_vstack(Xs):
if any(sp.issparse(X) for X in Xs):
return sp.vstack(Xs)
else:
return np.vstack(Xs)
def norm(x):
"""Dot product-based Euclidean norm implementation
See: http://fseoane.net/blog/2011/computing-the-vector-norm/
"""
return sqrt(squared_norm(x))
def trace_dot(X, Y):
"""Trace of np.dot(X, Y.T)."""
return np.dot(X.ravel(), Y.ravel())
def _sparseness(x):
"""Hoyer's measure of sparsity for a vector"""
sqrt_n = np.sqrt(len(x))
return (sqrt_n - np.linalg.norm(x, 1) / norm(x)) / (sqrt_n - 1)
def _check_init(A, shape, whom):
A = check_array(A)
if np.shape(A) != shape:
raise ValueError('Array with wrong shape passed to %s. Expected %s, '
'but got %s ' % (whom, shape, np.shape(A)))
check_non_negative(A, whom)
if np.max(A) == 0:
raise ValueError('Array passed to %s is full of zeros.' % whom)
def _safe_compute_error(X, W, H):
"""Frobenius norm between X and WH, safe for sparse array"""
if not sp.issparse(X):
error = norm(X - np.dot(W, H))
else:
norm_X = np.dot(X.data, X.data)
norm_WH = trace_dot(np.dot(np.dot(W.T, W), H), H)
cross_prod = trace_dot((X * H.T), W)
error = sqrt(norm_X + norm_WH - 2. * cross_prod)
return error
def _check_string_param(sparseness, solver):
allowed_sparseness = (None, 'data', 'components')
if sparseness not in allowed_sparseness:
raise ValueError(
'Invalid sparseness parameter: got %r instead of one of %r' %
(sparseness, allowed_sparseness))
allowed_solver = ('pg', 'cd')
if solver not in allowed_solver:
raise ValueError(
'Invalid solver parameter: got %r instead of one of %r' %
(solver, allowed_solver))
def _initialize_nmf(X, n_components, init=None, eps=1e-6,
random_state=None):
"""Algorithms for NMF initialization.
Computes an initial guess for the non-negative
rank k matrix approximation for X: X = WH
Parameters
----------
X : array-like, shape (n_samples, n_features)
The data matrix to be decomposed.
n_components : integer
The number of components desired in the approximation.
init : None | 'random' | 'nndsvd' | 'nndsvda' | 'nndsvdar'
Method used to initialize the procedure.
Default: 'nndsvdar' if n_components < n_features, otherwise 'random'.
Valid options:
- 'random': non-negative random matrices, scaled with:
sqrt(X.mean() / n_components)
- 'nndsvd': Nonnegative Double Singular Value Decomposition (NNDSVD)
initialization (better for sparseness)
- 'nndsvda': NNDSVD with zeros filled with the average of X
(better when sparsity is not desired)
- 'nndsvdar': NNDSVD with zeros filled with small random values
(generally faster, less accurate alternative to NNDSVDa
for when sparsity is not desired)
- 'custom': use custom matrices W and H
eps : float
Truncate all values less then this in output to zero.
random_state : int seed, RandomState instance, or None (default)
Random number generator seed control, used in 'nndsvdar' and
'random' modes.
Returns
-------
W : array-like, shape (n_samples, n_components)
Initial guesses for solving X ~= WH
H : array-like, shape (n_components, n_features)
Initial guesses for solving X ~= WH
References
----------
C. Boutsidis, E. Gallopoulos: SVD based initialization: A head start for
nonnegative matrix factorization - Pattern Recognition, 2008
http://tinyurl.com/nndsvd
"""
check_non_negative(X, "NMF initialization")
n_samples, n_features = X.shape
if init is None:
if n_components < n_features:
init = 'nndsvd'
else:
init = 'random'
# Random initialization
if init == 'random':
avg = np.sqrt(X.mean() / n_components)
rng = check_random_state(random_state)
H = avg * rng.randn(n_components, n_features)
W = avg * rng.randn(n_samples, n_components)
# we do not write np.abs(H, out=H) to stay compatible with
# numpy 1.5 and earlier where the 'out' keyword is not
# supported as a kwarg on ufuncs
np.abs(H, H)
np.abs(W, W)
return W, H
# NNDSVD initialization
U, S, V = randomized_svd(X, n_components, random_state=random_state)
W, H = np.zeros(U.shape), np.zeros(V.shape)
# The leading singular triplet is non-negative
# so it can be used as is for initialization.
W[:, 0] = np.sqrt(S[0]) * np.abs(U[:, 0])
H[0, :] = np.sqrt(S[0]) * np.abs(V[0, :])
for j in range(1, n_components):
x, y = U[:, j], V[j, :]
# extract positive and negative parts of column vectors
x_p, y_p = np.maximum(x, 0), np.maximum(y, 0)
x_n, y_n = np.abs(np.minimum(x, 0)), np.abs(np.minimum(y, 0))
# and their norms
x_p_nrm, y_p_nrm = norm(x_p), norm(y_p)
x_n_nrm, y_n_nrm = norm(x_n), norm(y_n)
m_p, m_n = x_p_nrm * y_p_nrm, x_n_nrm * y_n_nrm
# choose update
if m_p > m_n:
u = x_p / x_p_nrm
v = y_p / y_p_nrm
sigma = m_p
else:
u = x_n / x_n_nrm
v = y_n / y_n_nrm
sigma = m_n
lbd = np.sqrt(S[j] * sigma)
W[:, j] = lbd * u
H[j, :] = lbd * v
W[W < eps] = 0
H[H < eps] = 0
if init == "nndsvd":
pass
elif init == "nndsvda":
avg = X.mean()
W[W == 0] = avg
H[H == 0] = avg
elif init == "nndsvdar":
rng = check_random_state(random_state)
avg = X.mean()
W[W == 0] = abs(avg * rng.randn(len(W[W == 0])) / 100)
H[H == 0] = abs(avg * rng.randn(len(H[H == 0])) / 100)
else:
raise ValueError(
'Invalid init parameter: got %r instead of one of %r' %
(init, (None, 'random', 'nndsvd', 'nndsvda', 'nndsvdar')))
return W, H
def _nls_subproblem(V, W, H, tol, max_iter, alpha=0., l1_ratio=0.,
sigma=0.01, beta=0.1):
"""Non-negative least square solver
Solves a non-negative least squares subproblem using the projected
gradient descent algorithm.
Parameters
----------
V : array-like, shape (n_samples, n_features)
Constant matrix.
W : array-like, shape (n_samples, n_components)
Constant matrix.
H : array-like, shape (n_components, n_features)
Initial guess for the solution.
tol : float
Tolerance of the stopping condition.
max_iter : int
Maximum number of iterations before timing out.
alpha : double, default: 0.
Constant that multiplies the regularization terms. Set it to zero to
have no regularization.
l1_ratio : double, default: 0.
The regularization mixing parameter, with 0 <= l1_ratio <= 1.
For l1_ratio = 0 the penalty is an L2 penalty.
For l1_ratio = 1 it is an L1 penalty.
For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2.
sigma : float
Constant used in the sufficient decrease condition checked by the line
search. Smaller values lead to a looser sufficient decrease condition,
thus reducing the time taken by the line search, but potentially
increasing the number of iterations of the projected gradient
procedure. 0.01 is a commonly used value in the optimization
literature.
beta : float
Factor by which the step size is decreased (resp. increased) until
(resp. as long as) the sufficient decrease condition is satisfied.
Larger values allow to find a better step size but lead to longer line
search. 0.1 is a commonly used value in the optimization literature.
Returns
-------
H : array-like, shape (n_components, n_features)
Solution to the non-negative least squares problem.
grad : array-like, shape (n_components, n_features)
The gradient.
n_iter : int
The number of iterations done by the algorithm.
References
----------
C.-J. Lin. Projected gradient methods for non-negative matrix
factorization. Neural Computation, 19(2007), 2756-2779.
http://www.csie.ntu.edu.tw/~cjlin/nmf/
"""
WtV = safe_sparse_dot(W.T, V)
WtW = fast_dot(W.T, W)
# values justified in the paper (alpha is renamed gamma)
gamma = 1
for n_iter in range(1, max_iter + 1):
grad = np.dot(WtW, H) - WtV
if alpha > 0 and l1_ratio == 1.:
grad += alpha
elif alpha > 0:
grad += alpha * (l1_ratio + (1 - l1_ratio) * H)
# The following multiplication with a boolean array is more than twice
# as fast as indexing into grad.
if norm(grad * np.logical_or(grad < 0, H > 0)) < tol:
break
Hp = H
for inner_iter in range(20):
# Gradient step.
Hn = H - gamma * grad
# Projection step.
Hn *= Hn > 0
d = Hn - H
gradd = np.dot(grad.ravel(), d.ravel())
dQd = np.dot(np.dot(WtW, d).ravel(), d.ravel())
suff_decr = (1 - sigma) * gradd + 0.5 * dQd < 0
if inner_iter == 0:
decr_gamma = not suff_decr
if decr_gamma:
if suff_decr:
H = Hn
break
else:
gamma *= beta
elif not suff_decr or (Hp == Hn).all():
H = Hp
break
else:
gamma /= beta
Hp = Hn
if n_iter == max_iter:
warnings.warn("Iteration limit reached in nls subproblem.")
return H, grad, n_iter
def _update_projected_gradient_w(X, W, H, tolW, nls_max_iter, alpha, l1_ratio,
sparseness, beta, eta):
"""Helper function for _fit_projected_gradient"""
n_samples, n_features = X.shape
n_components_ = H.shape[0]
if sparseness is None:
Wt, gradW, iterW = _nls_subproblem(X.T, H.T, W.T, tolW, nls_max_iter,
alpha=alpha, l1_ratio=l1_ratio)
elif sparseness == 'data':
Wt, gradW, iterW = _nls_subproblem(
safe_vstack([X.T, np.zeros((1, n_samples))]),
safe_vstack([H.T, np.sqrt(beta) * np.ones((1,
n_components_))]),
W.T, tolW, nls_max_iter, alpha=alpha, l1_ratio=l1_ratio)
elif sparseness == 'components':
Wt, gradW, iterW = _nls_subproblem(
safe_vstack([X.T,
np.zeros((n_components_, n_samples))]),
safe_vstack([H.T,
np.sqrt(eta) * np.eye(n_components_)]),
W.T, tolW, nls_max_iter, alpha=alpha, l1_ratio=l1_ratio)
return Wt.T, gradW.T, iterW
def _update_projected_gradient_h(X, W, H, tolH, nls_max_iter, alpha, l1_ratio,
sparseness, beta, eta):
"""Helper function for _fit_projected_gradient"""
n_samples, n_features = X.shape
n_components_ = W.shape[1]
if sparseness is None:
H, gradH, iterH = _nls_subproblem(X, W, H, tolH, nls_max_iter,
alpha=alpha, l1_ratio=l1_ratio)
elif sparseness == 'data':
H, gradH, iterH = _nls_subproblem(
safe_vstack([X, np.zeros((n_components_, n_features))]),
safe_vstack([W,
np.sqrt(eta) * np.eye(n_components_)]),
H, tolH, nls_max_iter, alpha=alpha, l1_ratio=l1_ratio)
elif sparseness == 'components':
H, gradH, iterH = _nls_subproblem(
safe_vstack([X, np.zeros((1, n_features))]),
safe_vstack([W, np.sqrt(beta) * np.ones((1, n_components_))]),
H, tolH, nls_max_iter, alpha=alpha, l1_ratio=l1_ratio)
return H, gradH, iterH
def _fit_projected_gradient(X, W, H, tol, max_iter,
nls_max_iter, alpha, l1_ratio,
sparseness, beta, eta):
"""Compute Non-negative Matrix Factorization (NMF) with Projected Gradient
References
----------
C.-J. Lin. Projected gradient methods for non-negative matrix
factorization. Neural Computation, 19(2007), 2756-2779.
http://www.csie.ntu.edu.tw/~cjlin/nmf/
P. Hoyer. Non-negative Matrix Factorization with Sparseness Constraints.
Journal of Machine Learning Research 2004.
"""
gradW = (np.dot(W, np.dot(H, H.T)) -
safe_sparse_dot(X, H.T, dense_output=True))
gradH = (np.dot(np.dot(W.T, W), H) -
safe_sparse_dot(W.T, X, dense_output=True))
init_grad = squared_norm(gradW) + squared_norm(gradH.T)
# max(0.001, tol) to force alternating minimizations of W and H
tolW = max(0.001, tol) * np.sqrt(init_grad)
tolH = tolW
for n_iter in range(1, max_iter + 1):
# stopping condition
# as discussed in paper
proj_grad_W = squared_norm(gradW * np.logical_or(gradW < 0, W > 0))
proj_grad_H = squared_norm(gradH * np.logical_or(gradH < 0, H > 0))
if (proj_grad_W + proj_grad_H) / init_grad < tol ** 2:
break
# update W
W, gradW, iterW = _update_projected_gradient_w(X, W, H, tolW,
nls_max_iter,
alpha, l1_ratio,
sparseness, beta, eta)
if iterW == 1:
tolW = 0.1 * tolW
# update H
H, gradH, iterH = _update_projected_gradient_h(X, W, H, tolH,
nls_max_iter,
alpha, l1_ratio,
sparseness, beta, eta)
if iterH == 1:
tolH = 0.1 * tolH
H[H == 0] = 0 # fix up negative zeros
if n_iter == max_iter:
W, _, _ = _update_projected_gradient_w(X, W, H, tol, nls_max_iter,
alpha, l1_ratio, sparseness,
beta, eta)
return W, H, n_iter
def _update_coordinate_descent(X, W, Ht, l1_reg, l2_reg, shuffle,
random_state):
"""Helper function for _fit_coordinate_descent
Update W to minimize the objective function, iterating once over all
coordinates. By symmetry, to update H, one can call
_update_coordinate_descent(X.T, Ht, W, ...)
"""
n_components = Ht.shape[1]
HHt = fast_dot(Ht.T, Ht)
XHt = safe_sparse_dot(X, Ht)
# L2 regularization corresponds to increase of the diagonal of HHt
if l2_reg != 0.:
# adds l2_reg only on the diagonal
HHt.flat[::n_components + 1] += l2_reg
# L1 regularization corresponds to decrease of each element of XHt
if l1_reg != 0.:
XHt -= l1_reg
if shuffle:
permutation = random_state.permutation(n_components)
else:
permutation = np.arange(n_components)
# The following seems to be required on 64-bit Windows w/ Python 3.5.
permutation = np.asarray(permutation, dtype=np.intp)
return _update_cdnmf_fast(W, HHt, XHt, permutation)
def _fit_coordinate_descent(X, W, H, tol=1e-4, max_iter=200, alpha=0.001,
l1_ratio=0., regularization=None, update_H=True,
verbose=0, shuffle=False, random_state=None):
"""Compute Non-negative Matrix Factorization (NMF) with Coordinate Descent
The objective function is minimized with an alternating minimization of W
and H. Each minimization is done with a cyclic (up to a permutation of the
features) Coordinate Descent.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Constant matrix.
W : array-like, shape (n_samples, n_components)
Initial guess for the solution.
H : array-like, shape (n_components, n_features)
Initial guess for the solution.
tol : float, default: 1e-4
Tolerance of the stopping condition.
max_iter : integer, default: 200
Maximum number of iterations before timing out.
alpha : double, default: 0.
Constant that multiplies the regularization terms.
l1_ratio : double, default: 0.
The regularization mixing parameter, with 0 <= l1_ratio <= 1.
For l1_ratio = 0 the penalty is an L2 penalty.
For l1_ratio = 1 it is an L1 penalty.
For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2.
regularization : 'both' | 'components' | 'transformation' | None
Select whether the regularization affects the components (H), the
transformation (W), both or none of them.
update_H : boolean, default: True
Set to True, both W and H will be estimated from initial guesses.
Set to False, only W will be estimated.
verbose : integer, default: 0
The verbosity level.
shuffle : boolean, default: False
If true, randomize the order of coordinates in the CD solver.
random_state : integer seed, RandomState instance, or None (default)
Random number generator seed control.
Returns
-------
W : array-like, shape (n_samples, n_components)
Solution to the non-negative least squares problem.
H : array-like, shape (n_components, n_features)
Solution to the non-negative least squares problem.
n_iter : int
The number of iterations done by the algorithm.
References
----------
Cichocki, Andrzej, and P. H. A. N. Anh-Huy. "Fast local algorithms for
large scale nonnegative matrix and tensor factorizations."
IEICE transactions on fundamentals of electronics, communications and
computer sciences 92.3: 708-721, 2009.
"""
# so W and Ht are both in C order in memory
Ht = check_array(H.T, order='C')
X = check_array(X, accept_sparse='csr')
# L1 and L2 regularization
l1_H, l2_H, l1_W, l2_W = 0, 0, 0, 0
if regularization in ('both', 'components'):
alpha = float(alpha)
l1_H = l1_ratio * alpha
l2_H = (1. - l1_ratio) * alpha
if regularization in ('both', 'transformation'):
alpha = float(alpha)
l1_W = l1_ratio * alpha
l2_W = (1. - l1_ratio) * alpha
rng = check_random_state(random_state)
for n_iter in range(max_iter):
violation = 0.
# Update W
violation += _update_coordinate_descent(X, W, Ht, l1_W, l2_W,
shuffle, rng)
# Update H
if update_H:
violation += _update_coordinate_descent(X.T, Ht, W, l1_H, l2_H,
shuffle, rng)
if n_iter == 0:
violation_init = violation
if violation_init == 0:
break
if verbose:
print("violation:", violation / violation_init)
if violation / violation_init <= tol:
if verbose:
print("Converged at iteration", n_iter + 1)
break
return W, Ht.T, n_iter
def non_negative_factorization(X, W=None, H=None, n_components=None,
init='random', update_H=True, solver='cd',
tol=1e-4, max_iter=200, alpha=0., l1_ratio=0.,
regularization=None, random_state=None,
verbose=0, shuffle=False, nls_max_iter=2000,
sparseness=None, beta=1, eta=0.1):
"""Compute Non-negative Matrix Factorization (NMF)
Find two non-negative matrices (W, H) whose product approximates the non-
negative matrix X. This factorization can be used for example for
dimensionality reduction, source separation or topic extraction.
The objective function is::
0.5 * ||X - WH||_Fro^2
+ alpha * l1_ratio * ||vec(W)||_1
+ alpha * l1_ratio * ||vec(H)||_1
+ 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2
+ 0.5 * alpha * (1 - l1_ratio) * ||H||_Fro^2
Where::
||A||_Fro^2 = \sum_{i,j} A_{ij}^2 (Frobenius norm)
||vec(A)||_1 = \sum_{i,j} abs(A_{ij}) (Elementwise L1 norm)
The objective function is minimized with an alternating minimization of W
and H. If H is given and update_H=False, it solves for W only.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Constant matrix.
W : array-like, shape (n_samples, n_components)
If init='custom', it is used as initial guess for the solution.
H : array-like, shape (n_components, n_features)
If init='custom', it is used as initial guess for the solution.
If update_H=False, it is used as a constant, to solve for W only.
n_components : integer
Number of components, if n_components is not set all features
are kept.
init : None | 'random' | 'nndsvd' | 'nndsvda' | 'nndsvdar' | 'custom'
Method used to initialize the procedure.
Default: 'nndsvd' if n_components < n_features, otherwise random.
Valid options:
- 'random': non-negative random matrices, scaled with:
sqrt(X.mean() / n_components)
- 'nndsvd': Nonnegative Double Singular Value Decomposition (NNDSVD)
initialization (better for sparseness)
- 'nndsvda': NNDSVD with zeros filled with the average of X
(better when sparsity is not desired)
- 'nndsvdar': NNDSVD with zeros filled with small random values
(generally faster, less accurate alternative to NNDSVDa
for when sparsity is not desired)
- 'custom': use custom matrices W and H
update_H : boolean, default: True
Set to True, both W and H will be estimated from initial guesses.
Set to False, only W will be estimated.
solver : 'pg' | 'cd'
Numerical solver to use:
'pg' is a (deprecated) Projected Gradient solver.
'cd' is a Coordinate Descent solver.
tol : float, default: 1e-4
Tolerance of the stopping condition.
max_iter : integer, default: 200
Maximum number of iterations before timing out.
alpha : double, default: 0.
Constant that multiplies the regularization terms.
l1_ratio : double, default: 0.
The regularization mixing parameter, with 0 <= l1_ratio <= 1.
For l1_ratio = 0 the penalty is an elementwise L2 penalty
(aka Frobenius Norm).
For l1_ratio = 1 it is an elementwise L1 penalty.
For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2.
regularization : 'both' | 'components' | 'transformation' | None
Select whether the regularization affects the components (H), the
transformation (W), both or none of them.
random_state : integer seed, RandomState instance, or None (default)
Random number generator seed control.
verbose : integer, default: 0
The verbosity level.
shuffle : boolean, default: False
If true, randomize the order of coordinates in the CD solver.
nls_max_iter : integer, default: 2000
Number of iterations in NLS subproblem.
Used only in the deprecated 'pg' solver.
sparseness : 'data' | 'components' | None, default: None
Where to enforce sparsity in the model.
Used only in the deprecated 'pg' solver.
beta : double, default: 1
Degree of sparseness, if sparseness is not None. Larger values mean
more sparseness. Used only in the deprecated 'pg' solver.
eta : double, default: 0.1
Degree of correctness to maintain, if sparsity is not None. Smaller
values mean larger error. Used only in the deprecated 'pg' solver.
Returns
-------
W : array-like, shape (n_samples, n_components)
Solution to the non-negative least squares problem.
H : array-like, shape (n_components, n_features)
Solution to the non-negative least squares problem.
n_iter : int
Actual number of iterations.
References
----------
C.-J. Lin. Projected gradient methods for non-negative matrix
factorization. Neural Computation, 19(2007), 2756-2779.
http://www.csie.ntu.edu.tw/~cjlin/nmf/
Cichocki, Andrzej, and P. H. A. N. Anh-Huy. "Fast local algorithms for
large scale nonnegative matrix and tensor factorizations."
IEICE transactions on fundamentals of electronics, communications and
computer sciences 92.3: 708-721, 2009.
"""
X = check_array(X, accept_sparse=('csr', 'csc'))
check_non_negative(X, "NMF (input X)")
_check_string_param(sparseness, solver)
n_samples, n_features = X.shape
if n_components is None:
n_components = n_features
if not isinstance(n_components, six.integer_types) or n_components <= 0:
raise ValueError("Number of components must be positive;"
" got (n_components=%r)" % n_components)
if not isinstance(max_iter, numbers.Number) or max_iter < 0:
raise ValueError("Maximum number of iteration must be positive;"
" got (max_iter=%r)" % max_iter)
if not isinstance(tol, numbers.Number) or tol < 0:
raise ValueError("Tolerance for stopping criteria must be "
"positive; got (tol=%r)" % tol)
# check W and H, or initialize them
if init == 'custom' and update_H:
_check_init(H, (n_components, n_features), "NMF (input H)")
_check_init(W, (n_samples, n_components), "NMF (input W)")
elif not update_H:
_check_init(H, (n_components, n_features), "NMF (input H)")
W = np.zeros((n_samples, n_components))
else:
W, H = _initialize_nmf(X, n_components, init=init,
random_state=random_state)
if solver == 'pg':
warnings.warn("'pg' solver will be removed in release 0.19."
" Use 'cd' solver instead.", DeprecationWarning)
if update_H: # fit_transform
W, H, n_iter = _fit_projected_gradient(X, W, H, tol,
max_iter,
nls_max_iter,
alpha, l1_ratio,
sparseness,
beta, eta)
else: # transform
W, H, n_iter = _update_projected_gradient_w(X, W, H,
tol, nls_max_iter,
alpha, l1_ratio,
sparseness, beta,
eta)
elif solver == 'cd':
W, H, n_iter = _fit_coordinate_descent(X, W, H, tol,
max_iter,
alpha, l1_ratio,
regularization,
update_H=update_H,
verbose=verbose,
shuffle=shuffle,
random_state=random_state)
else:
raise ValueError("Invalid solver parameter '%s'." % solver)
if n_iter == max_iter:
warnings.warn("Maximum number of iteration %d reached. Increase it to"
" improve convergence." % max_iter, ConvergenceWarning)
return W, H, n_iter
class NMF(BaseEstimator, TransformerMixin):
"""Non-Negative Matrix Factorization (NMF)
Find two non-negative matrices (W, H) whose product approximates the non-
negative matrix X. This factorization can be used for example for
dimensionality reduction, source separation or topic extraction.
The objective function is::
0.5 * ||X - WH||_Fro^2
+ alpha * l1_ratio * ||vec(W)||_1
+ alpha * l1_ratio * ||vec(H)||_1
+ 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2
+ 0.5 * alpha * (1 - l1_ratio) * ||H||_Fro^2
Where::
||A||_Fro^2 = \sum_{i,j} A_{ij}^2 (Frobenius norm)
||vec(A)||_1 = \sum_{i,j} abs(A_{ij}) (Elementwise L1 norm)
The objective function is minimized with an alternating minimization of W
and H.
Read more in the :ref:`User Guide <NMF>`.
Parameters
----------
n_components : int or None
Number of components, if n_components is not set all features
are kept.
init : 'random' | 'nndsvd' | 'nndsvda' | 'nndsvdar' | 'custom'
Method used to initialize the procedure.
Default: 'nndsvdar' if n_components < n_features, otherwise random.
Valid options:
- 'random': non-negative random matrices, scaled with:
sqrt(X.mean() / n_components)
- 'nndsvd': Nonnegative Double Singular Value Decomposition (NNDSVD)
initialization (better for sparseness)
- 'nndsvda': NNDSVD with zeros filled with the average of X
(better when sparsity is not desired)
- 'nndsvdar': NNDSVD with zeros filled with small random values
(generally faster, less accurate alternative to NNDSVDa
for when sparsity is not desired)
- 'custom': use custom matrices W and H
solver : 'pg' | 'cd'
Numerical solver to use:
'pg' is a Projected Gradient solver (deprecated).
'cd' is a Coordinate Descent solver (recommended).
.. versionadded:: 0.17
Coordinate Descent solver.
.. versionchanged:: 0.17
Deprecated Projected Gradient solver.
tol : double, default: 1e-4
Tolerance value used in stopping conditions.
max_iter : integer, default: 200
Number of iterations to compute.
random_state : integer seed, RandomState instance, or None (default)
Random number generator seed control.
alpha : double, default: 0.
Constant that multiplies the regularization terms. Set it to zero to
have no regularization.
.. versionadded:: 0.17
*alpha* used in the Coordinate Descent solver.
l1_ratio : double, default: 0.
The regularization mixing parameter, with 0 <= l1_ratio <= 1.
For l1_ratio = 0 the penalty is an elementwise L2 penalty
(aka Frobenius Norm).
For l1_ratio = 1 it is an elementwise L1 penalty.
For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2.
.. versionadded:: 0.17
Regularization parameter *l1_ratio* used in the Coordinate Descent
solver.
shuffle : boolean, default: False
If true, randomize the order of coordinates in the CD solver.
.. versionadded:: 0.17
*shuffle* parameter used in the Coordinate Descent solver.
nls_max_iter : integer, default: 2000
Number of iterations in NLS subproblem.
Used only in the deprecated 'pg' solver.
.. versionchanged:: 0.17
Deprecated Projected Gradient solver. Use Coordinate Descent solver
instead.
sparseness : 'data' | 'components' | None, default: None
Where to enforce sparsity in the model.
Used only in the deprecated 'pg' solver.
.. versionchanged:: 0.17
Deprecated Projected Gradient solver. Use Coordinate Descent solver
instead.
beta : double, default: 1
Degree of sparseness, if sparseness is not None. Larger values mean
more sparseness. Used only in the deprecated 'pg' solver.
.. versionchanged:: 0.17
Deprecated Projected Gradient solver. Use Coordinate Descent solver
instead.
eta : double, default: 0.1
Degree of correctness to maintain, if sparsity is not None. Smaller
values mean larger error. Used only in the deprecated 'pg' solver.
.. versionchanged:: 0.17
Deprecated Projected Gradient solver. Use Coordinate Descent solver
instead.
Attributes
----------
components_ : array, [n_components, n_features]
Non-negative components of the data.
reconstruction_err_ : number
Frobenius norm of the matrix difference between
the training data and the reconstructed data from
the fit produced by the model. ``|| X - WH ||_2``
n_iter_ : int
Actual number of iterations.
Examples
--------
>>> import numpy as np
>>> X = np.array([[1,1], [2, 1], [3, 1.2], [4, 1], [5, 0.8], [6, 1]])
>>> from sklearn.decomposition import NMF
>>> model = NMF(n_components=2, init='random', random_state=0)
>>> model.fit(X) #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
NMF(alpha=0.0, beta=1, eta=0.1, init='random', l1_ratio=0.0, max_iter=200,
n_components=2, nls_max_iter=2000, random_state=0, shuffle=False,
solver='cd', sparseness=None, tol=0.0001, verbose=0)
>>> model.components_
array([[ 2.09783018, 0.30560234],
[ 2.13443044, 2.13171694]])
>>> model.reconstruction_err_ #doctest: +ELLIPSIS
0.00115993...
References
----------
C.-J. Lin. Projected gradient methods for non-negative matrix
factorization. Neural Computation, 19(2007), 2756-2779.
http://www.csie.ntu.edu.tw/~cjlin/nmf/
Cichocki, Andrzej, and P. H. A. N. Anh-Huy. "Fast local algorithms for
large scale nonnegative matrix and tensor factorizations."
IEICE transactions on fundamentals of electronics, communications and
computer sciences 92.3: 708-721, 2009.
"""
def __init__(self, n_components=None, init=None, solver='cd',
tol=1e-4, max_iter=200, random_state=None,
alpha=0., l1_ratio=0., verbose=0, shuffle=False,
nls_max_iter=2000, sparseness=None, beta=1, eta=0.1):
self.n_components = n_components
self.init = init
self.solver = solver
self.tol = tol
self.max_iter = max_iter
self.random_state = random_state
self.alpha = alpha
self.l1_ratio = l1_ratio
self.verbose = verbose
self.shuffle = shuffle
if sparseness is not None:
warnings.warn("Controlling regularization through the sparseness,"
" beta and eta arguments is only available"
" for 'pg' solver, which will be removed"
" in release 0.19. Use another solver with L1 or L2"
" regularization instead.", DeprecationWarning)
self.nls_max_iter = nls_max_iter
self.sparseness = sparseness
self.beta = beta
self.eta = eta
def fit_transform(self, X, y=None, W=None, H=None):
"""Learn a NMF model for the data X and returns the transformed data.
This is more efficient than calling fit followed by transform.
Parameters
----------
X: {array-like, sparse matrix}, shape (n_samples, n_features)
Data matrix to be decomposed
W : array-like, shape (n_samples, n_components)
If init='custom', it is used as initial guess for the solution.
H : array-like, shape (n_components, n_features)
If init='custom', it is used as initial guess for the solution.
Attributes
----------
components_ : array-like, shape (n_components, n_features)
Factorization matrix, sometimes called 'dictionary'.
n_iter_ : int
Actual number of iterations for the transform.
Returns
-------
W: array, shape (n_samples, n_components)
Transformed data.
"""
X = check_array(X, accept_sparse=('csr', 'csc'))
W, H, n_iter_ = non_negative_factorization(
X=X, W=W, H=H, n_components=self.n_components,
init=self.init, update_H=True, solver=self.solver,
tol=self.tol, max_iter=self.max_iter, alpha=self.alpha,
l1_ratio=self.l1_ratio, regularization='both',
random_state=self.random_state, verbose=self.verbose,
shuffle=self.shuffle,
nls_max_iter=self.nls_max_iter, sparseness=self.sparseness,
beta=self.beta, eta=self.eta)
if self.solver == 'pg':
self.comp_sparseness_ = _sparseness(H.ravel())
self.data_sparseness_ = _sparseness(W.ravel())
self.reconstruction_err_ = _safe_compute_error(X, W, H)
self.n_components_ = H.shape[0]
self.components_ = H
self.n_iter_ = n_iter_
return W
def fit(self, X, y=None, **params):
"""Learn a NMF model for the data X.
Parameters
----------
X: {array-like, sparse matrix}, shape (n_samples, n_features)
Data matrix to be decomposed
Attributes
----------
components_ : array-like, shape (n_components, n_features)
Factorization matrix, sometimes called 'dictionary'.
n_iter_ : int
Actual number of iterations for the transform.
Returns
-------
self
"""
self.fit_transform(X, **params)
return self
def transform(self, X):
"""Transform the data X according to the fitted NMF model
Parameters
----------
X: {array-like, sparse matrix}, shape (n_samples, n_features)
Data matrix to be transformed by the model
Attributes
----------
n_iter_ : int
Actual number of iterations for the transform.
Returns
-------
W: array, shape (n_samples, n_components)
Transformed data
"""
check_is_fitted(self, 'n_components_')
W, _, n_iter_ = non_negative_factorization(
X=X, W=None, H=self.components_, n_components=self.n_components_,
init=self.init, update_H=False, solver=self.solver,
tol=self.tol, max_iter=self.max_iter, alpha=self.alpha,
l1_ratio=self.l1_ratio, regularization='both',
random_state=self.random_state, verbose=self.verbose,
shuffle=self.shuffle,
nls_max_iter=self.nls_max_iter, sparseness=self.sparseness,
beta=self.beta, eta=self.eta)
self.n_iter_ = n_iter_
return W
def inverse_transform(self, W):
"""
Parameters
----------
W: {array-like, sparse matrix}, shape (n_samples, n_components)
Transformed Data matrix
Returns
-------
X: {array-like, sparse matrix}, shape (n_samples, n_features)
Data matrix of original shape
.. versionadded:: 0.18
"""
check_is_fitted(self, 'n_components_')
return np.dot(W, self.components_)
@deprecated("It will be removed in release 0.19. Use NMF instead."
"'pg' solver is still available until release 0.19.")
class ProjectedGradientNMF(NMF):
"""Non-Negative Matrix Factorization (NMF)
Find two non-negative matrices (W, H) whose product approximates the non-
negative matrix X. This factorization can be used for example for
dimensionality reduction, source separation or topic extraction.
The objective function is::
0.5 * ||X - WH||_Fro^2
+ alpha * l1_ratio * ||vec(W)||_1
+ alpha * l1_ratio * ||vec(H)||_1
+ 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2
+ 0.5 * alpha * (1 - l1_ratio) * ||H||_Fro^2
Where::
||A||_Fro^2 = \sum_{i,j} A_{ij}^2 (Frobenius norm)
||vec(A)||_1 = \sum_{i,j} abs(A_{ij}) (Elementwise L1 norm)
The objective function is minimized with an alternating minimization of W
and H.
Read more in the :ref:`User Guide <NMF>`.
Parameters
----------
n_components : int or None
Number of components, if n_components is not set all features
are kept.
init : 'random' | 'nndsvd' | 'nndsvda' | 'nndsvdar' | 'custom'
Method used to initialize the procedure.
Default: 'nndsvdar' if n_components < n_features, otherwise random.
Valid options:
- 'random': non-negative random matrices, scaled with:
sqrt(X.mean() / n_components)
- 'nndsvd': Nonnegative Double Singular Value Decomposition (NNDSVD)
initialization (better for sparseness)
- 'nndsvda': NNDSVD with zeros filled with the average of X
(better when sparsity is not desired)
- 'nndsvdar': NNDSVD with zeros filled with small random values
(generally faster, less accurate alternative to NNDSVDa
for when sparsity is not desired)
- 'custom': use custom matrices W and H
solver : 'pg' | 'cd'
Numerical solver to use:
'pg' is a Projected Gradient solver (deprecated).
'cd' is a Coordinate Descent solver (recommended).
.. versionadded:: 0.17
Coordinate Descent solver.
.. versionchanged:: 0.17
Deprecated Projected Gradient solver.
tol : double, default: 1e-4
Tolerance value used in stopping conditions.
max_iter : integer, default: 200
Number of iterations to compute.
random_state : integer seed, RandomState instance, or None (default)
Random number generator seed control.
alpha : double, default: 0.
Constant that multiplies the regularization terms. Set it to zero to
have no regularization.
.. versionadded:: 0.17
*alpha* used in the Coordinate Descent solver.
l1_ratio : double, default: 0.
The regularization mixing parameter, with 0 <= l1_ratio <= 1.
For l1_ratio = 0 the penalty is an elementwise L2 penalty
(aka Frobenius Norm).
For l1_ratio = 1 it is an elementwise L1 penalty.
For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2.
.. versionadded:: 0.17
Regularization parameter *l1_ratio* used in the Coordinate Descent
solver.
shuffle : boolean, default: False
If true, randomize the order of coordinates in the CD solver.
.. versionadded:: 0.17
*shuffle* parameter used in the Coordinate Descent solver.
nls_max_iter : integer, default: 2000
Number of iterations in NLS subproblem.
Used only in the deprecated 'pg' solver.
.. versionchanged:: 0.17
Deprecated Projected Gradient solver. Use Coordinate Descent solver
instead.
sparseness : 'data' | 'components' | None, default: None
Where to enforce sparsity in the model.
Used only in the deprecated 'pg' solver.
.. versionchanged:: 0.17
Deprecated Projected Gradient solver. Use Coordinate Descent solver
instead.
beta : double, default: 1
Degree of sparseness, if sparseness is not None. Larger values mean
more sparseness. Used only in the deprecated 'pg' solver.
.. versionchanged:: 0.17
Deprecated Projected Gradient solver. Use Coordinate Descent solver
instead.
eta : double, default: 0.1
Degree of correctness to maintain, if sparsity is not None. Smaller
values mean larger error. Used only in the deprecated 'pg' solver.
.. versionchanged:: 0.17
Deprecated Projected Gradient solver. Use Coordinate Descent solver
instead.
Attributes
----------
components_ : array, [n_components, n_features]
Non-negative components of the data.
reconstruction_err_ : number
Frobenius norm of the matrix difference between
the training data and the reconstructed data from
the fit produced by the model. ``|| X - WH ||_2``
n_iter_ : int
Actual number of iterations.
Examples
--------
>>> import numpy as np
>>> X = np.array([[1,1], [2, 1], [3, 1.2], [4, 1], [5, 0.8], [6, 1]])
>>> from sklearn.decomposition import NMF
>>> model = NMF(n_components=2, init='random', random_state=0)
>>> model.fit(X) #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
NMF(alpha=0.0, beta=1, eta=0.1, init='random', l1_ratio=0.0, max_iter=200,
n_components=2, nls_max_iter=2000, random_state=0, shuffle=False,
solver='cd', sparseness=None, tol=0.0001, verbose=0)
>>> model.components_
array([[ 2.09783018, 0.30560234],
[ 2.13443044, 2.13171694]])
>>> model.reconstruction_err_ #doctest: +ELLIPSIS
0.00115993...
References
----------
C.-J. Lin. Projected gradient methods for non-negative matrix
factorization. Neural Computation, 19(2007), 2756-2779.
http://www.csie.ntu.edu.tw/~cjlin/nmf/
Cichocki, Andrzej, and P. H. A. N. Anh-Huy. "Fast local algorithms for
large scale nonnegative matrix and tensor factorizations."
IEICE transactions on fundamentals of electronics, communications and
computer sciences 92.3: 708-721, 2009.
"""
def __init__(self, n_components=None, solver='pg', init=None,
tol=1e-4, max_iter=200, random_state=None,
alpha=0., l1_ratio=0., verbose=0,
nls_max_iter=2000, sparseness=None, beta=1, eta=0.1):
super(ProjectedGradientNMF, self).__init__(
n_components=n_components, init=init, solver='pg', tol=tol,
max_iter=max_iter, random_state=random_state, alpha=alpha,
l1_ratio=l1_ratio, verbose=verbose, nls_max_iter=nls_max_iter,
sparseness=sparseness, beta=beta, eta=eta)
|
unlicense
|
fruce-ki/utility_scripts
|
archive/mutpe/fileutilities.py
|
1
|
68356
|
#!/usr/bin/env python3
"""fileutilities.py
Author: Kimon Froussios
Compatibility tested: python 3.5.2
Last reviewed: 10/05/2019
This module is a solution for Frequently Performed Generic Tasks that involve
multiple files:
* repeating a command for a range of files (not currently parallelized),
* accessing and restructuring (multiple) delimited files.
* miscellaneous stuff. Some of it is auxiliary to the primary functions, some
is a legacy of this module's evolution of concept.
The module provides a library of flexible functions as
well as a main() implementing the primary use scenarios.
Execute with -h in a shell to obtain syntax and help.
"""
# This module consists of:
# - a class for handling lists of files,
# - a library of functions that perform generic tasks on multiple files, and
# - a main that provides access to most of the above functionality
# NOTE about DataFrame indexes and headers:
# Although dataframes support row and column labels, these make content manipulations
# in the context of this module harder. Instead, any labels present in the text
# input are treated as plain rows or columns. These may be optionally dropped or
# preserved, but the dataframe in-built labels for columns and rows are reserved
# solely for custom use. When appropriate these custom labels will be included in
# the output.
import os, sys, string, re, subprocess, random, argparse
import pandas as pd
from builtins import list
from collections import Counter
import mylogs as ml
##### F U N C T I O N S #####
# http://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort
def natural_sorted(l):
"""Sort list of numbers/strings in human-friendly order.
Args:
l(list): A list of strings.
Returns:
list
"""
convert = lambda text: int(text) if text.isdigit() else text.lower()
alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
return sorted(l, key = alphanum_key)
def expand_fpaths(flist):
"""Fully expand and absolute-ify the paths of listed files.
Does not verify path validity. All paths are expanded.
Args:
flist[str]: A list/FilesList of files.
Returns:
[str]: List of expanded paths.
"""
return [os.path.abspath(os.path.expanduser(str(f))) for f in flist]
# Helper function, string check.
def istext(s):
"""Check if a string is (probably) text.
Use heuristic based on characters contained in the string, adapted from:
http://code.activestate.com/recipes/173220-test-if-a-file-or-string-is-text-or-binary/
Args:
s(str): A string to test.
Returns:
bool
"""
# Copy-pasted. No idea what the code means.
text_characters = "".join(list(map(chr, list(range(32, 127)))) + list("\n\r\t\b"))
_null_trans = string.maketrans("", "")
if "\0" in s:
return False
if not s: # Empty files/strings are considered text
return True
# Get the non-text characters (maps a character to itself then
# use the 'remove' option to get rid of the text characters.)
t = s.translate(_null_trans, text_characters)
# If more than 30% non-text characters, then
# this is considered a binary file
if float(len(t))/float(len(s)) > 0.30:
return False
return True
def slink(flist, aliases=None, dir="./", autoext=True):
"""Create symbolic links for multiple files.
Create a link for each of the listed paths into the specified directory,
using the specified aliases. Items in the lists will be matched one for
one.
If the aliases argument is omitted, the names for the links will be drawn
from the aliases attribute of the paths list, if it is a FilesList object.
If no aliases exist in either form, the files will be linked in the current
or specified directory, using names their current basename.
If linking to files of the same name located in different directories, a
number will be automatically suffixed to the basename.
Args:
flist[str]: A list/FilesList of paths to link to.
aliases[str]: A list of respective names for the created links. If
omitted, the alias attribute of the flist argument will be
used, and failing that, the existing basenames will be used.
dir(str): The path to the directory in which the links should be
placed. (Default "./")
autoext(bool): Add the file extensions to the created links, if the
links are created from aliases that lack them.
(Default True)
"""
if not aliases:
# No link names provided. Try to find them elsewhere or create them.
try:
# flist is a FilesList and has the aliases attribute.
aliases = flist.aliases
except AttributeError:
# flist is a plain list, so compute the link name from the file name.
aliases = [os.path.basename(p) for p in flist]
# Check for duplicate aliases and amend them.
# This applies mainly to link names automatically created from filenames, as
# the same file name can exist in different directories.
if len(set(aliases)) < len(flist):
aliases = autonumerate(aliases)
# Add extensions where necessary, if desired.
if autoext:
for i in range(0, len(flist)):
(b, p) = os.path.splitext(flist[i])
c = p
# If it's a .gz, include the next nested extension as well.
if p == ".gz":
p = os.path.splitext(b)[1] + p
# Don't duplicate the extension if the alias already has it.
a = os.path.splitext(aliases[i])[1]
if c != a:
aliases[i] = aliases[i] + p
# Link.
for i, mypath in enumerate(flist):
os.symlink(mypath, os.path.join(dir, aliases[i]))
# Helper function.
def autonumerate(things):
"""Detect duplicate entries in a string list and suffix them.
Suffixes are in _N format where N a natural number >=2. Existing suffixes
in that format will also be detected and incremented.
Args:
things[str]: A list of strings.
Returns:
[str]: A corrected list of strings.
"""
c = Counter(things);
# Because I use decrement, reversing the list ensures first instance gets smallest number.
things.reverse()
for i, t in enumerate(things):
n = c[t]
if n > 1: # The first occurrence is not suffixed.
newname = t +'_' + str(n)
while newname in things: # Check for already present suffixes
n += 1
newname = t +'_' + str(n)
things[i] = newname
c[t] -= 1
things.reverse()
return things
def make_names(items, parameters):
"""Automatically create file names based on parameters.
If automatic names happen to turn out identical with one another, unique
numbers are appended to differentiate them. Check documentation for
autonumerate().
Args:
items[str]: A list of strings/filenames/paths to use as the basis for
the output names.
parameters(str,str,str): The first element is the output directory,
the second is a common prefix to add to the names,
the third is a common suffix to add to the names.
Like so: <out[0]>/<out[1]>item<out[2] .
If any of the 3 values in None, no outnames will be made.
Use current directory and empty strings as necessary.
Returns:
[str]: A list of file paths.
"""
outfiles = []
if None not in parameters:
for i in items:
outfiles.append(os.path.join(os.path.abspath(os.path.expanduser(parameters[0])),
parameters[1] + i + parameters[2]) )
autonumerate(outfiles)
return outfiles
def do_foreach(flist, comm, progress=True, out=(None,None,None), log=False):
"""Execute an arbitrary command for each of the listed files.
Enables executing a shell command over a range of items, by inserting the
item values into the command as directed by place-holder substrings.
Although the above is how it is meant to be used, the values in the
FilesList could be overridden to be any arbitrary string, in which case,
only {val} will have the desired effect. The other placeholder values are
computed with the assumption of the values being files, so may not be
sensible when the items are not files.
This is the only function with comments or progress attributes, because
invoked commands print their own output directly, so any informative messages
controlled by this library will need to be inserted in real time.
Args:
flist[]: A FilesList.
comm[str]: The components of an arbitrary command, with place-holders:
{abs} : absolute path of file.
{dir} : absolute path of the file's directory.
{val} : the actual value specified as target
{bas} : the basename of the file, without the last extension.
{alias}: the alias for the file, if iterating through a FilesList.
Placeholders can be nested, to allow nested calls of fileutilities:
i.e. {{abs}}. A layer of nesting is peeled off each time the function is called,
until the placeholders are allowed to be evaluated.
progress(bool): Show start and completion of iterations on STDERR.
(Default True)
out(str,str,str): The first element is the output directory, the second
is a common prefix to add to the names, the third is a
common suffix to add to the names. Check documentation for
make_names().
log(bool): Log to /commands.log each individual call.
"""
outstream= sys.stdout
# Create output files. [] if out contains None.
outfiles = make_names(flist, out)
for i, (myfile, myalias) in flist.enum():
# Substitute place-holders.
command = []
for c in comm:
# Evaluate placeholders, if they are not nested.
(mypath, mybase) = os.path.split(str(myfile))
c = re.sub(r"(?<!\{){abs}(?!\})", str(myfile), c)
c = re.sub(r"(?<!\{){dir}(?!\})", mypath, c)
c = re.sub(r"(?<!\{){val}(?!\})", mybase, c)
c = re.sub(r"(?<!\{){bas}(?!\})", os.path.splitext(mybase)[0], c)
c = re.sub(r"(?<!\{){ali}(?!\})", str(myalias), c)
# Peel off a layer of nesting for the remaining placeholders and flags.
c = c.replace('{{abs}}', '{abs}')
c = c.replace('{{dir}}', '{dir}')
c = c.replace('{{val}}', '{val}')
c = c.replace('{{bas}}', '{bas}')
c = c.replace('{{ali}}', '{ali}')
c = c.replace(',-', '-')
# This argument is ready to go now.
command.append(c)
# Redirect output.
if outfiles:
outstream = open(outfiles[i], 'w')
# Verbose stuff.
see = " ".join(command)
if log:
ml.log_message(message=see, logfile="./commands.log")
if progress:
sys.stderr.write(ml.infostring("DO: "+ see))
# Do the thing.
subprocess.call(" ".join(command), stdout=outstream, shell=True)
# More verbose stuff.
if progress:
sys.stderr.write(ml.infostring("Finished: "+ str(myalias) +"\n"))
if outfiles:
outstream.close()
def swap_strFiles(flist, insep=[","], outsep="\t"):
"""Replace the column separator with a different one.
Supports multiple different delimiters in the input, to support one-step
uniformity when the input files have different delimiters, but ALL input
will be split at ALL/ANY occurring delimiters. If the delimiter of one
file is present in a different use in an other file, the output may not
be what you want.
Although made for converting delimited text, inseps and outsep could be any
substring in a text, delimited or not.
Args:
flist: A list/FilesList of delimited text files.
insep[str]: A list of regex strings. (Default [","])
outsep(str): New column separator. (Default "\t")
Returns:
[str]: A list of strings with the changed delimiters. One string per
file. It is up to you to decide what to do with the new
strings. The order of strings is the same as the input.
"""
input = []
if flist == []:
# Read all data from STDIN at once. Input[] gets a single entry.
input.append(sys.stdin.read())
else:
# Read in all the files entirely. Input[] gets as many entries as there are files.
for myfile in flist:
with open(myfile) as f:
input.append(f.read())
return swap_substr(input, insep, outsep)
# Helper function
def swap_substr(slist, insep=[","], outsep="\t"):
"""Replace all occurrences of insep with outsep.
Insep may be a regex.
Args:
slist[str]: A list of strings.
insep[str]: A list of regex strings. (Default [","])
outsep(str): New substring. (Default "\t")
Returns:
[str]: A list of the edited strings. The order of the strings is the
same as the input.
"""
rx = re.compile("|".join(insep), re.MULTILINE)
result = []
for s in slist:
# Replace all delimiters with the new one.
result.append(rx.sub(outsep, s))
return result
def prepare_df(df, myalias="", keyCol=None, keyhead="row_ID", header=False, cols=None, appendNum=True):
"""Prepare row names and column names.
Assign column as row labels, rename columns based on their position and an
arbitrary alias name for the dataframe, drop the first row.
Args:
df(pandas.DataFrame): A dataframe.
myalias(str): The basename for the relabelling.
header(bool): Remove first row (Default False).
keyCol(int): Column to be used as row index. If None, no index will be
used. (Default None)
keyhead(str): Label for the index.
cols[int]: Custom index numbers for the columns (Default None). If None
then their current index positions are used.
appendNum(bool): Append the columns' positional indices to the alias
when making the new names (True).
Returns:
pandas.DataFrame
"""
# Set row labels.
if keyhead is None:
keyhead = "row_ID"
if keyCol is not None:
# Add index without dropping it, so as not to affect column positions.
df.set_index(df.columns.values.tolist()[keyCol], inplace=True, drop=False)
df.index.name = str(keyhead)
# Make custom column labels, based on alias and column position.
if not cols:
cols = list(range(0, df.shape[1]))
labels = []
if appendNum:
labels = [str(myalias) +"_|"+ str(i) for i in cols]
else:
labels = [str(myalias) for i in cols]
df.columns = labels
# Remove header.
if header:
df.drop(df.index.values.tolist()[0], axis=0, inplace=True)
return df
def count_columns(flist=[None], colSep=["\t"]):
"""Determine the number of fields in each file by inspecting the first row.
Args:
flist: A list of FilesList of files.
colSep[str]: A list of characters used to separate columns.
Returns:
[int]: A list, in the same order as the given files.
"""
tokenizer = re.compile("|".join(colSep))
counts = []
for file in flist:
f = None
if file is None:
f = sys.stdin
file = "<STDIN>"
else:
f = open(file)
while True:
line = f.readline()
# Skip comments.
if line[0] != "#":
counts.append(len( tokenizer.split(line.rstrip()) ))
break
f.readline
if f != sys.stdin:
f.close()
return counts
def get_valuesSet(flist=[None], axis='r', index=0, filter='a', colSep=["\t"]):
""""List the set of different values in the column(s)/row(s).
Args:
flist: A list of FilesList of files.
colSep[str]: A list of characters used to separate columns.
index: Position index of the required column/row.
axis(str): Data slice orientation - 'r' for row, 'c' for column.
filter(str): non redundant set of: 'a' - all, 'u' - unique, 'r' -
repeated values.
Returns:
[[]]: A list of lists. The inner lists represent the sets in order as
requested.
Raises:
ValueError: Invalid axis or filter values.
"""
tokenizer = "|".join(colSep)
result = []
if flist == []:
# Use None as a flag to read from STDIN
flist.append(None)
# Test if it is a FilesList or plain list. Upgrade it if it's plain.
# It will have at least one entry for sure by now, either way.
try:
flist.aliases[0]
except AttributeError:
flist = FilesList(flist)
# Main part of this function.
results = []
for f, (myfile, myalias) in flist.enum():
# Input.
df = None
instream = sys.stdin
if myfile is not None:
instream = open(myfile)
df = pd.read_csv(instream, sep=tokenizer, header=None, index_col=None, comment="#", engine='python')
if instream != sys.stdin:
instream.close()
# Get value set.
values = None
if axis == 'r':
values = df.iloc[int(index),:].tolist()
elif axis == 'c':
values = df.iloc[:,int(index)].tolist()
else:
raise ValueError("".join(["Unrecognized option: axis=", axis]))
# Get count per value
c = Counter(values);
# Filter.
if filter == 'a':
results.append( set(values) )
elif filter == 'u':
results.append( set([v for v in values if c[v] == 1]) ) # set() is redundant but keeps output type consistent
elif filter == 'r':
results.append( set([v for v in values if c[v] > 1]) )
else:
raise ValueError("".join(["Unrecognized option: filter=", filter]))
return results
def get_columns(flist=[None], cols=[0], colSep=["\t"], header=False, index=None, merge=True):
"""Obtain the specified columns.
Comment lines starting with '#' are ignored.
The data columns are assembled into a single DataFrame.
The returned columns will be labeled based on the name of the file they
came from and their position in it. Existing labels are optionally
preserved as the top row or can be skipped entirely.
If an index is specified, it will be used only for merging, and will NOT be
included in the output columns, unless explicitly present in cols[].
Args:
flist: A list/FilesList of delimited plain text files.
header(bool): Crop the header line (first non-comment line). (Default False)
cols[int/str] : A list of positional indexes or names or ranges of the
desired columns. (Default [0]).
colSep[str]: List of characters used as field separators.
(Default ["\t"]).
merge(bool): Concatenate results from all files into a single
dataframe. If False, a list of dataframes is returned
instead. (Default True).
index(int): Column to be used as row index for merging. (Default None)
Returns:
[pandas.DataFrame]: List of DataFrames. If merge=True, only the
first element will be populated.
"""
tokenizer = "|".join(colSep)
result = []
if flist == []:
# Use None as a flag to read from STDIN
flist.append(None)
# Test if it is a FilesList or plain list. Upgrade it if it's plain.
# It will have at least one entry for sure by now, either way.
try:
flist.aliases[0]
except AttributeError:
flist = FilesList(flist)
# Parse.
keyhead = None
for f, (myfile, myalias) in flist.enum():
# I used to use the pandas parser, with my own parser used only as fallback
# for problematic cases. As flexibility requirements increased, using the
# pandas parser became too opaque and difficult to maintain,
# so now all cases are delegated to mine.
df = get_columns_manual(myfile, cols=cols, colSep=colSep, header=header,
alias=myalias, index=index)
if not keyhead:
keyhead = df.index.name
result.append(df)
# Merge.
if merge:
result = [pd.concat(result, axis=1, join='outer', ignore_index=False, sort=False), ]
result[0].index.name = keyhead
return result
# Helper function
def get_columns_manual(file=None, cols=[0], colSep=["\t"], header=False, index=None, alias=None):
"""Get specified columns from a file where rows have varying numbers of fields.
Some tables contain a fixed set of fields followed by optional fields. In
these rare cases, traditional parsers fail due to inconsistent number of
fields. This function provides a work-around for that.
It is entirely the user's responsibility to ensure that the inconsistent
row lengths are not a symptom of table corruption/malformation and that it
is safe and reliable to extract the desired columns. If a row is shorter
than expected, it is padded with the value "IDXERROR". If this value shows
up in your result and you are not explicitly expecting it, you should stop
and seriously examine your input table.
Args:
file(str): A delimited plain text file.
header(bool): If True, the first non-comment line will not be in
the data. (Default False)
cols[int]: A list of positional indexes of the desired columns.
(Default [0]).
colSep[str]: List of regex strings for field separators.
(Default ["\t"]).
index(int): Position of column to be used as row index. (Default None)
alias(str): An alias for the file. Used for naming the columns.
Returns:
pandas.DataFrame: DataFrame with the columns, labeled by original
column number, ordered as specified.
"""
tokenizer = re.compile("|".join(colSep))
# Input source.
f = None
if file is None:
f = sys.stdin
file = "STDIN"
else:
f = open(file)
if alias is None:
alias = FilesList.autoalias(file)
# Import data.
keyhead = None
values = []
labels = []
for l, line in enumerate(f):
if line[0] == '#' or line == "\n":
# Skip comments and empty lines.
continue
else:
# Get the fields.
fields = tokenizer.split(line.rstrip("\n"))
# Column labels from the first non-comment non-empty row,
# regardless of whether they really are labels or not.
if not labels:
labels = fields
# Find out name of row index.
if (not keyhead) and header and (index is not None):
keyhead = str(fields[index])
# Get columns.
selection = []
expandedcols = []
for c in cols:
v = str(c).split(":")
if len(v) == 1:
try:
expandedcols.append(int(v[0]))
except ValueError:
expandedcols.append(labels.index(v[0]))
else:
try:
expandedcols.extend(list(range(int(v[0]), int(v[1]) + 1)))
except TypeError:
expandedcols.extend(list(range(labels.index(v[0]), labels.index(v[1]) + 1)))
for i in expandedcols:
try:
selection.append(fields[i])
except IndexError:
# Silently adding fields is too dangerous, so a flag value is needed.
# Values like None or NA can sometimes be legitimate values for fields.
selection.append("IDXERROR")
# Add the key at the end, where they won't interfere with column numbers.
if index is not None:
selection.append(fields[index])
values.append(selection)
if f != sys.stdin:
f.close()
# Adjust index of row keys to reflect the fact I stuck them at the end.
if index is not None:
index = len(values[0])-1
expandedcols.append("my_garbage_label_row_key")
# Package data nicely.
df = pd.DataFrame(data=values)
df.astype(str, copy=False) # Uniform string type is simplest and safest.
df = prepare_df(df, myalias=alias, keyCol=index, header=header, cols=expandedcols,
keyhead=keyhead, appendNum=True if len(expandedcols)>1 else False)
if index is not None:
df.drop(alias+"_|my_garbage_label_row_key", 1, inplace=True)
return df
def get_random_columns(flist, colSep=["\t"], k=1, header=False, index=None, merge=True):
""" Get k random columns from each file.
The returned columns will be labeled based on the name of the file they
came from and their position in it. Existing labels are optionally
preserved as the top row or can be skipped entirely.
If an index is specified, it will be used for merging (if applicable) and
will be included as a column in each output file.
Args:
flist: A list or FilesList of files.
k(int): How many columns to get.
colSep[str]: A list of characters used as field separators.
(Default ["\t"])
header(bool): Strip column headers. (Default False)
index(int): Column to use as row index for merging. (Default None)
merge(bool): Concatenate results from all files into a single
dataframe. If False, a list of dataframes is returned
instead. (Default True).
Returns:
[pandas.DataFrame]: List of DataFrames. If merge=True, only the
first element will be populated.
"""
tokenizer = "|".join(colSep)
# The files may have different number of columns
fieldNums = count_columns(flist, colSep)
result = []
if flist == []:
# Use None as a flag to read from STDIN
flist.append(None)
keyhead = None
# Test if it is a FilesList or plain list. Upgrade it if it's plain.
# get_columns() does this too, but as I call it per item in flist, I *must*
# preserve any alias that is potentially already specified.
try:
flist.aliases[0]
except AttributeError:
flist = FilesList(flist)
# Get columns.
for f, (myfile, myalias) in flist.enum():
cols = []
if index is not None:
# Generate random choice of columns.
# range() is right-open.
cols.extend(random.sample(list(range(0, fieldNums[f]-1)), k))
else:
cols = random.sample(list(range(0,fieldNums[f])), k)
# Would normally delegate the actual getting to get_columns() but there
# are too many little differences to accommodate that complicate the code
# to the point of defeating any benefits from code re-use.
df = pd.read_csv(myfile, sep=tokenizer, header=None, index_col=None, comment="#", engine='python')
if (not keyhead) and header and (index is not None):
keyhead = str(df.iloc[0,index])
# Adjust row and column labels.
df = prepare_df(df, myalias=myalias, keyCol=index, header=header, keyhead=keyhead,
appendNum=True if k>1 else False)
# Slice the part I need.
df = df.iloc[:,cols]
result.append(df)
# Merge.
if merge:
result = [pd.concat(result, axis=1, join='outer', ignore_index=False)]
result[0].index.name = keyhead
return result
def append_columns(flist, colSep=["\t"], header=False, index=None, merge=True, type='outer'):
"""Append all columns from the files, as they are.
Inner or outer concatenation by a unique index, or index-less concatenation.
Ideally used with a unique index and for only for same-length files.
Args:
flist: A list/FilesList of files to combine.
colSep[str]: A list of characters used as field delimiters.
(Default ["\t"])
header(bool): First non-comment line as column labels. (Default False)
index(int): Column to use as row index (same in all files).
(Default None)
If None, the number of rows can differ between files and will be
padded (outer) or truncated (inner), otherwise the row number must
be the same in all files.
type(str): Join type 'inner' or 'outer'.
Returns:
pandas.Dataframe
"""
try:
flist.aliases[0]
except AttributeError:
flist = FilesList(flist)
# Determine how many columns each file has.
numofcols = count_columns(flist, colSep=colSep)
# Delegate fetching all the columns.
data = []
keyhead = None
for f, (myfile, myalias) in flist.enum():
# List the columns and remove the index one from among them.
cols = [i for i in range(0,numofcols[f]) if i != index]
df =get_columns(FilesList(files=[myfile], aliases=[myalias]), cols=cols,
colSep=colSep, header=header, merge=False, index=index)[0]
data.append( df )
# Merge. Row indexes will have been assigned by get_columns(), if applicable.
keyhead = data[0].index.name
result = pd.concat(data, axis=1, join=type, ignore_index=False, sort=False)
result.index.name = keyhead
return result
def merge_tables(flist, colSep=["\t"], header=False, index=0, merge=True, type='outer', saveHeader=False, dedup=True):
"""Incrementally merge tables.
Join the first two files and then join the third file to the merged first two, etc.
For assymetric joins (left or right) the order of files in flist can change the outcome.
For symmetric joins (inner or outter) the order of files should not change the outcome.
Args:
flist: A list/FilesList of files to combine.
colSep[str]: A list of characters used as field delimiters.
(Default ["\t"])
header(bool): Crop first non-comment line as column labels. (Default False)
index(int): Column to use as row index (same in all files).
(Default 0)
type(str): 'left', 'right', 'outer' or 'inner' merge. (Default outer)
saveHeader(bool): Exclude the first row from sorting upon merging. (False)
Necessary when the header is not to be cropped.
dedup(bool): Remove repeated index columns (one per file).
Returns:
pandas.Dataframe
"""
try:
flist.aliases[0]
except AttributeError:
flist = FilesList(flist)
# Determine how many columns each file has.
numofcols = count_columns(flist, colSep=colSep)
# Fetch and incrementally merge.
result = None
for f, (myfile, myalias) in flist.enum():
# List the columns and remove the index one from among them.
cols = [i for i in range(0,numofcols[f])]
df = get_columns(FilesList(files=[myfile], aliases=[myalias]), cols=cols,
colSep=colSep, header=header, merge=False, index=index)[0]
if (f == 0):
result = df
else:
if saveHeader:
# Extract headers, merge headers and tables separately, then put merged header on top of the merged table.
hnew = pd.merge(left=result.iloc[[0]], right=df.iloc[[0]], sort=False,
left_index=True, right_index=True, how="outer")
result = pd.concat([hnew, pd.merge(left=result.iloc[1:,:], right=df.iloc[1:,:], how=type, on=None,
left_index=True, right_index=True,
sort=False, suffixes=('','_'+ myalias))],
axis=0, ignore_index=False, sort=False)
else:
result = pd.merge(left=result, right=df, how=type, on=None,
left_index=True, right_index=True,
sort=False, suffixes=('','_'+ myalias))
# In addition to the new row_ID columns, the index column was kept for each table. Drop them as redundant.
# If the index columns are not exact duplicates (due to gappy rows),
# dedup_columns can be used afterwards on the merged file).
if dedup:
index_cols = [col for col in result.columns if '_|' + str(index) in col]
result.drop(columns=index_cols, inplace=True)
return result
# Helper function
def getDuplicateColumns(df):
'''
Get a list of duplicate columns.
It will iterate over all the columns in dataframe and find the columns whose contents are duplicate.
Stolen from https://thispointer.com/how-to-find-drop-duplicate-columns-in-a-dataframe-python-pandas/ .
Args:
df: Dataframe object
Returns:
List of columns whose contents are redudnant (one occurence will of each will not be included in the list).
'''
duplicateColumnNames = set()
# Iterate over all the columns in dataframe
for x in range(df.shape[1]):
# Select column at xth index.
col = df.iloc[:, x]
# Iterate over all the columns in DataFrame from (x+1)th index till end
for y in range(x + 1, df.shape[1]):
# Select column at yth index.
otherCol = df.iloc[:, y]
# Check if two columns at x 7 y index are equal
if col.equals(otherCol):
duplicateColumnNames.add(df.columns.values[y])
return list(duplicateColumnNames)
def dedup_columns(flist, cols=[0,1], colSep=["\t"], merge=True):
"""Merge duplicate columns from the files, as they are.
This function also supports key-aware appending, using outer-join, when a
row index is specified.
Args:
flist: A list/FilesList of files to combine.
colSep[str]: A list of characters used as field delimiters.
(Default ["\t"])
cols[int] : A list of positional indexes of the
desired columns. (Default [0,1]).
Returns:
pandas.Dataframe
"""
try:
flist.aliases[0]
except AttributeError:
flist = FilesList(flist)
# Determine how many columns each file has.
numofcols = count_columns(flist, colSep=colSep)
# Delegate fetching all the columns.
result = []
keyhead = None
for f, (myfile, myalias) in flist.enum():
# List the columns.
allcols = [i for i in range(0,numofcols[f])]
df = get_columns(FilesList(files=[myfile], aliases=[myalias]), cols=allcols,
colSep=colSep, header=False, merge=False, index=None)[0]
# Collect duplicated values, drop duplicated columns, assign values to new column.
v = df.iloc[:, cols].apply(lambda x: next(s for s in x.unique() if s), axis=1)
df.drop(df.columns[cols], axis=1, inplace=True)
df = pd.concat([df, v], axis=1, join='outer', sort=False, ignore_index=False)
if not keyhead:
keyhead = df.index.name
result.append(df)
# Merge.
if merge:
result = [pd.concat(result, axis=1, join='outer', ignore_index=False, sort=False), ]
result[0].index.name = keyhead
return result
def get_crosspoints(flist, cols=[0], rows=[0], colSep=["\t"], header=False, index=None, merge=True):
""" Get the values at selected rows and columns.
The values at the intersections of the selected rows and columns are extracted.
Args:
flist: A [str] list or fileutilities.FilesList of delimited text files.
colSep[str]: List of column separators.
cols[int]: List of columns.
rows[int]: List of rows.
header(bool): Whether there is a header line (False).
index(int): Which column has the row labels (None).
merge(bool): Merge results into single table (True).
Returns:
[pandas.DataFrame]:
"""
results = get_columns(flist, cols=cols, colSep=colSep, header=header, merge=merge, index=index)
for i in range(0, len(results)):
results[i] = results[i].iloc[rows,:]
return results
def store_metadata(flist, numoflines):
"""Store top lines of files into dictionary.
Args:
flist: A list or FilesList.
numoflines(int): Number of lines to save.
Returns:
dict[]: The items of flist[] are used as keys.
"""
metadata = dict()
for myfile in flist:
if myfile is None:
fin = sys.stdin
else:
fin = open(myfile)
lines = []
for i in range(0, numoflines):
lines.append(fin.readline())
metadata[myfile] = "".join(lines)
if fin != sys.stdin:
fin.close()
return metadata
##### C L A S S E S #####
class FilesList(list):
"""A container for a list of files.
An extension of the built-in list, specifically for files, providing a
means to import multiple filenames either from text lists or from
directories. The purpose is to facilitate batch operations and sensible
output of their results.
FilesList is generally backwards compatible with the built-in list and it
should be possible for them to be used interchangeably in most cases. A
plain list can be cast as a FilesList, when necessary, allowing appointment
of default alias values. A FilesList should always work as a plain list
without additional actions (except for its string representation). When a
FilesList is accessed as a plain list, only the full paths will be
accessed. Certain equivalent methods are supplied for
Most basic operations inherited from list are supported. Appending has been
overridden to keep paths and aliases in sync. Sorting, deleting and
inserting of items are currently not supported and will break the
correspondence between paths and aliases.
Attributes defined here:
aliases = [] : Practical aliases for the full file-paths.
"""
def __init__(self, files=None, aliases=None, fromtuples=None, verbatim=True):
"""Construct an instance of the FilesList.
A FilesList can be created:
- empty
- from a list of files (with default aliases automatically assigned)
- from a list of files and a list of aliases (in the same order)
- from a list of (file, alias) tuples.
Args:
verbatim(bool): Whether to skip path pre-preocessing. (Default True)
files[str]: A list of files. (Default None)
aliases[str]: A list of aliases. (Default None)
fromtuples[(str,str)]: A list of tuples (file, alias). (Default
None) If this is specified together with flist and/or
aliases, the data in fromtuples is used only.
"""
# If data is a list of (file, alias) tuples, unpair tuples into lists.
if fromtuples is not None:
data = [list(t) for t in zip(*fromtuples)]
# Any data passed to flist and aliases at method call is discarded.
files = data[0]
aliases = data[1]
# Having aliases without the paths is rather useless.
if aliases:
if not files:
raise ValueError("No files supplied for the aliases.")
else:
# Make None into empty.
aliases = []
# Assign default aliases to be same as files. Expand file paths.
if files is not None:
if not verbatim:
files = expand_fpaths(files)
if not aliases:
for f in files:
aliases.append(self.autoalias(f))
else:
# If still empty, it was an empty call to the constructor.
files = []
# Create the basic list.
super().__init__(files)
# Add a plain list attribute for the aliases with default values.
self.aliases = autonumerate(aliases)
def __str__(self):
"""Represent as string.
Overrides built-in list's representation.
Returns:
str
"""
tmp = []
for f, (myfile, myalias) in self.enum():
tmp.append("\t".join([str(f), myfile, myalias]))
tmp.append("")
return "\n".join(tmp)
def to_file(self, outfile=None, mode ='a'):
"""Save list as a text file that can be read back in.
Args:
outfile(str): Output file to write into. If omitted, it only
returns the content as a print-ready string.
(Default None)
mode(str): Append ('a') or overwrite ('w'). (Default 'a')
Returns:
str: A print-ready multi-line string. This is returned even when an
output file is specified and written into.
"""
result = ""
for f, (myfile, myalias) in self.enum():
result += myfile + "\t" + myalias + "\n"
if outfile is not None:
with open(outfile, mode) as out:
out.write(result)
return result
def enum(self):
"""Enumerate as (index, (filepath, filealias)).
Returns:
enumerator"""
return enumerate(zip(self, self.aliases))
def get(self, loc):
"""Access path and alias at specified location as tuple.
Args:
loc[int]: Index of item to get.
Returns:
(str,str): Tuple (path, alias).
"""
return (self[loc], self.aliases[loc])
def append(self, myfile, myalias=None, verbatim=True):
"""Appends value to both the paths list and the aliases list.
This method overrides the built-in append() of list. It is backwards
compatible by automatically guessing an alias.
This reduces the risk of the paths and aliases going out of sync due
to items being manually added without updating the aliases.
It is still possible to break the sync by manually adding items to the
aliases.
Args:
myfile(str): File (path will be expanded).
myalias(str): Alias for the file (Default None).
verbatim(bool): Do not pre-process path for the target value. (Default True)
"""
if myfile is not None:
if not verbatim:
myfile = expand_fpaths([myfile])[0]
super().append(myfile)
if not myalias:
myalias = self.autoalias(myfile)
self.aliases.append(myalias)
self.aliases = autonumerate(self.aliases)
def populate_from_files(self, myfiles, colSep="\t", verbatim=True):
"""Parse the list of files from one or multiple text files.
Read in multiple lists of files from text and append them to the
FilesList. All paths are automatically expanded and converted to
absolute paths. Because of this, each file may also be given a more
convenient alias. If no alias is given, the filename as supplied is
used as the alias instead. The paths are not checked for existence.
Existing contents of the object are kept and the new contents are
appended.
Input file format (no spaces allowed inside names):
#comment
path1/file1 alias1-prefix alias1-suffix1 alias1-suffix2
path1/file2 alias1-prefix alias1-suffix3
path2/file3 alias3
path3/file4
Args:
file[str]: A list of text files each containing a list of files.
colSep(str): Column separator. (Default "\\t")
verbatim(bool): Do not pre-process paths for the target values. (Default True)
Returns:
FilesList: Returns self, to facilitate instantiation shortcuts.
"""
# Read new list.
paths = []
for myfile in myfiles:
with open(myfile, 'rU') as input:
for line in input:
if line == "\n":
# Skip empty lines.
continue
elif line[0] == '#':
# Skip comments.
continue
else:
fields = line.rstrip().split(colSep)
paths.append(fields[0])
# Store the alias for the file.
if len(fields) > 1:
self.aliases.append("_".join(fields[1:]))
# If an alias was not specified, re-use the filepath given.
else:
self.aliases.append(self.autoalias(fields[0]))
# Expand to absolute paths and add to main self list.
if not verbatim:
paths = expand_fpaths(paths)
self.extend(paths)
self.aliases = autonumerate(self.aliases)
return self
def populate_from_directories(self, dirpaths, patterns=None, verbatim=True):
"""Get files based on naming patterns from within a list of directories.
Useful for selecting among files that follow a naming convention. The
convention is represented by a list of regex strings, at least one of
which has to match.
File paths will be expanded automatically. The filenames will be used
as the aliases.
Existing contents of the object are kept and the new contents are
appended.
Args:
dirpaths[str]: A list/FilesList of paths to directories from where
to get files.
patterns[str]: A list of regex strings. Only files matching at least
one of these will be returned. The patterns will be
matched anywhere in the filenames.
verbatim(bool): Do not pre-process paths for the target values. (Default True)
Returns:
FilesList: Returns self, to facilitate instantiation shortcuts.
"""
rx = []
if patterns:
rx = [re.compile(p) for p in patterns]
for d in dirpaths:
try:
os.chdir(d)
for f in os.listdir(d):
if f in ["","\n",".",".."]:
continue
if not patterns:
# No filter.
self.append(os.path.join(d, f), self.autoalias(f), verbatim=verbatim)
else:
for p in rx:
if p.search(f):
self.append(os.path.join(d, f), self.autoalias(f), verbatim=verbatim)
break
finally:
pass
self.aliases = autonumerate(self.aliases)
return self.sorted()
# Helper function.
@staticmethod
def autoalias(pathname):
"""Strip a path to the base filename."""
if pathname is None:
return None
else:
return os.path.splitext(os.path.basename(str(pathname)))[0]
def sorted(self):
"""Sorted copy.
Returns:
FilesList
"""
d = dict()
for i, (myfile, myalias) in self.enum():
d[myfile] = myalias
sk = natural_sorted(list(d.keys()))
newFL = FilesList()
for k in sk:
newFL.append(k, d[k])
return newFL
##### M A I N #####
def main(args):
"""Provide command-line access to the module's functionality.
The functionality and format of main is subject to change, as the module
expands and evolves to suit my needs. Main() is not intended to be called
from within other code.
Optional short info is printed in commented lines. The info always
*succeeds* the relevant output, rather than precede it. This serves as
confirmation that the task completed. Calling details of the script are
recorded in commented lines at the top of the output.
For more info on the functionality, read the above documentation of the
classes and functions. For usage syntax, execute the module with the -h
argument.
"""
# Organize arguments and usage help:
parser = argparse.ArgumentParser(description="Provide INPUTTYPE and TARGETs \
*before* providing any of the other parameters. This is due to many \
parameters accepting an indefinite number of values. Only one task at a time.")
# Input/Output.
parser.add_argument('INPUTTYPE', type=str, choices=['L','T','D','P'],
help=" Specify the type of the TARGETs: \
'T' = The actual input filess. \
'L' = Text file(s) listing the input files. \
'P' = Get list of input files from STDIN pipe. \
'D' = Input data directly from STDIN pipe. \
('D' is compatible with only some of the functions)")
parser.add_argument('TARGET', type=str, nargs='*',
help=" The targets, space- or comma-separated. Usually files. \
Look into the specific task details below for special uses. \
Do not specify with INPUTTYPE 'P' or 'D'.")
parser.add_argument('-O','--out', type=str, nargs=3,
help=" Send individual outputs to individual files instead of \
merging them to STDOUT. Output files will be like \
<out[0]>/<out[1]>target<out[2]>, where target is stripped of \
any directory path and its outermost file extension.")
# Parameters.
parser.add_argument('-L','--log', action='store_true',
help=" Log subcommands to ./commands.log.")
parser.add_argument('-C','--STDERRcomments', action="store_false",
help=" Do NOT show info in STDERR. (Default show)")
parser.add_argument('-s','--sep', type=str, default=["\t"], nargs='+',
help=" A list of input field separators. The first value \
will be used for all output. (Default \\t, bash syntax for tab: $'\\t').")
parser.add_argument('-l','--labels', action='store_true',
help=" Discard column headers (first content line) in input files. (Default do not discard)")
parser.add_argument('-r','--relabel', action='store_false',
help=" Do not create new column headers that reflect the origin of the columns. (Default create)")
parser.add_argument('-i','--index', action='store_true',
help=" Use column 0 as row index. The index will always be included in the output. (Default no index)")
parser.add_argument('-M','--metadata', type=int, default=0,
help=" Number of metadata lines at the \
beginning of input data (Default 0). Metadate will be read separately \
and re-added verbatim into the output.")
parser.add_argument('-R','--expand_ranges', action='store_true',
help=" If numeric ranges exist among the targets expand them as individual vlaues. \
Ranges must be in from:to format, inclusive of both end values. (Default False)")
parser.add_argument('-V','--verbatim', action='store_true',
help=" Preserve the target values from a list file, do not try to expand them into absolute paths. (Default impute absolute paths)")
# General tasks.
parser.add_argument('--dir', type=str, nargs='*',
help=" List the contents of the target paths. \
Full absolute file paths are returned. Each file is also given an alias. \
Supplying an optional list of regex patterns enables filtering of the result.")
parser.add_argument('--link', type=str, nargs='+',
help=" Create symbolic links for the targets into the specified directory. \
Any additional values are used as respective names for the links, one for one, \
otherwise the aliases or basenames will be used, enumerated when necessary.")
parser.add_argument('--loop', type=str, nargs='+',
help=" Repeat the specified shell command for each target value. \
Available PLACEHOLDERS to insert the targets into the commands: \
{abs} full path, {dir} path of directory portion, {val} target value such as filename, \
{bas} basename (filename minus outermost extension), {ali} file alias. \
Flags intended for the nested command should be preceded \
by a ',' sign like this: ',-v'. Recursive calls to fileutilities.py are possible by \
nesting the placeholders and escapes: i.e. {{abs}}, ,,-v. One layer is peeled off \
with each call to fileutilities loop. The placeholders will take the values \
of the targets of the respectively nested call.")
# Delimited file tasks.
parser.add_argument('--concat', type=str,
help="Create an X-separated list out of the target values, where X is the string specified as argument here. \
Useful for creating comma-separated lists of files.")
parser.add_argument('--swap', type=str,
help=" Replace all occurrences of the --sep values with the value supplied here.\
** Bash syntax for tab: $'\\t'. Compatible with 'D' as INPUTTYPE.")
parser.add_argument('--cntcols', action='store_true',
help=" Count the number of fields in the first row of each target file.")
parser.add_argument('--cols', nargs='+',
help=" Extract the specified columns (named or 0-indexed) from each target. \
Column ranges in x:y format closed at both ends. \
Negative indices must be escaped first: \-1. Compatible with 'D' as INPUTTYPE.")
parser.add_argument('--rndcols', type=int,
help="Randomly select this many columns from the target files. \
With --index, the index column will not be part of the random selection.")
parser.add_argument('--appnd', type=str,
help="Append all the columns from same-length target files into a single table. \
Can be 'outer' or 'inner' join. If index is used, the values must be unique \
within each file.")
parser.add_argument('--merge', nargs=3, type=str,
help="Merge table files. Index may contain duplicates and files may differ in dimensions. \
The first column of each file will be used as row index to merge on regardless of -i flag. \
First argument is type: 'left', 'right', 'inner', 'outer'. \
Second argument is preserve first row: 'yes', 'no' (because merge sorts rows) \
Third argument is deduplicate: 'yes', 'no' (index columns get repeated for each file. \
For very large tables, best don't deduplicate, and use --mrgdups on the output). \
For left/right joins, the order of files affects the result.")
parser.add_argument('--mrgdups', type=int, nargs='+',
help="Combine gappy duplicate columns into a single column with all the values.\
Columns are specified by their 0-based positional index given as arguments here.")
parser.add_argument('--valset', nargs=3,
help="Get the non-redundant set of values in the given row/column. \
Takes three arguments: (i) orientation 'r' for row or 'c' for column, \
(ii) position index of the row/column, (iii) repetition filter: \
'a' all values, 'u' unique values only, 'r' only values with two or more instances.")
params = parser.parse_args(args)
# INPUT ###################################################################
targets = []
for t in params.TARGET:
v = t.split(",")
if len(v) == 1:
targets.append(t)
else:
targets.extend(v)
flist = None
if params.INPUTTYPE == 'P':
# Read files list from STDIN
flist = FilesList()
for line in sys.stdin:
fields = line.rstrip("\n").split("\t")
if fields[0] != "":
try:
flist.append(fields[0], fields[1])
except IndexError:
flist.append(fields[0])
elif params.INPUTTYPE == 'L':
# Create the FilesList, by appending the contents of all provided lists.
flist = FilesList().populate_from_files(targets, verbatim=params.verbatim)
elif params.INPUTTYPE == 'T':
# Create the FilesList by supplying a direct list of files.
flist = FilesList(targets, verbatim=params.verbatim)
elif params.INPUTTYPE == 'D':
# Data will be read from STDIN. No files needed. Make an empty list.
# Not all functions will switch to STDIN given this. Several will simply do nothing.
flist = FilesList(verbatim=params.verbatim)
else:
sys.exit(ml.errstring("Unknown INPUTTYPE."))
if params.expand_ranges:
# Generate the range.
myrange = []
for t in params.TARGET: # Look for multiple ranges.
v = t.split(":")
if len(v) > 1:
myrange.extend(list(range(int(v[0]), int(v[1]) + 1)))
else:
myrange.extend(t) # Assume string literal. Allows mixing numeric and string target values.
flist = FilesList(myrange, verbatim=True) # If some values are mere numbers, it's unlikely that any others are file paths.
# Metadata. ---------------------------------------------------------------
metadata = ""
if params.metadata:
metadata = store_metadata(flist, params.metadata)
# OUTPUT ##################################################################
outdir, outpref, outsuff = None, None, None
if params.out:
outdir = expand_fpaths([params.out[0]])[0]
outpref = params.out[1]
outsuff = params.out[2]
# CALL DETAILS ############################################################
if params.STDERRcomments:
sys.stderr.write(ml.paramstring())
# TASKS ###################################################################
# Filter DIRECTORY contents. ----------------------------------------------
if params.dir is not None:
result = FilesList().populate_from_directories(flist, params.dir)
sys.stdout.write(result.to_file())
if params.STDERRcomments:
sys.stderr.write(ml.donestring("listing"))
# LOOP a command. -------------------------------------------------
elif params.loop:
command = []
for c in params.loop:
command.append(c.lstrip("+"))
do_foreach(flist, command, out=(outdir, outpref, outsuff),
progress=(params.STDERRcomments), log=params.log)
if params.STDERRcomments:
sys.stderr.write(ml.donestring("looping"))
# Symbolic LINKS. ---------------------------------------------------------
elif params.link:
slink(flist, dir=params.link[0], aliases=params.link[1:])
if params.STDERRcomments:
sys.stderr.write(ml.donestring("linking"))
# CONCATENATE strings. --------------------------------------------------------
if params.concat:
sys.stdout.write(params.concat.join(flist))
if params.STDERRcomments:
sys.stderr.write(ml.donestring("concatenating values"))
# SWAP substrings. --------------------------------------------------------
elif params.swap is not None:
result = swap_strFiles(flist, insep=params.sep, outsep=params.swap)
# Create output filenames, if applicable. If [], then STDOUT.
outfiles = make_names(flist.aliases, (outdir, outpref, outsuff))
outstream = sys.stdout
# I need the for loop to iterate at least once. Relevant for STDIN input, since I have no input files listed then.
if flist == []:
flist.append("<STDIN>")
# Print the converted data.
for i, (myfile, myalias) in flist.enum():
if outfiles:
# Send to individual file instead of STDOUT.
outstream = open(outfiles[i], 'w')
outstream.write(result[i].rstrip("\n") +"\n")
if outfiles:
# Don't want to accidentally close STDOUT.
outstream.close()
if params.STDERRcomments:
sys.stderr.write(ml.donestring("swapping delimiters"))
# Get COLUMNS or RANDOM columns. (most code shared) -----------------------
elif params.cols or params.rndcols:
# Create output filenames, if applicable. If [], then STDOUT.
outfiles = make_names(flist.aliases, (outdir, outpref, outsuff))
outstream = sys.stdout
merge = False if outfiles else True
# Determine if using index, and assign appropriate value.
idx = None
if params.index:
idx = 0
else:
idx = None
# Extract data.
result = None
if params.cols:
cols = []
for p in params.cols: # space separated arguments
cols.extend(p.split(",")) # comma separated arguments
# Get the specified columns.
result = get_columns(flist, cols=cols, colSep=params.sep,
header=params.labels, merge=merge, index=idx)
else:
# Get random columns.
result = get_random_columns(flist, k=params.rndcols, colSep=params.sep,
header=params.labels, merge=merge, index=idx)
# I need the for loop to iterate at least once. Relevant for STDIN input, since I have no input files listed then.
if flist == []:
flist.append("<STDIN>")
if merge:
if params.metadata:
# Dump all the metadata from all the merged input sources.
for i, (myfile, myalias) in flist.enum():
outstream.write(metadata[myfile])
outstream.write( result[0].to_csv(header=params.relabel, index=params.index, sep=params.sep[0]))
else:
for i, (myfile, myalias) in flist.enum():
outstream = open(outfiles[i], 'w')
if params.metadata:
outstream.write(metadata[myfile])
outstream.write( result[i].to_csv(header=params.relabel, index=params.index, sep=params.sep[0]))
outstream.close()
if params.STDERRcomments:
if params.cols:
sys.stderr.write(ml.donestring("getting columns, index "+ str(idx is not None)))
else:
sys.stderr.write(ml.donestring("getting random columns, index "+ str(idx is not None)))
# APPEND columns or MERGE table. ---------------------------------------------------------
elif params.appnd or params.merge:
idx = None
if params.appnd:
if params.index:
idx = 0
df = append_columns(flist, colSep=params.sep, header=params.labels, index=idx, type=params.appnd)
else:
df = merge_tables(flist, colSep=params.sep, header=params.labels, index=0, type=params.merge[0],
saveHeader=params.merge[1] == "yes", dedup=params.merge[2] == "yes")
if params.metadata:
# Dump all the metadata from all the merged input sources.
for i, (myfile, myalias) in flist.enum():
outstream.write(metadata[myfile])
sys.stdout.write(df.to_csv(sep=params.sep[0], header=params.relabel, index=params.index))
if params.STDERRcomments:
if params.appnd:
sys.stderr.write(ml.donestring(params.appnd +" append of columns, index "+ str(idx is not None)))
else:
sys.stderr.write(ml.donestring(params.merge[0] +" merge of tables"))
# MERGE duplicate columns. ---------------------------------------------------------
elif params.mrgdups:
# Create output filenames, if applicable. If [], then STDOUT.
outfiles = make_names(flist.aliases, (outdir, outpref, outsuff))
outstream = sys.stdout
merge = False if outfiles else True
# Do.
result = dedup_columns(flist, colSep=params.sep, cols=params.mrgdups)
# I need the for loop to iterate at least once. Relevant for STDIN input, since I have no input files listed then.
if flist == []:
flist.append("<STDIN>")
if merge:
if params.metadata:
# Dump all the metadata from all the merged input sources.
for i, (myfile, myalias) in flist.enum():
outstream.write(metadata[myfile])
outstream.write( result[0].to_csv(header=params.relabel, index=params.index, sep=params.sep[0]))
else:
for i, (myfile, myalias) in flist.enum():
outstream = open(outfiles[i], 'w')
if params.metadata:
outstream.write(metadata[myfile])
outstream.write( result[i].to_csv(header=params.relabel, index=params.index, sep=params.sep[0]))
outstream.close()
if params.STDERRcomments:
sys.stderr.write(ml.donestring("deduplicating columns"))
# COUNT columns. ----------------------------------------------------------
elif params.cntcols:
result = count_columns(flist, params.sep)
for f, (myfile, myalias) in flist.enum():
print("\t".join([str(result[f]), myalias, myfile]))
if params.STDERRcomments:
sys.stderr.write(ml.donestring("counting columns"))
# SET of values in row/column. --------------------------------------------
elif params.valset:
nest = get_valuesSet(flist, axis=params.valset[0], index=params.valset[1], filter=params.valset[2], colSep=params.sep)
for f, (myfile, myalias) in flist.enum():
print("".join([myfile, "\t", str(nest[f])]))
if params.STDERRcomments:
sys.stderr.write(ml.donestring("obtaining set of values."))
# All done.
# if params.STDERRcomments:
# sys.stderr.write(ml.donestring())
##### E X E C U T I O N #####
# Call main only if the module was executed directly.
if __name__ == "__main__":
main(sys.argv[1:])
sys.exit(0)
#EOF
|
mit
|
JrtPec/tmpo-py
|
setup.py
|
2
|
3036
|
# -*- coding: utf-8 -*-
"""
A setuptools based setup module for tmpo.
Adapted from
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
# Get the version from the source code
with open(path.join(here, 'tmpo', '__init__.py'), encoding='utf-8') as f:
lines = f.readlines()
for l in lines:
if l.startswith('__version__'):
__version__ = l.split('"')[1] # take the part after the first "
setup(
name='tmpo',
version=__version__,
description='A python client for the tmpo protocol for timeseries',
long_description=long_description,
url='https://github.com/flukso/tmpo-py',
author='Bart Van Der Meerssche',
author_email='[email protected]',
license='MIT',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 4 - Beta',
# Indicate who your project is intended for
'Intended Audience :: Developers',
'Topic :: Scientific/Engineering',
# Pick your license as you wish (should match "license" above)
'License :: OSI Approved :: MIT License',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
keywords='data monitoring tmpo timeseries sqlite',
# You can just specify the packages manually here if your project is
# simple. Or you can use find_packages().
packages=find_packages(),
# Alternatively, if you want to distribute just a my_module.py, uncomment
# this:
#py_modules=["tmpo.py"],
# List run-time dependencies here. These will be installed by pip when
# your project is installed.
install_requires=['numpy', 'pandas', 'futures', 'requests_futures'],
# If there are data files included in your packages that need to be
# installed, specify them here. If using Python 2.6 or less, then these
# have to be included in MANIFEST.in as well.
# Note: for creating the source distribution, they had to be included in the
# MANIFEST.in as well.
package_data={
'tmpo': ['tmpo.ipynb', 'LICENSE', 'README.md'],
},
)
|
mit
|
swirlingsand/self-driving-car-nanodegree-nd013
|
p9-pid-control/quizes-python/pid-controller.py
|
1
|
4463
|
# -----------
# User Instructions
#
# Implement a P controller by running 100 iterations
# of robot motion. The steering angle should be set
# by the parameter tau so that:
#
# steering = -tau_p * CTE - tau_d * diff_CTE - tau_i * int_CTE
#
# where the integrated crosstrack error (int_CTE) is
# the sum of all the previous crosstrack errors.
# This term works to cancel out steering drift.
#
# Only modify code at the bottom! Look for the TODO.
# ------------
import random
import numpy as np
import matplotlib.pyplot as plt
# ------------------------------------------------
#
# this is the Robot class
#
class Robot(object):
def __init__(self, length=20.0):
"""
Creates robot and initializes location/orientation to 0, 0, 0.
"""
self.x = 0.0
self.y = 0.0
self.orientation = 0.0
self.length = length
self.steering_noise = 0.0
self.distance_noise = 0.0
self.steering_drift = 0.0
def set(self, x, y, orientation):
"""
Sets a robot coordinate.
"""
self.x = x
self.y = y
self.orientation = orientation % (2.0 * np.pi)
def set_noise(self, steering_noise, distance_noise):
"""
Sets the noise parameters.
"""
# makes it possible to change the noise parameters
# this is often useful in particle filters
self.steering_noise = steering_noise
self.distance_noise = distance_noise
def set_steering_drift(self, drift):
"""
Sets the systematical steering drift parameter
"""
self.steering_drift = drift
def move(self, steering, distance, tolerance=0.001, max_steering_angle=np.pi / 4.0):
"""
steering = front wheel steering angle, limited by max_steering_angle
distance = total distance driven, most be non-negative
"""
if steering > max_steering_angle:
steering = max_steering_angle
if steering < -max_steering_angle:
steering = -max_steering_angle
if distance < 0.0:
distance = 0.0
# apply noise
steering2 = random.gauss(steering, self.steering_noise)
distance2 = random.gauss(distance, self.distance_noise)
# apply steering drift
steering2 += self.steering_drift
# Execute motion
turn = np.tan(steering2) * distance2 / self.length
if abs(turn) < tolerance:
# approximate by straight line motion
self.x += distance2 * np.cos(self.orientation)
self.y += distance2 * np.sin(self.orientation)
self.orientation = (self.orientation + turn) % (2.0 * np.pi)
else:
# approximate bicycle model for motion
radius = distance2 / turn
cx = self.x - (np.sin(self.orientation) * radius)
cy = self.y + (np.cos(self.orientation) * radius)
self.orientation = (self.orientation + turn) % (2.0 * np.pi)
self.x = cx + (np.sin(self.orientation) * radius)
self.y = cy - (np.cos(self.orientation) * radius)
def __repr__(self):
return '[x=%.5f y=%.5f orient=%.5f]' % (self.x, self.y, self.orientation)
############## ADD / MODIFY CODE BELOW ####################
# ------------------------------------------------------------------------
#
# run - does a single control run
robot = Robot()
robot.set(0, 1, 0)
# steering = -tau_p * CTE - tau_d * diff_CTE - tau_i * int_CTE
def run(robot, tau_p, tau_d, tau_i, n=100, speed=1.0):
x_trajectory = []
y_trajectory = []
int_CTE = []
robot.set_steering_drift(10 / 180 * 3.14)
previous_cross_track_error = 0
for i in range(n):
CTE = robot.y
int_CTE.append(CTE)
diff_CTE = robot.y - previous_cross_track_error
int_CTE_sum = sum(int_CTE)
# print(int_CTE_sum)
steering = -tau_p * CTE - tau_d * diff_CTE - tau_i * int_CTE_sum
previous_cross_track_error = CTE
robot.move(steering, speed)
x_trajectory.append(robot.x)
y_trajectory.append(robot.y)
print(robot, steering)
return x_trajectory, y_trajectory
x_trajectory, y_trajectory = run(robot, 0.2, 3.0, 0.006)
n = len(x_trajectory)
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 8))
ax1.plot(x_trajectory, y_trajectory, 'g', label='PID controller')
ax1.plot(x_trajectory, np.zeros(n), 'r', label='reference')
plt.show()
|
mit
|
themrmax/scikit-learn
|
sklearn/mixture/tests/test_dpgmm.py
|
84
|
7866
|
# Important note for the deprecation cleaning of 0.20 :
# All the function and classes of this file have been deprecated in 0.18.
# When you remove this file please also remove the related files
# - 'sklearn/mixture/dpgmm.py'
# - 'sklearn/mixture/gmm.py'
# - 'sklearn/mixture/test_gmm.py'
import unittest
import sys
import numpy as np
from sklearn.mixture import DPGMM, VBGMM
from sklearn.mixture.dpgmm import log_normalize
from sklearn.datasets import make_blobs
from sklearn.utils.testing import assert_array_less, assert_equal
from sklearn.utils.testing import assert_warns_message, ignore_warnings
from sklearn.mixture.tests.test_gmm import GMMTester
from sklearn.externals.six.moves import cStringIO as StringIO
from sklearn.mixture.dpgmm import digamma, gammaln
from sklearn.mixture.dpgmm import wishart_log_det, wishart_logz
np.seterr(all='warn')
@ignore_warnings(category=DeprecationWarning)
def test_class_weights():
# check that the class weights are updated
# simple 3 cluster dataset
X, y = make_blobs(random_state=1)
for Model in [DPGMM, VBGMM]:
dpgmm = Model(n_components=10, random_state=1, alpha=20, n_iter=50)
dpgmm.fit(X)
# get indices of components that are used:
indices = np.unique(dpgmm.predict(X))
active = np.zeros(10, dtype=np.bool)
active[indices] = True
# used components are important
assert_array_less(.1, dpgmm.weights_[active])
# others are not
assert_array_less(dpgmm.weights_[~active], .05)
@ignore_warnings(category=DeprecationWarning)
def test_verbose_boolean():
# checks that the output for the verbose output is the same
# for the flag values '1' and 'True'
# simple 3 cluster dataset
X, y = make_blobs(random_state=1)
for Model in [DPGMM, VBGMM]:
dpgmm_bool = Model(n_components=10, random_state=1, alpha=20,
n_iter=50, verbose=True)
dpgmm_int = Model(n_components=10, random_state=1, alpha=20,
n_iter=50, verbose=1)
old_stdout = sys.stdout
sys.stdout = StringIO()
try:
# generate output with the boolean flag
dpgmm_bool.fit(X)
verbose_output = sys.stdout
verbose_output.seek(0)
bool_output = verbose_output.readline()
# generate output with the int flag
dpgmm_int.fit(X)
verbose_output = sys.stdout
verbose_output.seek(0)
int_output = verbose_output.readline()
assert_equal(bool_output, int_output)
finally:
sys.stdout = old_stdout
@ignore_warnings(category=DeprecationWarning)
def test_verbose_first_level():
# simple 3 cluster dataset
X, y = make_blobs(random_state=1)
for Model in [DPGMM, VBGMM]:
dpgmm = Model(n_components=10, random_state=1, alpha=20, n_iter=50,
verbose=1)
old_stdout = sys.stdout
sys.stdout = StringIO()
try:
dpgmm.fit(X)
finally:
sys.stdout = old_stdout
@ignore_warnings(category=DeprecationWarning)
def test_verbose_second_level():
# simple 3 cluster dataset
X, y = make_blobs(random_state=1)
for Model in [DPGMM, VBGMM]:
dpgmm = Model(n_components=10, random_state=1, alpha=20, n_iter=50,
verbose=2)
old_stdout = sys.stdout
sys.stdout = StringIO()
try:
dpgmm.fit(X)
finally:
sys.stdout = old_stdout
@ignore_warnings(category=DeprecationWarning)
def test_digamma():
assert_warns_message(DeprecationWarning, "The function digamma is"
" deprecated in 0.18 and will be removed in 0.20. "
"Use scipy.special.digamma instead.", digamma, 3)
@ignore_warnings(category=DeprecationWarning)
def test_gammaln():
assert_warns_message(DeprecationWarning, "The function gammaln"
" is deprecated in 0.18 and will be removed"
" in 0.20. Use scipy.special.gammaln instead.",
gammaln, 3)
@ignore_warnings(category=DeprecationWarning)
def test_log_normalize():
v = np.array([0.1, 0.8, 0.01, 0.09])
a = np.log(2 * v)
result = assert_warns_message(DeprecationWarning, "The function "
"log_normalize is deprecated in 0.18 and"
" will be removed in 0.20.",
log_normalize, a)
assert np.allclose(v, result, rtol=0.01)
@ignore_warnings(category=DeprecationWarning)
def test_wishart_log_det():
a = np.array([0.1, 0.8, 0.01, 0.09])
b = np.array([0.2, 0.7, 0.05, 0.1])
assert_warns_message(DeprecationWarning, "The function "
"wishart_log_det is deprecated in 0.18 and"
" will be removed in 0.20.",
wishart_log_det, a, b, 2, 4)
@ignore_warnings(category=DeprecationWarning)
def test_wishart_logz():
assert_warns_message(DeprecationWarning, "The function "
"wishart_logz is deprecated in 0.18 and "
"will be removed in 0.20.", wishart_logz,
3, np.identity(3), 1, 3)
@ignore_warnings(category=DeprecationWarning)
def test_DPGMM_deprecation():
assert_warns_message(
DeprecationWarning, "The `DPGMM` class is not working correctly and "
"it's better to use `sklearn.mixture.BayesianGaussianMixture` class "
"with parameter `weight_concentration_prior_type='dirichlet_process'` "
"instead. DPGMM is deprecated in 0.18 and will be removed in 0.20.",
DPGMM)
def do_model(self, **kwds):
return VBGMM(verbose=False, **kwds)
class DPGMMTester(GMMTester):
model = DPGMM
do_test_eval = False
def score(self, g, train_obs):
_, z = g.score_samples(train_obs)
return g.lower_bound(train_obs, z)
class TestDPGMMWithSphericalCovars(unittest.TestCase, DPGMMTester):
covariance_type = 'spherical'
setUp = GMMTester._setUp
class TestDPGMMWithDiagCovars(unittest.TestCase, DPGMMTester):
covariance_type = 'diag'
setUp = GMMTester._setUp
class TestDPGMMWithTiedCovars(unittest.TestCase, DPGMMTester):
covariance_type = 'tied'
setUp = GMMTester._setUp
class TestDPGMMWithFullCovars(unittest.TestCase, DPGMMTester):
covariance_type = 'full'
setUp = GMMTester._setUp
def test_VBGMM_deprecation():
assert_warns_message(
DeprecationWarning, "The `VBGMM` class is not working correctly and "
"it's better to use `sklearn.mixture.BayesianGaussianMixture` class "
"with parameter `weight_concentration_prior_type="
"'dirichlet_distribution'` instead. VBGMM is deprecated "
"in 0.18 and will be removed in 0.20.", VBGMM)
class VBGMMTester(GMMTester):
model = do_model
do_test_eval = False
def score(self, g, train_obs):
_, z = g.score_samples(train_obs)
return g.lower_bound(train_obs, z)
class TestVBGMMWithSphericalCovars(unittest.TestCase, VBGMMTester):
covariance_type = 'spherical'
setUp = GMMTester._setUp
class TestVBGMMWithDiagCovars(unittest.TestCase, VBGMMTester):
covariance_type = 'diag'
setUp = GMMTester._setUp
class TestVBGMMWithTiedCovars(unittest.TestCase, VBGMMTester):
covariance_type = 'tied'
setUp = GMMTester._setUp
class TestVBGMMWithFullCovars(unittest.TestCase, VBGMMTester):
covariance_type = 'full'
setUp = GMMTester._setUp
def test_vbgmm_no_modify_alpha():
alpha = 2.
n_components = 3
X, y = make_blobs(random_state=1)
vbgmm = VBGMM(n_components=n_components, alpha=alpha, n_iter=1)
assert_equal(vbgmm.alpha, alpha)
assert_equal(vbgmm.fit(X).alpha_, float(alpha) / n_components)
|
bsd-3-clause
|
eyaler/tensorpack
|
tensorpack/dataflow/format.py
|
1
|
9076
|
# -*- coding: utf-8 -*-
# File: format.py
import numpy as np
import six
from six.moves import range
import os
from ..utils import logger
from ..utils.utils import get_tqdm
from ..utils.timer import timed_operation
from ..utils.loadcaffe import get_caffe_pb
from ..utils.compatible_serialize import loads
from ..utils.argtools import log_once
from ..utils.develop import log_deprecated
from .base import RNGDataFlow, DataFlow, DataFlowReentrantGuard
from .common import MapData
__all__ = ['HDF5Data', 'LMDBData', 'LMDBDataDecoder', 'LMDBDataPoint',
'CaffeLMDB', 'SVMLightData', 'TFRecordData']
"""
Adapters for different data format.
"""
class HDF5Data(RNGDataFlow):
"""
Zip data from different paths in an HDF5 file.
Warning:
The current implementation will load all data into memory. (TODO)
"""
# TODO
def __init__(self, filename, data_paths, shuffle=True):
"""
Args:
filename (str): h5 data file.
data_paths (list): list of h5 paths to zipped.
For example `['images', 'labels']`.
shuffle (bool): shuffle all data.
"""
self.f = h5py.File(filename, 'r')
logger.info("Loading {} to memory...".format(filename))
self.dps = [self.f[k].value for k in data_paths]
lens = [len(k) for k in self.dps]
assert all([k == lens[0] for k in lens])
self._size = lens[0]
self.shuffle = shuffle
def __len__(self):
return self._size
def __iter__(self):
idxs = list(range(self._size))
if self.shuffle:
self.rng.shuffle(idxs)
for k in idxs:
yield [dp[k] for dp in self.dps]
class LMDBData(RNGDataFlow):
"""
Read a LMDB database and produce (k,v) raw bytes pairs.
The raw bytes are usually not what you're interested in.
You might want to use
:class:`LMDBDataDecoder` or apply a
mapper function after :class:`LMDBData`.
"""
def __init__(self, lmdb_path, shuffle=True, keys=None):
"""
Args:
lmdb_path (str): a directory or a file.
shuffle (bool): shuffle the keys or not.
keys (list[str] or str): list of str as the keys, used only when shuffle is True.
It can also be a format string e.g. ``{:0>8d}`` which will be
formatted with the indices from 0 to *total_size - 1*.
If not given, it will then look in the database for ``__keys__`` which
:func:`LMDBSerializer.save` used to store the list of keys.
If still not found, it will iterate over the database to find
all the keys.
"""
self._lmdb_path = lmdb_path
self._shuffle = shuffle
self._open_lmdb()
self._size = self._txn.stat()['entries']
self._set_keys(keys)
logger.info("Found {} entries in {}".format(self._size, self._lmdb_path))
self._guard = DataFlowReentrantGuard()
def _set_keys(self, keys=None):
def find_keys(txn, size):
logger.warn("Traversing the database to find keys is slow. Your should specify the keys.")
keys = []
with timed_operation("Loading LMDB keys ...", log_start=True), \
get_tqdm(total=size) as pbar:
for k in self._txn.cursor():
assert k[0] != b'__keys__'
keys.append(k[0])
pbar.update()
return keys
self.keys = self._txn.get(b'__keys__')
if self.keys is not None:
self.keys = loads(self.keys)
self._size -= 1 # delete this item
if self._shuffle: # keys are necessary when shuffle is True
if keys is None:
if self.keys is None:
self.keys = find_keys(self._txn, self._size)
else:
# check if key-format like '{:0>8d}' was given
if isinstance(keys, six.string_types):
self.keys = map(lambda x: keys.format(x), list(np.arange(self._size)))
else:
self.keys = keys
def _open_lmdb(self):
self._lmdb = lmdb.open(self._lmdb_path,
subdir=os.path.isdir(self._lmdb_path),
readonly=True, lock=False, readahead=True,
map_size=1099511627776 * 2, max_readers=100)
self._txn = self._lmdb.begin()
def reset_state(self):
self._lmdb.close()
super(LMDBData, self).reset_state()
self._open_lmdb()
def __len__(self):
return self._size
def __iter__(self):
with self._guard:
if not self._shuffle:
c = self._txn.cursor()
while c.next():
k, v = c.item()
if k != b'__keys__':
yield [k, v]
else:
self.rng.shuffle(self.keys)
for k in self.keys:
v = self._txn.get(k)
yield [k, v]
class LMDBDataDecoder(MapData):
""" Read a LMDB database with a custom decoder and produce decoded outputs."""
def __init__(self, lmdb_data, decoder):
"""
Args:
lmdb_data: a :class:`LMDBData` instance.
decoder (k,v -> dp | None): a function taking k, v and returning a datapoint,
or return None to discard.
"""
def f(dp):
return decoder(dp[0], dp[1])
super(LMDBDataDecoder, self).__init__(lmdb_data, f)
class LMDBDataPoint(MapData):
def __init__(self, *args, **kwargs):
log_deprecated("LMDBDataPoint", "Use LMDBSerializer.load() instead!", "2019-01-31")
if isinstance(args[0], DataFlow):
ds = args[0]
assert len(args) == 1 and len(kwargs) == 0, \
"No more arguments are allowed if LMDBDataPoint is called with a LMDBData instance!"
else:
ds = LMDBData(*args, **kwargs)
def f(dp):
return loads(dp[1])
super(LMDBDataPoint, self).__init__(ds, f)
def CaffeLMDB(lmdb_path, shuffle=True, keys=None):
"""
Read a Caffe LMDB file where each value contains a ``caffe.Datum`` protobuf.
Produces datapoints of the format: [HWC image, label].
Note that Caffe LMDB format is not efficient: it stores serialized raw
arrays rather than JPEG images.
Args:
lmdb_path, shuffle, keys: same as :class:`LMDBData`.
Returns:
a :class:`LMDBDataDecoder` instance.
Example:
.. code-block:: python
ds = CaffeLMDB("/tmp/validation", keys='{:0>8d}')
"""
cpb = get_caffe_pb()
lmdb_data = LMDBData(lmdb_path, shuffle, keys)
def decoder(k, v):
try:
datum = cpb.Datum()
datum.ParseFromString(v)
img = np.fromstring(datum.data, dtype=np.uint8)
img = img.reshape(datum.channels, datum.height, datum.width)
except Exception:
log_once("Cannot read key {}".format(k), 'warn')
return None
return [img.transpose(1, 2, 0), datum.label]
logger.warn("Caffe LMDB format doesn't store jpeg-compressed images, \
it's not recommended due to its inferior performance.")
return LMDBDataDecoder(lmdb_data, decoder)
class SVMLightData(RNGDataFlow):
""" Read X,y from an SVMlight file, and produce [X_i, y_i] pairs. """
def __init__(self, filename, shuffle=True):
"""
Args:
filename (str): input file
shuffle (bool): shuffle the data
"""
import sklearn.datasets # noqa
self.X, self.y = sklearn.datasets.load_svmlight_file(filename)
self.X = np.asarray(self.X.todense())
self.shuffle = shuffle
def __len__(self):
return len(self.y)
def __iter__(self):
idxs = np.arange(self.__len__())
if self.shuffle:
self.rng.shuffle(idxs)
for id in idxs:
yield [self.X[id, :], self.y[id]]
class TFRecordData(DataFlow):
def __init__(self, path, size=None):
log_deprecated("TFRecordData", "Use TFRecordSerializer.load instead!", "2019-01-31")
self._path = path
self._size = int(size)
def __len__(self):
if self._size:
return self._size
return len(super(TFRecordData, self))
def __iter__(self):
gen = tf.python_io.tf_record_iterator(self._path)
for dp in gen:
yield loads(dp)
from ..utils.develop import create_dummy_class # noqa
try:
import h5py
except ImportError:
HDF5Data = create_dummy_class('HDF5Data', 'h5py') # noqa
try:
import lmdb
except ImportError:
for klass in ['LMDBData', 'LMDBDataDecoder', 'LMDBDataPoint', 'CaffeLMDB']:
globals()[klass] = create_dummy_class(klass, 'lmdb')
try:
import tensorflow as tf
except ImportError:
TFRecordData = create_dummy_class('TFRecordData', 'tensorflow') # noqa
|
apache-2.0
|
manipopopo/tensorflow
|
tensorflow/python/estimator/inputs/inputs.py
|
20
|
1086
|
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utility methods to create simple input_fns."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=unused-import,line-too-long
from tensorflow.python.estimator.inputs.numpy_io import numpy_input_fn
from tensorflow.python.estimator.inputs.pandas_io import pandas_input_fn
# pylint: enable=unused-import,line-too-long
|
apache-2.0
|
alasdairtran/digbeta
|
python/digbeta/heuristics.py
|
3
|
18253
|
""" Heuristics used to query the most uncertain candidate out of the unlabelled pool. """
import numpy as np
import copy
from joblib import Parallel, delayed
from numpy.random import permutation
from sklearn.preprocessing import LabelBinarizer
from sklearn.base import clone
def random_h(candidate_mask, n_candidates, **kwargs):
""" Return a random candidate.
Parameters
----------
candidate_mask : boolean array
The boolean array that tells us which data points the heuristic should look at.
n_candidates : int
The number of best candidates to be selected at each iteration.
Returns
-------
best_candidates : int
The indices of the best candidates (here it is random).
"""
candidate_index = np.where(candidate_mask)[0]
random_index = np.random.choice(candidate_index, n_candidates, replace=False)
return random_index
def entropy_h(X, candidate_mask, classifier, n_candidates, **kwargs):
""" Return the candidate whose prediction vector displays the greatest Shannon entropy.
Parameters
----------
X : array
The feature matrix of all the data points.
candidate_mask : boolean array
The boolean array that tells us which data points the heuristic should look at.
classifier : Classifier object
A classifier object that will be used to make predictions.
It should have the same interface as scikit-learn classifiers.
n_candidates : int
The number of best candidates to be selected at each iteration.
Returns
-------
best_candidates : int
The indices of the best candidates.
"""
# predict probabilities
probs = classifier.predict_proba(X[candidate_mask])
# comptue Shannon entropy
candidate_shannon = -np.sum(probs * np.log(probs), axis=1)
# index the results properly
shannon = np.empty(len(candidate_mask))
shannon[:] = -np.inf
shannon[candidate_mask] = candidate_shannon
# pick the candidate with the greatest Shannon entropy
best_candidates = np.argsort(-shannon)[:n_candidates]
return best_candidates
def margin_h(X, candidate_mask, classifier, n_candidates, **kwargs):
""" Return the candidate with the smallest margin.
The margin is defined as the difference between the two largest values
in the prediction vector.
Parameters
----------
X : array
The feature matrix of all the data points.
candidate_mask : boolean array
The boolean array that tells us which data points the heuristic should look at.
classifier : Classifier object
A classifier object that will be used to make predictions.
It should have the same interface as scikit-learn classifiers.
n_candidates : int
The number of best candidates to be selected at each iteration.
Returns
-------
best_candidates : int
The indices of the best candidates.
"""
# predict probabilities
probs = classifier.predict_proba(X[candidate_mask])
# sort the probabilities from smallest to largest
probs = np.sort(probs, axis=1)
# compute the margin (difference between two largest values)
candidate_margin = np.abs(probs[:,-1] - probs[:,-2])
# index the results properly
margin = np.empty(len(candidate_mask))
margin[:] = +np.inf
margin[candidate_mask] = candidate_margin
# pick the candidate with the smallest margin
best_candidates = np.argsort(margin)[:n_candidates]
return best_candidates
def qbb_margin_h(X, y, candidate_mask, train_mask, n_candidates, committee,
committee_samples, **kwargs):
""" Return the candidate with the smallest average margin.
We first use bagging to train k classifiers. The margin is then defined as
the average difference between the two largest values in the prediction vector.
Parameters
----------
X : array
The feature matrix of all the data points.
y : array
The target vector of all the data points.
candidate_mask : boolean array
The boolean array that tells us which data points the heuristic should look at.
train_mask : boolean array
The boolean array that tells us which data points are currently in the training set.
n_candidates : int
The number of best candidates to be selected at each iteration.
committee : BaggingClassifier object
The committee should have the same interface as scikit-learn BaggingClassifier.
Returns
-------
best_candidates : int
The indices of the best candidates.
"""
# check that the max bagging sample is not too big
committee.max_samples = min(committee_samples, len(y[train_mask]))
# train and predict
committee.fit(X[train_mask], y[train_mask])
# predict
n_samples = len(X[candidate_mask])
n_classes = len(committee.classes_)
probs = np.zeros((n_samples, n_classes))
for member in committee.estimators_:
memeber_prob = member.predict_proba(X[candidate_mask])
if n_classes == len(member.classes_):
probs += memeber_prob
else:
probs[:, member.classes_] += memeber_prob[:, range(len(member.classes_))]
# average out the probabilities
probs /= len(committee.estimators_)
# sort the probabilities from smallest to largest
probs = np.sort(probs, axis=1)
# compute the margin (difference between two largest values)
candidate_margin = np.abs(probs[:,-1] - probs[:,-2])
# index the results properly
margin = np.empty(len(candidate_mask))
margin[:] = +np.inf
margin[candidate_mask] = candidate_margin
# pick the candidate with the smallest margin
best_candidates = np.argsort(margin)[:n_candidates]
return best_candidates
def qbb_kl_h(X, y, candidate_mask, train_mask, n_candidates, committee, committee_samples,
**kwargs):
""" Return the candidate with the largest average KL divergence from the mean.
We first use bagging to train k classifiers. We then choose the candidate
that has the largest Kullback–Leibler divergence from the average.
Parameters
----------
X : array
The feature matrix of all the data points.
y : array
The target vector of all the data points.
candidate_mask : boolean array
The boolean array that tells us which data points the heuristic should look at.
train_mask : boolean array
The boolean array that tells us which data points are currently in the training set.
n_candidates : int
The number of best candidates to be selected at each iteration.
committee : BaggingClassifier object
The committee should have the same interface as scikit-learn BaggingClassifier.
Returns
-------
best_candidates : int
The indices of the best candidates.
"""
# check that the max bagging sample is not too big
committee.max_samples = min(committee_samples, len(y[train_mask]))
# train the committee
committee.fit(X[train_mask], y[train_mask])
# predict
n_samples = len(X[candidate_mask])
n_classes = len(committee.classes_)
avg_probs = np.zeros((n_samples, n_classes))
prob_list = []
for member in committee.estimators_:
member_prob = member.predict_proba(X[candidate_mask])
if n_classes == len(member.classes_):
avg_probs += member_prob
prob_list.append(member_prob)
else:
full_member_prob = np.zeros((n_samples, n_classes))
full_member_prob[:, member.classes_] += member_prob[:, range(len(member.classes_))]
avg_probs += full_member_prob
prob_list.append(full_member_prob)
# average out the probabilities
avg_probs /= len(committee.estimators_)
# compute the KL divergence
avg_kl = np.zeros(avg_probs.shape[0])
for p in prob_list:
inner = np.nan_to_num(p * np.log(p / avg_probs))
member_kl = np.sum(inner, axis=1)
avg_kl += member_kl
# average out the KL divergence
avg_kl /= len(committee)
# index the results properly
kl = np.empty(len(candidate_mask))
kl[:] = -np.inf
kl[candidate_mask] = avg_kl
# pick the candidate with the smallest margin
best_candidates = np.argsort(-kl)[:n_candidates]
return best_candidates
def _compute_A(X, pi, classes):
""" Compute the A matrix in the variance estimation technique.
Parameters
----------
X : array
The feature matrix.
pi : array
The probability matrix predicted by the classifier.
classes : array
The list of class names ordered lexicographically.
Returns
-------
A : array
The A matrix as part of the variance calcucation.
"""
n_classes = len(classes)
n_features = X.shape[1]
n_samples = X.shape[0]
width = n_classes * n_features
one_in_k = LabelBinarizer(pos_label=1, neg_label=0).fit_transform(classes)
I_same = one_in_k.repeat(n_features, axis=0)
I_same = np.tile(I_same, n_samples)
I_diff = 1 - I_same
A = np.tile(pi.flatten(), (width, 1))
B = 1 - A
C = -A
D = pi.transpose().repeat(n_features, axis=0).repeat(n_classes, axis=1)
E = X.transpose().repeat(n_classes, axis=1)
E = np.tile(E, (n_classes, 1))
G = A * B * I_same + C * D * I_diff
G = E * G
outer = np.dot(G, G.transpose())
return outer
def _compute_F(X, pi, classes, C=1):
""" Compute the F matrix in the variance estimation technqiue.
Parameters
----------
X : array
The feature matrix.
pi : array
The probability matrix predicted by the classifier.
classes : array
The list of class names ordered lexicographically.
C : float
The regularisation parameter in logistic regression.
Returns
-------
F : array
The F matrix as part of the variance calcucation.
"""
n_classes = len(classes)
n_features = X.shape[1]
n_samples = X.shape[0]
width = n_classes * n_features
I_diag = np.eye(width)
mini_off_diag = 1 - np.eye(n_features)
mini_zeros = np.zeros((n_features, n_features * n_classes))
I_mini_off_diag = np.hstack((mini_off_diag, mini_zeros))
I_mini_off_diag = np.tile(I_mini_off_diag, n_classes - 1)
I_mini_off_diag = np.hstack((I_mini_off_diag, mini_off_diag))
I_mini_off_diag = np.hsplit(I_mini_off_diag, n_classes)
I_mini_off_diag = np.vstack(I_mini_off_diag)
I_main_off_diag = 1 - I_diag - I_mini_off_diag
M = np.tile(X.transpose(), (n_classes, 1))
N = pi.transpose().repeat(n_features, axis=0)
F_1 = np.dot(M * N * (1 - N), M.transpose()) + C
F_2 = np.dot(M * N * (1 - N), M.transpose())
F_3 = np.dot(M * N, M.transpose() * N.transpose())
F = F_1 * I_diag + F_2 * I_mini_off_diag + F_3 * I_main_off_diag
F = F / n_samples
return F
def compute_pool_variance(X, pi, classes, C=1):
""" Estimate the variance of the pool.
Parameters
----------
X : array
The feature matrix.
pi : array
The probability matrix predicted by the classifier.
classes : array
The list of class names ordered lexicographically.
C : float
The regularisation parameter in logistic regression.
Returns
-------
variance : float
The estimated variance on the pool X.
"""
A = _compute_A(X, pi, classes)
F = _compute_F(X, pi, classes, C=C)
return np.trace(np.dot(A, np.linalg.inv(F)))
def pool_variance_h(X, y, candidate_mask, train_mask, classifier, n_candidates,
pool_n, C, n_jobs=-1, **kwargs):
""" Return the candidate that will minimise the expected variance of the predictions.
Parameters
----------
X_training_candidates : array
The feature matrix of the potential training candidates.
C : float
The regularisation parameter of Logistic Regression.
pool_sample_size : int
The size of the sample which will be used to estimate the variance/entropy.
n_jobs : int
The number of parallel jobs (-1 if want to use all cores)
Returns
-------
best_candidate : int
The index of the best candidate.
"""
classes = classifier.classes_ # sorted lexicographically
n_classes = len(classes)
candidate_size = np.sum(train_mask)
n_features = X.shape[1]
variance = np.empty(len(candidate_mask))
variance[:] = np.inf
# the probabilities used to calculate expected value of pool
probs = classifier.predict_proba(X[candidate_mask])
# copy the classifier (avoid modifying the original classifier)
classifier_plus = clone(classifier)
# construct the sample pool (used to estimate the variance)
unlabelled_indices = np.where(-train_mask)[0]
pool_indices = permutation(unlabelled_indices)[:pool_n]
pool_mask = np.zeros(len(candidate_mask), dtype=bool)
pool_mask[pool_indices] = True
# let's look at each candidate
candidate_indices = np.where(candidate_mask)[0]
results = Parallel(n_jobs=n_jobs)(delayed(_parallel_variance_estimate)(
X, y.copy(), train_mask.copy(), pool_mask,
clone(classifier_plus), classes, n_classes, probs, i, index, C)
for i, index in enumerate(candidate_indices))
indices, expected = zip(*results)
indices, expected = np.asarray(indices), np.asarray(expected)
assert not np.isnan(expected).any(), 'Some expected values are undefined.'
variance[indices] = expected
# pick the candidate with the smallest expected variance
best_candidates = np.argsort(variance)[:n_candidates]
return best_candidates
def _parallel_variance_estimate(X, y, train_mask, pool_mask, classifier,
classes, n_classes, probs, i, index, C):
""" Helper function. """
# assume a label and compute entropy
potential_variance = np.zeros(n_classes)
train_mask[index] = True
for cls_idx, cls in enumerate(classes):
y[index] = cls
classifier.fit(X[train_mask], y[train_mask])
pi = classifier.predict_proba(X[pool_mask])
potential_variance[cls_idx] = compute_pool_variance(X[pool_mask], pi, classes, C)
# calculate expected entropy and save result
expected = np.dot(probs[i], potential_variance)
return index, expected
def compute_pool_entropy(pi):
""" Estimate the variance of the pool.
Parameters
----------
pi : array
The probability matrix predicted by the classifier.
Returns
-------
entropy : float
The estimated entropy on the pool.
"""
return np.nan_to_num(-np.sum(pi * np.log(pi)))
def pool_entropy_h(X, y, candidate_mask, train_mask, classifier, n_candidates,
pool_n, n_jobs=-1, **kwargs):
""" Return the candidate that will minimise the expected entropy of the predictions.
Parameters
----------
X_training_candidates : array
The feature matrix of the potential training candidates.
classes : int
The name of classes.
pool_n : int
The size of the sampel pool used in estimating the entropy
n_jobs : int
The number of parallel jobs (-1 if want to use all cores)
Returns
-------
best_candidate : int
The index of the best candidate.
"""
classes = classifier.classes_ # sorted lexicographically
n_classes = len(classes)
candidate_size = np.sum(train_mask)
n_features = X.shape[1]
entropy = np.empty(len(candidate_mask))
entropy[:] = np.inf
# the probabilities used to calculate expected value of pool
probs = classifier.predict_proba(X[candidate_mask])
# copy the classifier (avoid modifying the original classifier)
classifier_plus = clone(classifier)
# construct the sample pool (used to estimate the entropy)
unlabelled_indices = np.where(-train_mask)[0]
pool_indices = permutation(unlabelled_indices)[:pool_n]
pool_mask = np.zeros(len(candidate_mask), dtype=bool)
pool_mask[pool_indices] = True
# let's look at each candidate
candidate_indices = np.where(candidate_mask)[0]
results = Parallel(n_jobs=n_jobs)(delayed(_parallel_entropy_estimate)(
X, y.copy(), train_mask.copy(), pool_mask,
clone(classifier_plus), classes, n_classes, probs, i, index)
for i, index in enumerate(candidate_indices))
indices, expected = zip(*results)
indices, expected = np.asarray(indices), np.asarray(expected)
assert not np.isnan(expected).any(), 'Some expected values are undefined.'
entropy[indices] = expected
# pick the candidate with the smallest expected entropy
best_candidates = np.argsort(entropy)[:n_candidates]
return best_candidates
def _parallel_entropy_estimate(X, y, train_mask, pool_mask, classifier,
classes, n_classes, probs, i, index):
""" Helper function. """
# assume a label and compute entropy
potential_entropy = np.zeros(n_classes)
train_mask[index] = True
for cls_idx, cls in enumerate(classes):
y[index] = cls
classifier.fit(X[train_mask], y[train_mask])
pi = classifier.predict_proba(X[pool_mask])
potential_entropy[cls_idx] = compute_pool_entropy(pi)
# calculate expected entropy and save result
expected = np.dot(probs[i], potential_entropy)
return index, expected
|
gpl-3.0
|
kaichogami/scikit-learn
|
examples/bicluster/plot_spectral_coclustering.py
|
276
|
1736
|
"""
==============================================
A demo of the Spectral Co-Clustering algorithm
==============================================
This example demonstrates how to generate a dataset and bicluster it
using the the Spectral Co-Clustering algorithm.
The dataset is generated using the ``make_biclusters`` function, which
creates a matrix of small values and implants bicluster with large
values. The rows and columns are then shuffled and passed to the
Spectral Co-Clustering algorithm. Rearranging the shuffled matrix to
make biclusters contiguous shows how accurately the algorithm found
the biclusters.
"""
print(__doc__)
# Author: Kemal Eren <[email protected]>
# License: BSD 3 clause
import numpy as np
from matplotlib import pyplot as plt
from sklearn.datasets import make_biclusters
from sklearn.datasets import samples_generator as sg
from sklearn.cluster.bicluster import SpectralCoclustering
from sklearn.metrics import consensus_score
data, rows, columns = make_biclusters(
shape=(300, 300), n_clusters=5, noise=5,
shuffle=False, random_state=0)
plt.matshow(data, cmap=plt.cm.Blues)
plt.title("Original dataset")
data, row_idx, col_idx = sg._shuffle(data, random_state=0)
plt.matshow(data, cmap=plt.cm.Blues)
plt.title("Shuffled dataset")
model = SpectralCoclustering(n_clusters=5, random_state=0)
model.fit(data)
score = consensus_score(model.biclusters_,
(rows[:, row_idx], columns[:, col_idx]))
print("consensus score: {:.3f}".format(score))
fit_data = data[np.argsort(model.row_labels_)]
fit_data = fit_data[:, np.argsort(model.column_labels_)]
plt.matshow(fit_data, cmap=plt.cm.Blues)
plt.title("After biclustering; rearranged to show biclusters")
plt.show()
|
bsd-3-clause
|
tdhopper/scikit-learn
|
examples/decomposition/plot_kernel_pca.py
|
353
|
2011
|
"""
==========
Kernel PCA
==========
This example shows that Kernel PCA is able to find a projection of the data
that makes data linearly separable.
"""
print(__doc__)
# Authors: Mathieu Blondel
# Andreas Mueller
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA, KernelPCA
from sklearn.datasets import make_circles
np.random.seed(0)
X, y = make_circles(n_samples=400, factor=.3, noise=.05)
kpca = KernelPCA(kernel="rbf", fit_inverse_transform=True, gamma=10)
X_kpca = kpca.fit_transform(X)
X_back = kpca.inverse_transform(X_kpca)
pca = PCA()
X_pca = pca.fit_transform(X)
# Plot results
plt.figure()
plt.subplot(2, 2, 1, aspect='equal')
plt.title("Original space")
reds = y == 0
blues = y == 1
plt.plot(X[reds, 0], X[reds, 1], "ro")
plt.plot(X[blues, 0], X[blues, 1], "bo")
plt.xlabel("$x_1$")
plt.ylabel("$x_2$")
X1, X2 = np.meshgrid(np.linspace(-1.5, 1.5, 50), np.linspace(-1.5, 1.5, 50))
X_grid = np.array([np.ravel(X1), np.ravel(X2)]).T
# projection on the first principal component (in the phi space)
Z_grid = kpca.transform(X_grid)[:, 0].reshape(X1.shape)
plt.contour(X1, X2, Z_grid, colors='grey', linewidths=1, origin='lower')
plt.subplot(2, 2, 2, aspect='equal')
plt.plot(X_pca[reds, 0], X_pca[reds, 1], "ro")
plt.plot(X_pca[blues, 0], X_pca[blues, 1], "bo")
plt.title("Projection by PCA")
plt.xlabel("1st principal component")
plt.ylabel("2nd component")
plt.subplot(2, 2, 3, aspect='equal')
plt.plot(X_kpca[reds, 0], X_kpca[reds, 1], "ro")
plt.plot(X_kpca[blues, 0], X_kpca[blues, 1], "bo")
plt.title("Projection by KPCA")
plt.xlabel("1st principal component in space induced by $\phi$")
plt.ylabel("2nd component")
plt.subplot(2, 2, 4, aspect='equal')
plt.plot(X_back[reds, 0], X_back[reds, 1], "ro")
plt.plot(X_back[blues, 0], X_back[blues, 1], "bo")
plt.title("Original space after inverse transform")
plt.xlabel("$x_1$")
plt.ylabel("$x_2$")
plt.subplots_adjust(0.02, 0.10, 0.98, 0.94, 0.04, 0.35)
plt.show()
|
bsd-3-clause
|
Jordan-Zhu/EdgeSegmentFitting
|
algo.py
|
1
|
2155
|
import cv2
import numpy as np
from matplotlib import pyplot as plt
def auto_canny(image, sigma=0.33):
# compute the median of the single channel pixel intensities
v = np.median(image)
# apply automatic Canny edge detection using the computed median
lower = int(max(0, (1.0 - sigma) * v))
upper = int(min(255, (1.0 + sigma) * v))
edged = cv2.Canny(image, lower, upper)
# return the edged image
return edged
def showimg(img, type='cv', write=False, imagename='img.png'):
if type == 'plt':
plt.figure()
plt.imshow(img, 'gray', interpolation='nearest', aspect='auto')
# plt.imshow(img, 'gray', interpolation='none')
plt.title('morphology')
plt.show()
if write:
plt.savefig(imagename, bbox_inches='tight')
elif type == 'cv':
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
if write:
cv2.imwrite("../../images/%s", imagename, img)
def grad_dir(img):
# compute x and y derivatives
# OpenCV's Sobel operator gives better results than numpy gradient
sobelx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=-1)
sobely = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=-1)
# calculate gradient direction angles
# phase needs 64-bit input
angle = cv2.phase(sobelx, sobely)
# truncates number
gradir = np.fix(180 + angle)
return gradir
if __name__ == '__main__':
# second argument is a flag which specifies the way
# an image should be read. -1 loads image unchanged with alpha channel
depthimg = cv2.imread('img/learn17.png', -1)
colorimg = cv2.imread('img/clearn17.png', 0)
# Normalize depth image
min, max, minloc, maxloc = cv2.minMaxLoc(depthimg)
adjmap = np.zeros_like(depthimg)
dst = cv2.convertScaleAbs(depthimg, adjmap, 255 / (max-min), -min)
im_color = cv2.applyColorMap(dst, cv2.COLORMAP_JET)
showimg(im_color)
# img = cv2.imread('img\clearn5.png', -1)
#
# cv2.imshow('image', img)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
|
agpl-3.0
|
RPGOne/Skynet
|
scikit-learn-0.18.1/examples/cluster/plot_kmeans_assumptions.py
|
270
|
2040
|
"""
====================================
Demonstration of k-means assumptions
====================================
This example is meant to illustrate situations where k-means will produce
unintuitive and possibly unexpected clusters. In the first three plots, the
input data does not conform to some implicit assumption that k-means makes and
undesirable clusters are produced as a result. In the last plot, k-means
returns intuitive clusters despite unevenly sized blobs.
"""
print(__doc__)
# Author: Phil Roth <[email protected]>
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
plt.figure(figsize=(12, 12))
n_samples = 1500
random_state = 170
X, y = make_blobs(n_samples=n_samples, random_state=random_state)
# Incorrect number of clusters
y_pred = KMeans(n_clusters=2, random_state=random_state).fit_predict(X)
plt.subplot(221)
plt.scatter(X[:, 0], X[:, 1], c=y_pred)
plt.title("Incorrect Number of Blobs")
# Anisotropicly distributed data
transformation = [[ 0.60834549, -0.63667341], [-0.40887718, 0.85253229]]
X_aniso = np.dot(X, transformation)
y_pred = KMeans(n_clusters=3, random_state=random_state).fit_predict(X_aniso)
plt.subplot(222)
plt.scatter(X_aniso[:, 0], X_aniso[:, 1], c=y_pred)
plt.title("Anisotropicly Distributed Blobs")
# Different variance
X_varied, y_varied = make_blobs(n_samples=n_samples,
cluster_std=[1.0, 2.5, 0.5],
random_state=random_state)
y_pred = KMeans(n_clusters=3, random_state=random_state).fit_predict(X_varied)
plt.subplot(223)
plt.scatter(X_varied[:, 0], X_varied[:, 1], c=y_pred)
plt.title("Unequal Variance")
# Unevenly sized blobs
X_filtered = np.vstack((X[y == 0][:500], X[y == 1][:100], X[y == 2][:10]))
y_pred = KMeans(n_clusters=3, random_state=random_state).fit_predict(X_filtered)
plt.subplot(224)
plt.scatter(X_filtered[:, 0], X_filtered[:, 1], c=y_pred)
plt.title("Unevenly Sized Blobs")
plt.show()
|
bsd-3-clause
|
claesenm/optunity-benchmark
|
HPOlib/Plotting/plotTrace.py
|
5
|
6695
|
#!/usr/bin/env python
##
# wrapping: A program making it easy to use hyperparameter
# optimization software.
# Copyright (C) 2013 Katharina Eggensperger and Matthias Feurer
#
# 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 argparse import ArgumentParser
import itertools
import sys
import cPickle
from matplotlib.pyplot import tight_layout, figure, subplots_adjust, subplot, savefig, show, yscale
import matplotlib.gridspec
import numpy as np
import scipy.stats as sc
from HPOlib.Plotting import plot_util
__authors__ = ["Katharina Eggensperger", "Matthias Feurer"]
__contact__ = "automl.org"
def plot_optimization_trace(trial_list, name_list, optimum=0, title="", log=False,
save="", y_min=0, y_max=0, cut=sys.maxint):
markers = plot_util.get_plot_markers()
colors = plot_util.get_plot_colors()
linestyles = itertools.cycle(['-'])
size = 1
# get handles
ratio = 5
gs = matplotlib.gridspec.GridSpec(ratio, 1)
fig = figure(1, dpi=100)
fig.suptitle(title, fontsize=16)
ax = subplot(gs[0:ratio, :])
ax.grid(True, linestyle='-', which='major', color='lightgrey', alpha=0.5)
min_val = sys.maxint
max_val = -sys.maxint
max_trials = 0
# This might not do what we actually want; Ideally it would only take the
# ones that where actually run according to instance_order
for i in range(len(name_list)):
print cut, len(trial_list[i])
num_plotted_trials = np.min([cut, len(trial_list[i])])
print num_plotted_trials
x = range(num_plotted_trials)
y = np.zeros((num_plotted_trials))
line = np.zeros((num_plotted_trials))
for j, inst_res in enumerate(trial_list[i][:num_plotted_trials]):
if j >= len(y):
break
if type(inst_res) == np.ndarray and not np.isfinite(inst_res).any():
inst_res[np.isnan(inst_res)] = 1
elif type(inst_res) != np.ndarray and np.isnan(inst_res):
inst_res = 1
tmp = sc.nanmean(np.array([inst_res, inst_res]).flat) # Black Magic
if log:
y[j] = np.log(tmp - optimum)
line[j] = np.min(y[:j + 1])
else:
y[j] = tmp - optimum
line[j] = np.min(y[:j + 1])
# Plot the stuff
marker = markers.next()
color = colors.next()
l = linestyles.next()
ax.scatter(np.argmin(line), min(line), facecolor="w", edgecolor=color,
s=size*10*15, marker=marker)
ax.scatter(x, y, color=color, marker=marker, s=size*15)
ax.plot(x, line, color=color, label=name_list[i][0], linestyle=l, linewidth=size)
if min(y) < min_val:
min_val = min(y)
if max(y) > max_val:
max_val = max(y)
if num_plotted_trials > max_trials:
max_trials = num_plotted_trials
# Describe and label the stuff
ax.set_xlabel("#Function evaluations")
if log:
ax.set_ylabel("log10(Minfunction value)")
else:
ax.set_ylabel("Minfunction value")
if y_min == y_max:
ax.set_ylim([min_val - 0.1, max_val + 0.1])
else:
ax.set_ylim([y_min, y_max])
ax.set_xlim([0, max_trials])
leg = ax.legend(loc='best', fancybox=True)
leg.get_frame().set_alpha(0.5)
tight_layout()
subplots_adjust(top=0.85)
if save != "":
savefig(save, dpi=100, facecolor='w', edgecolor='w',
orientation='portrait', papertype=None, format=None,
transparent=False, bbox_inches="tight", pad_inches=0.1)
else:
show()
def main(pkl_list, name_list, optimum=0, title="", log=False, save="", y_max=0,
y_min=0, cut=sys.maxint):
trial_list = list()
for i in range(len(pkl_list)):
if len(pkl_list[i]) != 1:
raise ValueError("%s is more than <onePickle>!" % str(pkl_list))
fh = open(pkl_list[i][0])
trl = cPickle.load(fh)
fh.close()
trial_list.append(plot_util.extract_trials(trl))
sys.stdout.write("Plotting trace\n")
plot_optimization_trace(trial_list=trial_list, name_list=name_list, optimum=optimum,
title=title, log=log, save=save, y_max=y_max,
y_min=y_min, cut=cut)
if save != "":
sys.stdout.write("Saved plot to " + save + "\n")
else:
sys.stdout.write("..Done\n")
if __name__ == "__main__":
prog = "python plotTrace.py WhatIsThis <onePickle> [WhatIsThis <onePickle>]"
description = "Plot a Trace with evaluated points wrt to performance"
parser = ArgumentParser(description=description, prog=prog)
# Options for specific benchmarks
parser.add_argument("-o", "--optimum", type=float, dest="optimum",
default=0, help="If not set, the optimum is supposed to be zero")
# General Options
parser.add_argument("-l", "--log", action="store_true", dest="log",
default=False, help="Plot on log scale")
parser.add_argument("--max", dest="max", type=float,
default=0, help="Maximum of the plot")
parser.add_argument("--min", dest="min", type=float,
default=0, help="Minimum of the plot")
parser.add_argument("-s", "--save", dest="save",
default="", help="Where to save plot instead of showing it?")
parser.add_argument("-t", "--title", dest="title",
default="", help="Optional supertitle for plot")
parser.add_argument("-c", "--cut", default=sys.maxint, type=int,
help="Cut experiment pickles after a specified number of trials.")
args, unknown = parser.parse_known_args()
sys.stdout.write("Found " + str(len(unknown)) + " arguments\n")
pkl_list_main, name_list_main = plot_util.get_pkl_and_name_list(unknown)
main(pkl_list=pkl_list_main, name_list=name_list_main, optimum=args.optimum,
title=args.title, log=args.log, save=args.save, y_max=args.max,
y_min=args.min, cut=args.cut)
|
gpl-3.0
|
metinsay/docluster
|
docluster/models/document_embedding/tfidf.py
|
1
|
6463
|
import pandas as pd
import numpy as np
from docluster.core import Model
from docluster.core.preprocessing import Preprocessor
from docluster.utils.constants import DistanceMetric, FileType
from docluster.utils.data_fetcher import FileFetcher
from docluster.utils.data_saver import FileSaver
from docluster.utils.visual import Grapher
class TfIdf(Model):
def __init__(self, n_words=10000, min_df=0.0, max_df=1.0, do_idf=True, preprocessor=Preprocessor(), do_plot=False, model_name='TfIdf'):
""" Initialize TfIdf
n_words - the number of words that is going to be in the vocab, eliminating
less frequent words
min_df - minimum document freqeuncy for a word to be included
max_df - maximum document frequency for a word to be included
do_idf - do perform inverse document frequency
preprocessor - the proproccessor that is going to tokenize the documents
do_plot - do plot scatter plot after fitting
model_name : str
Name of the model that will be used for printing and saving purposes.
"""
self.n_words = n_words
self.min_df = min_df
self.max_df = max_df
self.do_idf = do_idf
self.preprocessor = preprocessor
self.do_plot = do_plot
self.model_name = model_name
self.vocab = None
self.tfidf_vector = None
def fit(self, documents):
""" Run Tf-Idf on the documents
documents - an N list respresenting the documents
returns:
tfidf_vector - a NxD ndarray containing the the Tf-Idf vectors with D vocab
"""
n_documents = len(documents)
doc_tfs = []
df_map = {}
self.document_tokens = []
# Prepare df and tf maps
for index, document in enumerate(documents):
tf_map = {}
doc_tokens = self.preprocessor.fit(document)
self.document_tokens.append(doc_tokens)
# Each token in the document add the index of document to df, and add 1 to tf
for token in doc_tokens:
df_map[token] = set(
[index]) if token not in df_map else df_map[token] | set([index])
tf_map[token] = 1 if token not in tf_map else tf_map[token] + 1
doc_tfs.append(tf_map)
# Only filter the vocab if necessary
if self.max_df - self.min_df != 1.0:
def does_token_stay(item): return self.min_df <= len(
item[1]) / n_documents <= self.max_df
self.vocab = list(
map(lambda item: item[0], filter(does_token_stay, df_map.items())))
else:
self.vocab = list(map(lambda item: item[0], df_map.items()))
# Create vocab_to_doc map for easy and fast lookup
self.vocab_to_doc = {token: index for index, token in enumerate(self.vocab)}
n_vocab = len(self.vocab)
tfidf_vector = np.zeros((n_documents, n_vocab))
# Fill out tfidf_vector
for doc_id, token_map in enumerate(doc_tfs):
for token, tf in token_map.items():
if token in self.vocab_to_doc:
token_id = self.vocab_to_doc[token]
idf = np.log(n_documents / len(df_map[token])) if self.do_idf else 1
tfidf_vector[doc_id, token_id] = tf * idf
self.tfidf_vector = tfidf_vector
self.total_term_freq = np.sum(self.tfidf_vector, axis=0)
indices = (-self.total_term_freq).argsort()[:self.n_words]
self.vocab = list(np.take(self.vocab, indices))
self.tfidf_vector = np.take(self.tfidf_vector, indices)
if self.do_plot:
color_assignments = list(
map(lambda label: 'r' if label == 0 else 'b', documents.index))
Grapher().plot_scatter(tfidf_vector, color_assignments=color_assignments,
title="Scatter plot of document vectors")
return tfidf_vector
def get_values_of_token(self, token, safe=True):
""" Get the vector of a particular token
token - a string token
safe - Check if the token is present in the model
returns:
token_vector - a N ndarray containing the Tf-Idf score
of the token with each document
"""
if not safe or token in self.vocab_to_doc:
token_id = self.vocab_to_doc[token]
n_documents = self.tfidf_vector.shape[0]
return np.array([self.tfidf_vector[doc_id, token_id] for doc_id in range(n_documents)])
def get_token_vectors(self, do_plot=False):
""" Get the matrix of token vectors each representing
the Tf-Idf score of them for each document
do_plot - do plot scatter plot of token vectors
returns:
token_vector - a NxD ndarray containing the token vectors
"""
n_documents = self.tfidf_vector.shape[0]
n_vocab = len(self.vocab)
tokens_vector = np.zeros((n_vocab, n_documents))
for token in self.vocab:
token_id = self.vocab_to_doc[token]
tokens_vector[token_id] = self.get_values_of_token(token, safe=False)
if do_plot:
Grapher().plot_scatter(tokens_vector, labels=self.vocab, title="Scatter plot of token vectors")
return tokens_vector
def save_model(self, model_name, file_type=FileType.csv, safe=True, directory_path=None):
""" Save the fitted model
model_name - the model name / file name
file_type - the type of file (csv, txt, ...)
returns:
token_vector - a NxD ndarray containing the token vectors
"""
if self.tfidf_vector is None:
return False
data = pd.DataFrame(self.tfidf_vector)
data.columns = self.vocab
if directory_path:
file_saver = FileSaver(directory_path=directory_path)
else:
file_saver = FileSaver()
return file_saver.save(data, model_name, file_type=file_type, safe=safe)
def load_model(self, model_name, file_type=FileType.csv, directory_path=None):
if directory_path:
file_fetcher = FileFetcher(directory_path=directory_path)
else:
file_fetcher = FileFetcher()
data = file_fetcher.load(model_name, file_type)
self.tfidf_vector = data.as_matrix()
self.vocab = data.columns.tolist()
|
mit
|
pandegroup/osprey
|
osprey/fit_estimator.py
|
2
|
6253
|
from __future__ import print_function, absolute_import, division
import time
from distutils.version import LooseVersion
import numpy as np
import sklearn
from sklearn.base import is_classifier, clone
from sklearn.metrics.scorer import check_scoring
from sklearn.externals.joblib import Parallel, delayed
from sklearn.model_selection import check_cv
from sklearn.model_selection._validation import _safe_split, _score
from .utils import check_arrays, num_samples
from .utils import short_format_time, is_msmbuilder_estimator
if LooseVersion(sklearn.__version__) < LooseVersion('0.16.1'):
raise ImportError('Please upgrade to the latest version of scikit-learn')
def fit_and_score_estimator(estimator, parameters, cv, X, y=None, scoring=None,
iid=True, n_jobs=1, verbose=1,
pre_dispatch='2*n_jobs'):
"""Fit and score an estimator with cross-validation
This function is basically a copy of sklearn's
model_selection._BaseSearchCV._fit(), which is the core of the GridSearchCV
fit() method. Unfortunately, that class does _not_ return the training
set scores, which we want to save in the database, and because of the
way it's written, you can't change it by subclassing or monkeypatching.
This function uses some undocumented internal sklearn APIs (non-public).
It was written against sklearn version 0.16.1. Prior Versions are likely
to fail due to changes in the design of cross_validation module.
Returns
-------
out : dict, with keys 'mean_test_score' 'test_scores', 'train_scores'
The scores on the training and test sets, as well as the mean test set
score.
"""
scorer = check_scoring(estimator, scoring=scoring)
n_samples = num_samples(X)
X, y = check_arrays(X, y, allow_lists=True, sparse_format='csr',
allow_nans=True)
if y is not None:
if len(y) != n_samples:
raise ValueError('Target variable (y) has a different number '
'of samples (%i) than data (X: %i samples)'
% (len(y), n_samples))
cv = check_cv(cv=cv, y=y, classifier=is_classifier(estimator))
out = Parallel(
n_jobs=n_jobs, verbose=verbose, pre_dispatch=pre_dispatch
)(
delayed(_fit_and_score)(clone(estimator), X, y, scorer,
train, test, verbose, parameters,
fit_params=None)
for train, test in cv.split(X, y))
assert len(out) == cv.n_splits
train_scores, test_scores = [], []
n_train_samples, n_test_samples = [], []
for test_score, n_test, train_score, n_train, _ in out:
train_scores.append(train_score)
test_scores.append(test_score)
n_test_samples.append(n_test)
n_train_samples.append(n_train)
train_scores, test_scores = map(list, check_arrays(train_scores,
test_scores,
warn_nans=True,
replace_nans=True))
if iid:
if verbose > 0 and is_msmbuilder_estimator(estimator):
print('[CV] Using MSMBuilder API n_samples averaging')
print('[CV] n_train_samples: %s' % str(n_train_samples))
print('[CV] n_test_samples: %s' % str(n_test_samples))
mean_test_score = np.average(test_scores, weights=n_test_samples)
mean_train_score = np.average(train_scores, weights=n_train_samples)
else:
mean_test_score = np.average(test_scores)
mean_train_score = np.average(train_scores)
grid_scores = {
'mean_test_score': mean_test_score, 'test_scores': test_scores,
'mean_train_score': mean_train_score, 'train_scores': train_scores,
'n_test_samples': n_test_samples, 'n_train_samples': n_train_samples}
return grid_scores
def _fit_and_score(estimator, X, y, scorer, train, test, verbose, parameters,
fit_params=None):
if verbose > 1:
if parameters is None:
msg = "no parameters to be set"
else:
msg = '%s' % (', '.join('%s=%s' % (k, v)
for k, v in parameters.items()))
print("[CV] %s %s" % (msg, (64 - len(msg)) * '.'))
if num_samples(train) == 0 or num_samples(test) == 0:
raise RuntimeError(
'Cross validation error in fit_estimator. The total data set '
'contains %d elements, which were split into a training set '
'of %d elements and a test set of %d elements. Unfortunately, '
'you can\'t have a %s set with 0 elements.' % (
num_samples(X), num_samples(train), num_samples(test),
'training' if num_samples(train) == 0 else 'test'))
# adjust length of sample weights
n_samples = num_samples(X)
fit_params = fit_params if fit_params is not None else {}
fit_params = dict([(k, np.asarray(v)[train]
if hasattr(v, '__len__') and len(v) == n_samples else v)
for k, v in fit_params.items()])
if parameters is not None:
estimator.set_params(**parameters)
# fit and score
start_time = time.time()
X_train, y_train = _safe_split(estimator, X, y, train)
X_test, y_test = _safe_split(estimator, X, y, test, train)
if y_train is None:
estimator.fit(X_train, **fit_params)
else:
estimator.fit(X_train, y_train, **fit_params)
test_score = _score(estimator, X_test, y_test, scorer)
train_score = _score(estimator, X_train, y_train, scorer)
scoring_time = time.time() - start_time
msmbuilder_api = is_msmbuilder_estimator(estimator)
n_samples_test = num_samples(X_test, is_nested=msmbuilder_api)
n_samples_train = num_samples(X_train, is_nested=msmbuilder_api)
if verbose > 2:
msg += ", score=%f" % test_score
if verbose > 1:
end_msg = "%s -%s" % (msg, short_format_time(scoring_time))
print("[CV] %s %s" % ((64 - len(end_msg)) * '.', end_msg))
return (test_score, n_samples_test, train_score, n_samples_train,
scoring_time)
|
apache-2.0
|
qifeigit/scikit-learn
|
examples/linear_model/plot_sgd_loss_functions.py
|
249
|
1095
|
"""
==========================
SGD: convex loss functions
==========================
A plot that compares the various convex loss functions supported by
:class:`sklearn.linear_model.SGDClassifier` .
"""
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
def modified_huber_loss(y_true, y_pred):
z = y_pred * y_true
loss = -4 * z
loss[z >= -1] = (1 - z[z >= -1]) ** 2
loss[z >= 1.] = 0
return loss
xmin, xmax = -4, 4
xx = np.linspace(xmin, xmax, 100)
plt.plot([xmin, 0, 0, xmax], [1, 1, 0, 0], 'k-',
label="Zero-one loss")
plt.plot(xx, np.where(xx < 1, 1 - xx, 0), 'g-',
label="Hinge loss")
plt.plot(xx, -np.minimum(xx, 0), 'm-',
label="Perceptron loss")
plt.plot(xx, np.log2(1 + np.exp(-xx)), 'r-',
label="Log loss")
plt.plot(xx, np.where(xx < 1, 1 - xx, 0) ** 2, 'b-',
label="Squared hinge loss")
plt.plot(xx, modified_huber_loss(xx, 1), 'y--',
label="Modified Huber loss")
plt.ylim((0, 8))
plt.legend(loc="upper right")
plt.xlabel(r"Decision function $f(x)$")
plt.ylabel("$L(y, f(x))$")
plt.show()
|
bsd-3-clause
|
mattjj/pyhsmm-autoregressive
|
tests/test_distributions.py
|
2
|
4232
|
from __future__ import division
import numpy as np
import abc
from matplotlib import pyplot as plt
from nose.plugins.attrib import attr
from pyhsmm.basic.pybasicbayes.testing.mixins import BigDataGibbsTester
from .. import distributions as d
from ..util import AR_striding
# TODO merge nlags, prefixes into the hyperparameter settings
# TODO params_close should depend on setting_idx
class ARBigDataGibbsTester(BigDataGibbsTester):
def check_big_data(self,setting_idx,hypparam_dict):
d1 = self.distribution_class(**hypparam_dict)
d2 = self.distribution_class(**hypparam_dict)
data = d1.rvs(prefix=self.prefixes[setting_idx],length=self.big_data_size)
d2.resample(AR_striding(data,self.nlagss[setting_idx]))
assert self.params_close(d1,d2)
@abc.abstractproperty
def prefixes(self):
pass
@abc.abstractproperty
def nlagss(self):
pass
@attr('AR_MNIW')
class Test_AR_MNIW(ARBigDataGibbsTester):
@property
def distribution_class(self):
return d.AR_MNIW
@property
def hyperparameter_settings(self):
return (
dict(nu_0=25,S_0=25*np.eye(2),M_0=np.zeros((2,4)),Kinv_0=np.eye(4),
A=np.hstack((-0.2*np.eye(2),1.2*np.eye(2))),sigma=np.eye(2)),
dict(nu_0=25,S_0=2*25*np.eye(2),M_0=np.zeros((2,4)),Kinv_0=1./3*np.eye(4),
A=np.hstack((-0.2*np.eye(2),1.2*np.eye(2))),sigma=np.eye(2)),
)
@property
def prefixes(self):
return (np.zeros((2,2)),np.zeros((2,2)))
@property
def nlagss(self):
return (2,2)
def params_close(self,d1,d2):
return np.linalg.norm(d1.fullA-d2.fullA) < 0.1 \
and np.linalg.norm(d1.sigma-d2.sigma) < 0.1
@property
def big_data_size(self):
return 10000
@property
def big_data_repeats_per_setting(self):
return 3
@attr('AR_MNFixedSigma')
class Test_AR_MNFixedSigma(ARBigDataGibbsTester):
@property
def distribution_class(self):
return d.AR_MNFixedSigma
@property
def hyperparameter_settings(self):
return (
dict(sigma=np.diag([1.,2.]),M_0=np.zeros((2,4)),Uinv_0=np.diag([1e-2,2e-2]),
Vinv_0=np.diag([1e-2,2e-2,1e-2,1e-2]),
A=np.hstack((-0.2*np.eye(2),1.2*np.eye(2)))),
)
@property
def prefixes(self):
return (np.zeros((2,2)),)
@property
def nlagss(self):
return (2,)
def params_close(self,d1,d2):
return np.linalg.norm(d1.fullA-d2.fullA) < 0.1
@property
def big_data_size(self):
return 10000
@property
def big_data_repeats_per_setting(self):
return 3
@attr('AR_IWFixedA')
class Test_AR_IWFixedA(ARBigDataGibbsTester):
@property
def distribution_class(self):
return d.AR_IWFixedA
@property
def hyperparameter_settings(self):
return (
dict(A=np.hstack((-0.2*np.eye(2),1.2*np.eye(2))),nu_0=4,S_0=4*np.eye(2)),
)
@property
def prefixes(self):
return (np.zeros((2,2)),)
@property
def nlagss(self):
return (2,)
def params_close(self,d1,d2):
return np.linalg.norm(d1.sigma-d2.sigma) < 0.25
@property
def big_data_size(self):
return 10000
@property
def big_data_repeats_per_setting(self):
return 3
@attr('AR_MN_IW_Nonconj')
class Test_AR_MN_IW_Nonconj(ARBigDataGibbsTester):
@property
def distribution_class(self):
return d.AR_MN_IW_Nonconj
@property
def hyperparameter_settings(self):
return (
dict(
nu_0=5,S_0=5*np.eye(2),
M_0=np.zeros((2,4)),Uinv_0=1e-2*np.eye(2),Vinv_0=1e-2*np.eye(4),
A=np.hstack((-0.2*np.eye(2),1.2*np.eye(2))),sigma=np.eye(2),
niter=10),
)
@property
def prefixes(self):
return (np.zeros((2,2)),)
@property
def nlagss(self):
return (2,)
def params_close(self,d1,d2):
return np.linalg.norm(d1.fullA-d2.fullA) < 1.5
@property
def big_data_size(self):
return 5000
@property
def big_data_repeats_per_setting(self):
return 3
|
gpl-2.0
|
mdastro/UV_ETGs
|
GAMAII/Coding/abmag_newcat.py
|
1
|
8179
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Creating new catalog with the corrected AB magnitudes, absolute magnitudes and adds a flag for the UV classification
This version treats the data from GAMA II.
@author: Maria Luiza Linhares Dantas
@date: 2018.07.03
@version: 0.0.5
Comment 01: pivot wavelengths from http://www.astro.ljmu.ac.uk/~ikb/research/mags-fluxes/
Comment 02: AB offsets for UKIDSS taken from: http://www.ukidss.org/technical/photom/hewett-ukidss.pdf
"""
# ======================================================================================================================
from __future__ import division
import os
import pandas as pd
import pyneb as pn
import numpy as np
from astropy.cosmology import FlatLambdaCDM
# ======================================================================================================================
# Main thread
if __name__ == '__main__':
# Constants --------------------------------------------------------------------------------------------------------
c = 2.99792458E18 # Light Speed in Angstrom/s
# Configuring paths and inputs -------------------------------------------------------------------------------------
data_path = '/home/mldantas/Google Drive/Doutorado/GAMAII/Catalogue'
raw_catalog = 'Match06_small.csv'
pivot_wavelengths_file = '/home/mldantas/Google Drive/Doutorado/GAMAII/pivot_wls.csv'
offset_ab_mags = '/home/mldantas/Google Drive/Doutorado/GAMAII/offset_abmags.csv'
master_dataframe = pd.DataFrame(pd.read_csv(os.path.join(data_path, raw_catalog)))
master_catalog = np.loadtxt(os.path.join(data_path, raw_catalog), delimiter=',', dtype=str)
pivot_wavelengths = np.loadtxt(os.path.join(data_path, pivot_wavelengths_file), delimiter=',', dtype=float,
skiprows=1)
offset_ab_mags = np.loadtxt(os.path.join(data_path, offset_ab_mags), delimiter=',', dtype=float, skiprows=1)
my_dictionary = {}
for i in range(len(master_catalog[0, :])): # Converting numpy array into dictionary
my_dictionary[master_catalog[0, i]] = np.array(master_catalog[0 + 1:, i], dtype=str)
# Selecting the magnitudes, extinction, kcorr,... ------------------------------------------------------------------
## magnitudes ------------------------------------------------------------------------------------------------------
mag_apparent_all = np.column_stack((my_dictionary['BEST_MAG_FUV'].astype(float),
my_dictionary['BEST_MAG_NUV'].astype(float),
my_dictionary['MODELMAG_U'].astype(float),
my_dictionary['MODELMAG_G'].astype(float),
my_dictionary['MODELMAG_R'].astype(float),
my_dictionary['MODELMAG_I'].astype(float),
my_dictionary['MODELMAG_Z'].astype(float),
my_dictionary['MAG_PETRO_Y'].astype(float),
my_dictionary['MAG_PETRO_J'].astype(float),
my_dictionary['MAG_PETRO_H'].astype(float),
my_dictionary['MAG_PETRO_K'].astype(float)))
## k-corrections for z=0.0 -----------------------------------------------------------------------------------------
kcorr_all = np.column_stack((my_dictionary['KCORR_FUV'].astype(float),
my_dictionary['KCORR_NUV'].astype(float),
my_dictionary['KCORR_U'].astype(float),
my_dictionary['KCORR_G'].astype(float),
my_dictionary['KCORR_R'].astype(float),
my_dictionary['KCORR_I'].astype(float),
my_dictionary['KCORR_Z'].astype(float),
my_dictionary['KCORR_Y'].astype(float),
my_dictionary['KCORR_J'].astype(float),
my_dictionary['KCORR_H'].astype(float),
my_dictionary['KCORR_K'].astype(float)))
## extinction ------------------------------------------------------------------------------------------------------
ebv = my_dictionary['extBV'].astype(float)
dered = pn.RedCorr(law='F99', R_V=3.1, E_BV=ebv)
extinction = []
for i in range(pivot_wavelengths.size):
extinction_i = dered.getCorr(pivot_wavelengths[i], rel_wave=None) # extinction in flux
extinction_i = np.log10(extinction_i/2.5) # extinction in magnitude
extinction.append(extinction_i)
extinction = np.array(extinction).T
# Correcting magnitudes by: extinction, k-correction, offset -------------------------------------------------------
mag_ab_all = []
for each_band in range(mag_apparent_all[0, :].size): # for each band among galex, sdss, and ukidss surveys:
mag_ab_i = mag_apparent_all[:, each_band] + kcorr_all[:, each_band] + extinction[:, each_band] + \
offset_ab_mags[each_band]
mag_ab_all.append(mag_ab_i)
mag_ab_all = np.array(mag_ab_all).T
mag_ab_all = np.squeeze(mag_ab_all) # literally squeezing the dimensions in order to be the smallest possible
# Calculating absolute magnitude -----------------------------------------------------------------------------------
adopted_cosmology = FlatLambdaCDM(H0=70, Om0=0.3) # cosmology parameters
redshift = my_dictionary['Z'].astype(float) # heliocentric redshift
luminosity_distance = adopted_cosmology.luminosity_distance(redshift).value # in Mpc
mag_absolute = []
for each_band in range(mag_apparent_all[0, :].size):
mag_absolute_i = mag_ab_all[:, each_band] - 5 * np.log10(luminosity_distance) - 25
mag_absolute.append(mag_absolute_i)
mag_absolute = np.array(mag_absolute).T
# Defining the new catalog -----------------------------------------------------------------------------------------
mag_ab_df = pd.DataFrame(mag_ab_all)
mag_ab_df.columns = ['MAG_AB_FUV', 'MAG_AB_NUV', 'MAG_AB_U', 'MAG_AB_G', 'MAG_AB_R', 'MAG_AB_I', 'MAG_AB_Z',
'MAG_AB_Y', 'MAG_AB_J','MAG_AB_H','MAG_AB_K']
mag_absolute_df = pd.DataFrame(mag_absolute)
mag_absolute_df.columns = ['MAG_ABSOLUTE_FUV', 'MAG_ABSOLUTE_NUV', 'MAG_ABSOLUTE_U', 'MAG_ABSOLUTE_G',
'MAG_ABSOLUTE_R', 'MAG_ABSOLUTE_I', 'MAG_ABSOLUTE_Z', 'MAG_ABSOLUTE_Y', 'MAG_ABSOLUTE_J',
'MAG_ABSOLUTE_H','MAG_ABSOLUTE_K']
# Creating an UV classification flag based on the paper of Yi et al. (2011) ----------------------------------------
uv_color = mag_ab_df['MAG_AB_FUV'] - mag_ab_df['MAG_AB_NUV']
optical_uv_nuv_color = mag_ab_df['MAG_AB_NUV'] - mag_ab_df['MAG_AB_R']
optical_uv_fuv_color = mag_ab_df['MAG_AB_FUV'] - mag_ab_df['MAG_AB_R']
uv_class = []
for i in range(mag_ab_df['MAG_AB_FUV'].size):
if optical_uv_nuv_color[i] < 5.4:
uv_class_i = 'RSF'
elif (optical_uv_nuv_color[i] > 5.4) * (uv_color[i] < 0.9) * (optical_uv_fuv_color[i] < 6.6):
uv_class_i = 'UV_UPTURN'
else:
uv_class_i = 'UV_WEAK'
uv_class.append(uv_class_i)
uv_class = np.array(uv_class)
uv_class_df = pd.DataFrame(uv_class)
uv_class_df.columns = ['UV_CLASS_YI2011']
# Saving the new dataset into a csv --------------------------------------------------------------------------------
complete_dataset = pd.concat([master_dataframe, mag_ab_df, mag_absolute_df, uv_class_df], axis=1)
complete_dataset.to_csv(os.path.join(data_path, 'Match06_small_mags.csv'), sep=',', header=True,
index=False)
|
mit
|
ndingwall/scikit-learn
|
benchmarks/bench_plot_svd.py
|
12
|
2871
|
"""Benchmarks of Singular Value Decomposition (Exact and Approximate)
The data is mostly low rank but is a fat infinite tail.
"""
import gc
from time import time
import numpy as np
from collections import defaultdict
from scipy.linalg import svd
from sklearn.utils.extmath import randomized_svd
from sklearn.datasets import make_low_rank_matrix
def compute_bench(samples_range, features_range, n_iter=3, rank=50):
it = 0
results = defaultdict(lambda: [])
max_it = len(samples_range) * len(features_range)
for n_samples in samples_range:
for n_features in features_range:
it += 1
print('====================')
print('Iteration %03d of %03d' % (it, max_it))
print('====================')
X = make_low_rank_matrix(n_samples, n_features,
effective_rank=rank,
tail_strength=0.2)
gc.collect()
print("benchmarking scipy svd: ")
tstart = time()
svd(X, full_matrices=False)
results['scipy svd'].append(time() - tstart)
gc.collect()
print("benchmarking scikit-learn randomized_svd: n_iter=0")
tstart = time()
randomized_svd(X, rank, n_iter=0)
results['scikit-learn randomized_svd (n_iter=0)'].append(
time() - tstart)
gc.collect()
print("benchmarking scikit-learn randomized_svd: n_iter=%d "
% n_iter)
tstart = time()
randomized_svd(X, rank, n_iter=n_iter)
results['scikit-learn randomized_svd (n_iter=%d)'
% n_iter].append(time() - tstart)
return results
if __name__ == '__main__':
from mpl_toolkits.mplot3d import axes3d # register the 3d projection
import matplotlib.pyplot as plt
samples_range = np.linspace(2, 1000, 4).astype(int)
features_range = np.linspace(2, 1000, 4).astype(int)
results = compute_bench(samples_range, features_range)
label = 'scikit-learn singular value decomposition benchmark results'
fig = plt.figure(label)
ax = fig.gca(projection='3d')
for c, (label, timings) in zip('rbg', sorted(results.items())):
X, Y = np.meshgrid(samples_range, features_range)
Z = np.asarray(timings).reshape(samples_range.shape[0],
features_range.shape[0])
# plot the actual surface
ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3,
color=c)
# dummy point plot to stick the legend to since surface plot do not
# support legends (yet?)
ax.plot([1], [1], [1], color=c, label=label)
ax.set_xlabel('n_samples')
ax.set_ylabel('n_features')
ax.set_zlabel('Time (s)')
ax.legend()
plt.show()
|
bsd-3-clause
|
benoute/flockml
|
ensemble.py
|
1
|
6009
|
import numpy as np
import copy
from sklearn import metrics
from sklearn.base import BaseEstimator
from IPython.parallel import interactive
@interactive
def do_fit(classifier, dump_file, get_features_func, features_index):
from sklearn.externals import joblib
X, y = joblib.load(dump_file, mmap_mode='r')
#features_list = joblib.load(features_list_file, mmap_mode='r')
features = get_features_func(features_index)
return classifier.fit(X[:, features], y)
@interactive
def do_predict_proba(classifier, dump_file,
get_features_func, features_index):
from sklearn.externals import joblib
X = joblib.load(dump_file, mmap_mode='r')
#features_list = joblib.load(features_list_file, mmap_mode='r')
features = get_features_func(features_index)
return classifier.predict_proba(X[:, features])
@interactive
def do_fit_predict(classifier, dump_file_train, dump_file_test,
get_features_func, features_index):
from sklearn.externals import joblib
Xtrain, ytrain = joblib.load(dump_file_train, mmap_mode='r')
Xtest = joblib.load(dump_file_test, mmap_mode='r')
features = get_features_func(features_index)
classifier.fit(Xtrain[:, features], ytrain)
return classifier.predict_proba(Xtest[:, features])
class Ensemble(BaseEstimator):
"""
Take a list of classifiers and combine them.
"""
def __init__(self, classifiers, weights):
self.classifiers = classifiers
self.weights = weights
def fit(self, X, y):
for classifier in self.classifiers:
classifier.fit(X,y)
return self
def predict_proba(self, Xtest):
y = np.zeros(Xtest.shape[0])
for classifier, weight in zip(self.classifiers, self.weights):
y += weight * classifier.predict_proba(Xtest)
def score(self, X, y, method='auc'):
yhat = self.predict_proba(X)
fpr, tpr, thresholds = metrics.roc_curve(y, yhat, pos_label=1)
return metrics.auc(fpr, tpr)
class EnsembleFeature(BaseEstimator):
"""
Create a ensemble using a single type of classifier but with different
feature selected.
"""
def __init__(self, classifier, num_features, get_features_fun, weights,
dump_path='dumps/splits/'):
self.classifiers = [copy.deepcopy(classifier)
for i in xrange(num_features)]
self.get_features_fun = get_features_fun
self.weights = weights
self.dump_path = dump_path
self.lb_view=None
def set_lb_view(self, lb_view):
self.lb_view = lb_view
def fit(self, X, y):
if self.lb_view:
from sklearn.externals import joblib
tasks = []
dump_file = self.dump_path + 'ensemble_fit_Xyfeat.pkl'
joblib.dump((X,y), dump_file)
for i, classifier in enumerate(self.classifiers):
task = self.lb_view.apply(do_fit, classifier, dump_file,
self.get_features_fun, i)
tasks.append(task)
for i, task in enumerate(tasks):
self.lb_view.wait(task)
self.classifiers[i] = task.get()
else:
for i, classifier in enumerate(self.classifiers):
features = self.get_features_fun(i)
classifier.fit(X[:, features], y)
return self
def predict_proba(self, Xtest):
y = np.zeros((Xtest.shape[0], 2))
if self.lb_view:
from sklearn.externals import joblib
tasks = []
dump_file = self.dump_path + 'ensemble_predict_X.pkl'
joblib.dump(Xtest, dump_file)
for i, classifier in enumerate(self.classifiers):
task = self.lb_view.apply(do_predict_proba, classifier,
dump_file, self.get_features_fun, i)
tasks.append(task)
for task, weight in zip(tasks, self.weights):
self.lb_view.wait(task)
y += weight * task.get()
else:
for i,classifier, features, weight in enumerate(self.classifiers):
features = self.get_features_fun(i)
y += self.weights[i] * classifier.predict_proba(Xtest[:, features])
return y
def fit_predict(self, Xtrain, ytrain, Xtest):
y = np.zeros((Xtest.shape[0], 2))
if self.lb_view:
from sklearn.externals import joblib
tasks = []
dump_file_train = self.dump_path + 'ensemble_fit_Xyfeat.pkl'
joblib.dump((Xtrain,ytrain), dump_file_train)
dump_file_test = self.dump_path + 'ensemble_predict_X.pkl'
joblib.dump(Xtest, dump_file_test)
for i, classifier in enumerate(self.classifiers):
task = self.lb_view.apply(do_fit_predict, classifier,
dump_file_train, dump_file_test,
self.get_features_fun, i)
tasks.append(task)
for task, weight in zip(tasks, self.weights):
self.lb_view.wait(task)
y += weight * task.get()
else:
for i,classifier, features, weight in enumerate(self.classifiers):
features = self.get_features_fun(i)
classifier.fit(Xtrain[:, features], ytrain)
y += self.weights[i] * classifier.predict_proba(Xtest[:, features])
return y
def score(self, X, y, method='auc'):
yhat = self.predict_proba(X)[:,1]
fpr, tpr, thresholds = metrics.roc_curve(y, yhat, pos_label=1)
return metrics.auc(fpr, tpr)
def fit_score(self, Xtrain, ytrain, Xtest, ytest, method='auc'):
ytest_hat = self.fit_predict(Xtrain, ytrain, Xtest)[:,1]
fpr, tpr, thresholds = metrics.roc_curve(ytest, ytest_hat, pos_label=1)
return metrics.auc(fpr, tpr)
|
bsd-2-clause
|
dgwakeman/mne-python
|
examples/time_frequency/plot_compute_source_psd_epochs.py
|
19
|
2833
|
"""
=====================================================================
Compute Power Spectral Density of inverse solution from single epochs
=====================================================================
Compute PSD of dSPM inverse solution on single trial epochs restricted
to a brain label. The PSD is computed using a multi-taper method with
Discrete Prolate Spheroidal Sequence (DPSS) windows.
"""
# Author: Martin Luessi <[email protected]>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.datasets import sample
from mne.io import Raw
from mne.minimum_norm import read_inverse_operator, compute_source_psd_epochs
print(__doc__)
data_path = sample.data_path()
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
fname_raw = data_path + '/MEG/sample/sample_audvis_raw.fif'
fname_event = data_path + '/MEG/sample/sample_audvis_raw-eve.fif'
label_name = 'Aud-lh'
fname_label = data_path + '/MEG/sample/labels/%s.label' % label_name
event_id, tmin, tmax = 1, -0.2, 0.5
snr = 1.0 # use smaller SNR for raw data
lambda2 = 1.0 / snr ** 2
method = "dSPM" # use dSPM method (could also be MNE or sLORETA)
# Load data
inverse_operator = read_inverse_operator(fname_inv)
label = mne.read_label(fname_label)
raw = Raw(fname_raw)
events = mne.read_events(fname_event)
# Set up pick list
include = []
raw.info['bads'] += ['EEG 053'] # bads + 1 more
# pick MEG channels
picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True,
include=include, exclude='bads')
# Read epochs
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=(None, 0), reject=dict(mag=4e-12, grad=4000e-13,
eog=150e-6))
# define frequencies of interest
fmin, fmax = 0., 70.
bandwidth = 4. # bandwidth of the windows in Hz
# compute source space psd in label
# Note: By using "return_generator=True" stcs will be a generator object
# instead of a list. This allows us so to iterate without having to
# keep everything in memory.
stcs = compute_source_psd_epochs(epochs, inverse_operator, lambda2=lambda2,
method=method, fmin=fmin, fmax=fmax,
bandwidth=bandwidth, label=label,
return_generator=True)
# compute average PSD over the first 10 epochs
n_epochs = 10
for i, stc in enumerate(stcs):
if i >= n_epochs:
break
if i == 0:
psd_avg = np.mean(stc.data, axis=0)
else:
psd_avg += np.mean(stc.data, axis=0)
psd_avg /= n_epochs
freqs = stc.times # the frequencies are stored here
plt.figure()
plt.plot(freqs, psd_avg)
plt.xlabel('Freq (Hz)')
plt.ylabel('Power Spectral Density')
plt.show()
|
bsd-3-clause
|
brupoon/nextTwilight
|
hyperleda/hyperFinal.py
|
1
|
4273
|
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 12 11:46:12 2014
@title: Hyperleda Final Project
@author: bp
"""
import numpy as np
from matplotlib import pyplot as plt
from math import log10
afile = r"C:\ast\hyperleda\bhbDataC.txt"
adata = np.loadtxt(afile, usecols=[1,2,3,4,6,7,8,9,10,11,12,13,14,17,18])
#graph a
mbh = adata[:,2] #mbh, msun
reff = adata[:,14] #Reff in i-band, arcsec
mbhSr = []
reffSr = []
#graph c
rinf = adata[:,12] #Rinf, arcsec
mbh2Sr = []
rinfSr = []
#graph d
mbh3Sr = []
sigma = adata[:,4] #velocity dispersion km/s
sigmaSr = []
#graph e
sigma2Sr = []
rinf2Sr = []
#graph h
dist = adata[:,0]
mbh4Sr = []
distSr = []
#graph b
bfile = r"C:\ast\hyperleda\hyperledaAGN.cgi"
bdata = np.loadtxt(bfile)
bdataX = bdata[:,0]
bdataY = bdata[:,1]
bdataSrX = []
bdataSrY = []
#graph f
ffile = r"C:\ast\hyperleda\hyperledaQmabs-noname.cgi"
fdata = np.loadtxt(ffile, usecols=[0,3])
fdataX = fdata[:,1]
fdataY = fdata[:,0]
fdataSrX = []
fdataSrY = []
#graph g
gfile = r"C:\ast\hyperleda\hyperledaSeyfertmabs-noname.cgi"
gdata = np.loadtxt(gfile, usecols=[0,3])
gdataX = gdata[:,1]
gdataY = gdata[:,0]
gdataSrX = []
gdataSrY = []
def errDetectorBH(dataX, dataY, dataSrX, dataSrY):
for i in range(0,len(dataX)-1):
if dataX[i] != 0 and dataY[i] != 0:
dataSrX.append(dataX[i])
dataSrY.append(dataY[i])
def logify(array):
retArray = []
for i in range(0, len(array)):
retArray.append(log10(array[i]))
return retArray
def errDetector(dataX, dataY, dataSrX, dataSrY):
for i in range(0,len(dataX)):
if dataX[i] != -99999 and dataY[i] != -99999:
dataSrX.append(dataX[i])
dataSrY.append(dataY[i])
def plot(x,y,title,xlbl,ylbl,i):
plt.figure(i)
plt.clf()
plt.plot(x,y,'g.',markersize = 4)
plt.title(title)
plt.xlabel(xlbl)
plt.ylabel(ylbl)
plt.show()
def plotAlt(x,y,title,xlbl,ylbl,i):
plt.figure(i)
plt.clf()
plt.plot(x,y,'g.',markersize = 4)
plt.title(title)
plt.xlabel(xlbl)
plt.ylabel(ylbl)
if __name__ == '__main__':
aTitle = "Black Hole Mass vs Effective Radius"
axlbl = "Effective Radius (arcsec)"
aylbl = "Black Hole Mass (log(Msun))"
errDetectorBH(reff, mbh, reffSr, mbhSr)
plot(reffSr,logify(mbhSr),aTitle,axlbl,aylbl, 0)
bTitle = "MABS vs Galaxy Morphology (for agnclass S1)"
bylbl = "MABS"
bxlbl = "Morphology"
errDetector(bdataX, bdataY, bdataSrX, bdataSrY)
plot(bdataSrX,bdataSrY,bTitle,bxlbl,bylbl, 1)
cTitle = "Radius of Influence vs Black Hole Mass"
cxlbl = "Black Hole Mass (log(Msun))"
cylbl = "Radius of Influence (arcsec)"
errDetectorBH(mbh, rinf, mbh2Sr, rinfSr)
#plotAlt(mbh2Sr, rinfSr, cTitle, cxlbl, cylbl, 2)
#cfit = np.polyfit(mbh2Sr, rinfSr, 4)
#cpoly = poly1d(cfit)
#plt.plot(mbh2Sr, cpoly(mbh2Sr), 'b.')
#plt.show()
plot(logify(mbh2Sr), rinfSr, cTitle, cxlbl, cylbl, 2)
dTitle = "Velocity Dispersion vs Black Hole Mass"
dx = "Black Hole Mass (log(Msun))"
dy = "Velocity Dispersion (km/s)"
errDetectorBH(mbh, sigma, mbh3Sr, sigmaSr) #do log of mbh and figure out wtf is wrong with y lbl
plotAlt(logify(mbh3Sr), sigmaSr, dTitle, dx, dy, 3)
dfit = np.polyfit(logify(mbh3Sr), sigmaSr, 1)
dpoly = np.poly1d(dfit)
plt.plot(logify(mbh3Sr), dpoly(logify(mbh3Sr)), '-')
eTitle = "Radius of Influence vs Velocity Dispersion"
ey = "Radius of Influence (arcsec)"
ex = "Velocity Dispersion (km/s)"
errDetectorBH(rinf, sigma, rinf2Sr, sigma2Sr)
plot(sigma2Sr, rinf2Sr, eTitle, ex, ey, 4)
fTitle = "MABS vs Galaxy Morphology (for agnclass Q)"
fylbl = "MABS"
fxlbl = "Morphology"
errDetector(fdataX, fdataY, fdataSrX, fdataSrY)
plot(fdataSrX,fdataSrY,fTitle,fxlbl,fylbl, 5)
gTitle = "MABS vs Galaxy Morphology (for agnclass S1 and S1n)"
gylbl = "MABS"
gxlbl = "Morphology"
errDetector(gdataX, gdataY, gdataSrX, gdataSrY)
plot(gdataSrX,gdataSrY,gTitle,gxlbl,gylbl, 6)
hTitle = "Black Hole Mass vs Distance"
hylbl = "Black Hole Mass (log(Msun))"
hxlbl = "Distance (Mpc)"
errDetectorBH(mbh, dist, mbh4Sr, distSr)
plot(distSr, mbh4Sr, hTitle, hxlbl, hylbl, 7)
|
mit
|
aleju/ImageAugmenter
|
imgaug/augmentables/heatmaps.py
|
2
|
25136
|
"""Classes to represent heatmaps, i.e. float arrays of ``[0.0, 1.0]``."""
from __future__ import print_function, division, absolute_import
import numpy as np
import six.moves as sm
from .. import imgaug as ia
from .base import IAugmentable
class HeatmapsOnImage(IAugmentable):
"""Object representing heatmaps on a single image.
Parameters
----------
arr : (H,W) ndarray or (H,W,C) ndarray
Array representing the heatmap(s) on a single image.
Multiple heatmaps may be provided, in which case ``C`` is expected to
denote the heatmap index.
The array must be of dtype ``float32``.
shape : tuple of int
Shape of the image on which the heatmap(s) is/are placed.
**Not** the shape of the heatmap(s) array, unless it is identical
to the image shape (note the likely difference between the arrays
in the number of channels).
This is expected to be ``(H, W)`` or ``(H, W, C)`` with ``C`` usually
being ``3``.
If there is no corresponding image, use ``(H_arr, W_arr)`` instead,
where ``H_arr`` is the height of the heatmap(s) array
(analogous ``W_arr``).
min_value : float, optional
Minimum value for the heatmaps that `arr` represents. This will
usually be ``0.0``.
max_value : float, optional
Maximum value for the heatmaps that `arr` represents. This will
usually be ``1.0``.
"""
def __init__(self, arr, shape, min_value=0.0, max_value=1.0):
"""Construct a new HeatmapsOnImage object."""
assert ia.is_np_array(arr), (
"Expected numpy array as heatmap input array, "
"got type %s" % (type(arr),))
# TODO maybe allow 0-sized heatmaps? in that case the min() and max()
# must be adjusted
assert arr.shape[0] > 0 and arr.shape[1] > 0, (
"Expected numpy array as heatmap with height and width greater "
"than 0, got shape %s." % (arr.shape,))
assert arr.dtype.name in ["float32"], (
"Heatmap input array expected to be of dtype float32, "
"got dtype %s." % (arr.dtype,))
assert arr.ndim in [2, 3], (
"Heatmap input array must be 2d or 3d, got shape %s." % (
arr.shape,))
assert len(shape) in [2, 3], (
"Argument 'shape' in HeatmapsOnImage expected to be 2d or 3d, "
"got shape %s." % (shape,))
assert min_value < max_value, (
"Expected min_value to be lower than max_value, "
"got %.4f and %.4f" % (min_value, max_value))
eps = np.finfo(arr.dtype).eps
components = arr.flat[0:50]
beyond_min = np.min(components) < min_value - eps
beyond_max = np.max(components) > max_value + eps
if beyond_min or beyond_max:
ia.warn(
"Value range of heatmap was chosen to be (%.8f, %.8f), but "
"found actual min/max of (%.8f, %.8f). Array will be "
"clipped to chosen value range." % (
min_value, max_value, np.min(arr), np.max(arr)))
arr = np.clip(arr, min_value, max_value)
if arr.ndim == 2:
arr = arr[..., np.newaxis]
self.arr_was_2d = True
else:
self.arr_was_2d = False
min_is_zero = 0.0 - eps < min_value < 0.0 + eps
max_is_one = 1.0 - eps < max_value < 1.0 + eps
if min_is_zero and max_is_one:
self.arr_0to1 = arr
else:
self.arr_0to1 = (arr - min_value) / (max_value - min_value)
self.shape = shape
self.min_value = min_value
self.max_value = max_value
def get_arr(self):
"""Get the heatmap's array in value range provided to ``__init__()``.
The :class:`HeatmapsOnImage` object saves heatmaps internally in the
value range ``[0.0, 1.0]``. This function converts the internal
representation to ``[min, max]``, where ``min`` and ``max`` are
provided to :func:`HeatmapsOnImage.__init__` upon instantiation of
the object.
Returns
-------
(H,W) ndarray or (H,W,C) ndarray
Heatmap array of dtype ``float32``.
"""
if self.arr_was_2d and self.arr_0to1.shape[2] == 1:
arr = self.arr_0to1[:, :, 0]
else:
arr = self.arr_0to1
eps = np.finfo(np.float32).eps
min_is_zero = 0.0 - eps < self.min_value < 0.0 + eps
max_is_one = 1.0 - eps < self.max_value < 1.0 + eps
if min_is_zero and max_is_one:
return np.copy(arr)
diff = self.max_value - self.min_value
return self.min_value + diff * arr
# TODO
# def find_global_maxima(self):
# raise NotImplementedError()
def draw(self, size=None, cmap="jet"):
"""Render the heatmaps as RGB images.
Parameters
----------
size : None or float or iterable of int or iterable of float, optional
Size of the rendered RGB image as ``(height, width)``.
See :func:`~imgaug.imgaug.imresize_single_image` for details.
If set to ``None``, no resizing is performed and the size of the
heatmaps array is used.
cmap : str or None, optional
Name of the ``matplotlib`` color map to use when convert the
heatmaps to RGB images.
If set to ``None``, no color map will be used and the heatmaps
will be converted to simple intensity maps.
Returns
-------
list of (H,W,3) ndarray
Rendered heatmaps as ``uint8`` arrays.
Always a **list** containing one RGB image per heatmap array
channel.
"""
heatmaps_uint8 = self.to_uint8()
heatmaps_drawn = []
for c in sm.xrange(heatmaps_uint8.shape[2]):
# We use c:c+1 here to get a (H,W,1) array. Otherwise imresize
# would have to re-attach an axis.
heatmap_c = heatmaps_uint8[..., c:c+1]
if size is not None:
heatmap_c_rs = ia.imresize_single_image(
heatmap_c, size, interpolation="nearest")
else:
heatmap_c_rs = heatmap_c
heatmap_c_rs = np.squeeze(heatmap_c_rs).astype(np.float32) / 255.0
if cmap is not None:
# import only when necessary (faster startup; optional
# dependency; less fragile -- see issue #225)
import matplotlib.pyplot as plt
cmap_func = plt.get_cmap(cmap)
heatmap_cmapped = cmap_func(heatmap_c_rs)
heatmap_cmapped = np.delete(heatmap_cmapped, 3, 2)
else:
heatmap_cmapped = np.tile(
heatmap_c_rs[..., np.newaxis], (1, 1, 3))
heatmap_cmapped = np.clip(
heatmap_cmapped * 255, 0, 255).astype(np.uint8)
heatmaps_drawn.append(heatmap_cmapped)
return heatmaps_drawn
def draw_on_image(self, image, alpha=0.75, cmap="jet", resize="heatmaps"):
"""Draw the heatmaps as overlays over an image.
Parameters
----------
image : (H,W,3) ndarray
Image onto which to draw the heatmaps.
Expected to be of dtype ``uint8``.
alpha : float, optional
Alpha/opacity value to use for the mixing of image and heatmaps.
Larger values mean that the heatmaps will be more visible and the
image less visible.
cmap : str or None, optional
Name of the ``matplotlib`` color map to use.
See :func:`HeatmapsOnImage.draw` for details.
resize : {'heatmaps', 'image'}, optional
In case of size differences between the image and heatmaps,
either the image or the heatmaps can be resized. This parameter
controls which of the two will be resized to the other's size.
Returns
-------
list of (H,W,3) ndarray
Rendered overlays as ``uint8`` arrays.
Always a **list** containing one RGB image per heatmap array
channel.
"""
# assert RGB image
assert image.ndim == 3, (
"Expected to draw on three-dimensional image, "
"got %d dimensions with shape %s instead." % (
image.ndim, image.shape))
assert image.shape[2] == 3, (
"Expected RGB image, got %d channels instead." % (image.shape[2],))
assert image.dtype.name == "uint8", (
"Expected uint8 image, got dtype %s." % (image.dtype.name,))
assert 0 - 1e-8 <= alpha <= 1.0 + 1e-8, (
"Expected 'alpha' to be in the interval [0.0, 1.0], got %.4f" % (
alpha))
assert resize in ["heatmaps", "image"], (
"Expected resize to be \"heatmaps\" or \"image\", "
"got %s instead." % (resize,))
if resize == "image":
image = ia.imresize_single_image(
image, self.arr_0to1.shape[0:2], interpolation="cubic")
heatmaps_drawn = self.draw(
size=image.shape[0:2] if resize == "heatmaps" else None,
cmap=cmap)
# TODO use blend_alpha here
mix = [
np.clip(
(1-alpha) * image + alpha * heatmap_i,
0, 255
).astype(np.uint8)
for heatmap_i
in heatmaps_drawn]
return mix
def invert(self):
"""Invert each component in the heatmap.
This shifts low values towards high values and vice versa.
This changes each value to::
v' = max - (v - min)
where ``v`` is the value at a spatial location, ``min`` is the
minimum value in the heatmap and ``max`` is the maximum value.
As the heatmap uses internally a ``0.0`` to ``1.0`` representation,
this simply becomes ``v' = 1.0 - v``.
This function can be useful e.g. when working with depth maps, where
algorithms might have an easier time representing the furthest away
points with zeros, requiring an inverted depth map.
Returns
-------
imgaug.augmentables.heatmaps.HeatmapsOnImage
Inverted heatmap.
"""
arr_inv = HeatmapsOnImage.from_0to1(
1 - self.arr_0to1,
shape=self.shape,
min_value=self.min_value,
max_value=self.max_value)
arr_inv.arr_was_2d = self.arr_was_2d
return arr_inv
def pad(self, top=0, right=0, bottom=0, left=0, mode="constant", cval=0.0):
"""Pad the heatmaps at their top/right/bottom/left side.
Parameters
----------
top : int, optional
Amount of pixels to add at the top side of the heatmaps.
Must be ``0`` or greater.
right : int, optional
Amount of pixels to add at the right side of the heatmaps.
Must be ``0`` or greater.
bottom : int, optional
Amount of pixels to add at the bottom side of the heatmaps.
Must be ``0`` or greater.
left : int, optional
Amount of pixels to add at the left side of the heatmaps.
Must be ``0`` or greater.
mode : string, optional
Padding mode to use. See :func:`~imgaug.imgaug.pad` for details.
cval : number, optional
Value to use for padding `mode` is ``constant``.
See :func:`~imgaug.imgaug.pad` for details.
Returns
-------
imgaug.augmentables.heatmaps.HeatmapsOnImage
Padded heatmaps of height ``H'=H+top+bottom`` and
width ``W'=W+left+right``.
"""
from ..augmenters import size as iasize
arr_0to1_padded = iasize.pad(
self.arr_0to1,
top=top,
right=right,
bottom=bottom,
left=left,
mode=mode,
cval=cval)
# TODO change to deepcopy()
return HeatmapsOnImage.from_0to1(
arr_0to1_padded,
shape=self.shape,
min_value=self.min_value,
max_value=self.max_value)
def pad_to_aspect_ratio(self, aspect_ratio, mode="constant", cval=0.0,
return_pad_amounts=False):
"""Pad the heatmaps until they match a target aspect ratio.
Depending on which dimension is smaller (height or width), only the
corresponding sides (left/right or top/bottom) will be padded. In
each case, both of the sides will be padded equally.
Parameters
----------
aspect_ratio : float
Target aspect ratio, given as width/height. E.g. ``2.0`` denotes
the image having twice as much width as height.
mode : str, optional
Padding mode to use.
See :func:`~imgaug.imgaug.pad` for details.
cval : number, optional
Value to use for padding if `mode` is ``constant``.
See :func:`~imgaug.imgaug.pad` for details.
return_pad_amounts : bool, optional
If ``False``, then only the padded instance will be returned.
If ``True``, a tuple with two entries will be returned, where
the first entry is the padded instance and the second entry are
the amounts by which each array side was padded. These amounts are
again a tuple of the form ``(top, right, bottom, left)``, with
each value being an integer.
Returns
-------
imgaug.augmentables.heatmaps.HeatmapsOnImage
Padded heatmaps as :class:`HeatmapsOnImage` instance.
tuple of int
Amounts by which the instance's array was padded on each side,
given as a tuple ``(top, right, bottom, left)``.
This tuple is only returned if `return_pad_amounts` was set to
``True``.
"""
from ..augmenters import size as iasize
arr_0to1_padded, pad_amounts = iasize.pad_to_aspect_ratio(
self.arr_0to1,
aspect_ratio=aspect_ratio,
mode=mode,
cval=cval,
return_pad_amounts=True)
# TODO change to deepcopy()
heatmaps = HeatmapsOnImage.from_0to1(
arr_0to1_padded,
shape=self.shape,
min_value=self.min_value,
max_value=self.max_value)
if return_pad_amounts:
return heatmaps, pad_amounts
return heatmaps
def avg_pool(self, block_size):
"""Average-pool the heatmap(s) array using a given block/kernel size.
Parameters
----------
block_size : int or tuple of int
Size of each block of values to pool, aka kernel size.
See :func:`~imgaug.imgaug.pool` for details.
Returns
-------
imgaug.augmentables.heatmaps.HeatmapsOnImage
Heatmaps after average pooling.
"""
arr_0to1_reduced = ia.avg_pool(self.arr_0to1, block_size, pad_cval=0.0)
return HeatmapsOnImage.from_0to1(
arr_0to1_reduced,
shape=self.shape,
min_value=self.min_value,
max_value=self.max_value)
def max_pool(self, block_size):
"""Max-pool the heatmap(s) array using a given block/kernel size.
Parameters
----------
block_size : int or tuple of int
Size of each block of values to pool, aka kernel size.
See :func:`~imgaug.imgaug.pool` for details.
Returns
-------
imgaug.augmentables.heatmaps.HeatmapsOnImage
Heatmaps after max-pooling.
"""
arr_0to1_reduced = ia.max_pool(self.arr_0to1, block_size)
return HeatmapsOnImage.from_0to1(
arr_0to1_reduced,
shape=self.shape,
min_value=self.min_value,
max_value=self.max_value)
@ia.deprecated(alt_func="HeatmapsOnImage.resize()",
comment="resize() has the exactly same interface.")
def scale(self, *args, **kwargs):
"""Resize the heatmap(s) array given a target size and interpolation."""
return self.resize(*args, **kwargs)
def resize(self, sizes, interpolation="cubic"):
"""Resize the heatmap(s) array given a target size and interpolation.
Parameters
----------
sizes : float or iterable of int or iterable of float
New size of the array in ``(height, width)``.
See :func:`~imgaug.imgaug.imresize_single_image` for details.
interpolation : None or str or int, optional
The interpolation to use during resize.
See :func:`~imgaug.imgaug.imresize_single_image` for details.
Returns
-------
imgaug.augmentables.heatmaps.HeatmapsOnImage
Resized heatmaps object.
"""
arr_0to1_resized = ia.imresize_single_image(
self.arr_0to1, sizes, interpolation=interpolation)
# cubic interpolation can lead to values outside of [0.0, 1.0],
# see https://github.com/opencv/opencv/issues/7195
# TODO area interpolation too?
arr_0to1_resized = np.clip(arr_0to1_resized, 0.0, 1.0)
return HeatmapsOnImage.from_0to1(
arr_0to1_resized,
shape=self.shape,
min_value=self.min_value,
max_value=self.max_value)
def to_uint8(self):
"""Convert this heatmaps object to an ``uint8`` array.
Returns
-------
(H,W,C) ndarray
Heatmap as an ``uint8`` array, i.e. with the discrete value
range ``[0, 255]``.
"""
# TODO this always returns (H,W,C), even if input ndarray was
# originally (H,W). Does it make sense here to also return
# (H,W) if self.arr_was_2d?
arr_0to255 = np.clip(np.round(self.arr_0to1 * 255), 0, 255)
arr_uint8 = arr_0to255.astype(np.uint8)
return arr_uint8
@staticmethod
def from_uint8(arr_uint8, shape, min_value=0.0, max_value=1.0):
"""Create a ``float``-based heatmaps object from an ``uint8`` array.
Parameters
----------
arr_uint8 : (H,W) ndarray or (H,W,C) ndarray
Heatmap(s) array, where ``H`` is height, ``W`` is width
and ``C`` is the number of heatmap channels.
Expected dtype is ``uint8``.
shape : tuple of int
Shape of the image on which the heatmap(s) is/are placed.
**Not** the shape of the heatmap(s) array, unless it is identical
to the image shape (note the likely difference between the arrays
in the number of channels).
If there is not a corresponding image, use the shape of the
heatmaps array.
min_value : float, optional
Minimum value of the float heatmaps that the input array
represents. This will usually be 0.0. In most other cases it will
be close to the interval ``[0.0, 1.0]``.
Calling :func:`~imgaug.HeatmapsOnImage.get_arr`, will automatically
convert the interval ``[0.0, 1.0]`` float array to this
``[min, max]`` interval.
max_value : float, optional
Minimum value of the float heatmaps that the input array
represents. This will usually be 1.0.
See parameter `min_value` for details.
Returns
-------
imgaug.augmentables.heatmaps.HeatmapsOnImage
Heatmaps object.
"""
arr_0to1 = arr_uint8.astype(np.float32) / 255.0
return HeatmapsOnImage.from_0to1(
arr_0to1, shape,
min_value=min_value,
max_value=max_value)
@staticmethod
def from_0to1(arr_0to1, shape, min_value=0.0, max_value=1.0):
"""Create a heatmaps object from a ``[0.0, 1.0]`` float array.
Parameters
----------
arr_0to1 : (H,W) or (H,W,C) ndarray
Heatmap(s) array, where ``H`` is the height, ``W`` is the width
and ``C`` is the number of heatmap channels.
Expected dtype is ``float32``.
shape : tuple of ints
Shape of the image on which the heatmap(s) is/are placed.
**Not** the shape of the heatmap(s) array, unless it is identical
to the image shape (note the likely difference between the arrays
in the number of channels).
If there is not a corresponding image, use the shape of the
heatmaps array.
min_value : float, optional
Minimum value of the float heatmaps that the input array
represents. This will usually be 0.0. In most other cases it will
be close to the interval ``[0.0, 1.0]``.
Calling :func:`~imgaug.HeatmapsOnImage.get_arr`, will automatically
convert the interval ``[0.0, 1.0]`` float array to this
``[min, max]`` interval.
max_value : float, optional
Minimum value of the float heatmaps that the input array
represents. This will usually be 1.0.
See parameter `min_value` for details.
Returns
-------
imgaug.augmentables.heatmaps.HeatmapsOnImage
Heatmaps object.
"""
heatmaps = HeatmapsOnImage(arr_0to1, shape,
min_value=0.0, max_value=1.0)
heatmaps.min_value = min_value
heatmaps.max_value = max_value
return heatmaps
# TODO change name to change_value_range()?
@classmethod
def change_normalization(cls, arr, source, target):
"""Change the value range of a heatmap array.
E.g. the value range may be changed from the interval ``[0.0, 1.0]``
to ``[-1.0, 1.0]``.
Parameters
----------
arr : ndarray
Heatmap array to modify.
source : tuple of float
Current value range of the input array, given as a
tuple ``(min, max)``, where both are ``float`` values.
target : tuple of float
Desired output value range of the array, given as a
tuple ``(min, max)``, where both are ``float`` values.
Returns
-------
ndarray
Input array, with value range projected to the desired target
value range.
"""
assert ia.is_np_array(arr), (
"Expected 'arr' to be an ndarray, got type %s." % (type(arr),))
def _validate_tuple(arg_name, arg_value):
assert isinstance(arg_value, tuple), (
"'%s' was not a HeatmapsOnImage instance, "
"expected type tuple then. Got type %s." % (
arg_name, type(arg_value),))
assert len(arg_value) == 2, (
"Expected tuple '%s' to contain exactly two entries, "
"got %d." % (arg_name, len(arg_value),))
assert arg_value[0] < arg_value[1], (
"Expected tuple '%s' to have two entries with "
"entry 1 < entry 2, got values %.4f and %.4f." % (
arg_name, arg_value[0], arg_value[1]))
if isinstance(source, HeatmapsOnImage):
source = (source.min_value, source.max_value)
else:
_validate_tuple("source", source)
if isinstance(target, HeatmapsOnImage):
target = (target.min_value, target.max_value)
else:
_validate_tuple("target", target)
# Check if source and target are the same (with a tiny bit of
# tolerance) if so, evade compuation and just copy the array instead.
# This is reasonable, as source and target will often both
# be (0.0, 1.0).
eps = np.finfo(arr.dtype).eps
mins_same = source[0] - 10*eps < target[0] < source[0] + 10*eps
maxs_same = source[1] - 10*eps < target[1] < source[1] + 10*eps
if mins_same and maxs_same:
return np.copy(arr)
min_source, max_source = source
min_target, max_target = target
diff_source = max_source - min_source
diff_target = max_target - min_target
arr_0to1 = (arr - min_source) / diff_source
arr_target = min_target + arr_0to1 * diff_target
return arr_target
# TODO make this a proper shallow-copy
def copy(self):
"""Create a shallow copy of the heatmaps object.
Returns
-------
imgaug.augmentables.heatmaps.HeatmapsOnImage
Shallow copy.
"""
return self.deepcopy()
def deepcopy(self):
"""Create a deep copy of the heatmaps object.
Returns
-------
imgaug.augmentables.heatmaps.HeatmapsOnImage
Deep copy.
"""
return HeatmapsOnImage(
self.get_arr(),
shape=self.shape,
min_value=self.min_value,
max_value=self.max_value)
|
mit
|
shangwuhencc/scikit-learn
|
sklearn/svm/tests/test_svm.py
|
70
|
31674
|
"""
Testing for Support Vector Machine module (sklearn.svm)
TODO: remove hard coded numerical results when possible
"""
import numpy as np
import itertools
from numpy.testing import assert_array_equal, assert_array_almost_equal
from numpy.testing import assert_almost_equal
from scipy import sparse
from nose.tools import assert_raises, assert_true, assert_equal, assert_false
from sklearn.base import ChangedBehaviorWarning
from sklearn import svm, linear_model, datasets, metrics, base
from sklearn.cross_validation import train_test_split
from sklearn.datasets import make_classification, make_blobs
from sklearn.metrics import f1_score
from sklearn.metrics.pairwise import rbf_kernel
from sklearn.utils import check_random_state
from sklearn.utils import ConvergenceWarning
from sklearn.utils.validation import NotFittedError
from sklearn.utils.testing import assert_greater, assert_in, assert_less
from sklearn.utils.testing import assert_raises_regexp, assert_warns
from sklearn.utils.testing import assert_warns_message, assert_raise_message
from sklearn.utils.testing import ignore_warnings
# toy sample
X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]]
Y = [1, 1, 1, 2, 2, 2]
T = [[-1, -1], [2, 2], [3, 2]]
true_result = [1, 2, 2]
# also load the iris dataset
iris = datasets.load_iris()
rng = check_random_state(42)
perm = rng.permutation(iris.target.size)
iris.data = iris.data[perm]
iris.target = iris.target[perm]
def test_libsvm_parameters():
# Test parameters on classes that make use of libsvm.
clf = svm.SVC(kernel='linear').fit(X, Y)
assert_array_equal(clf.dual_coef_, [[-0.25, .25]])
assert_array_equal(clf.support_, [1, 3])
assert_array_equal(clf.support_vectors_, (X[1], X[3]))
assert_array_equal(clf.intercept_, [0.])
assert_array_equal(clf.predict(X), Y)
def test_libsvm_iris():
# Check consistency on dataset iris.
# shuffle the dataset so that labels are not ordered
for k in ('linear', 'rbf'):
clf = svm.SVC(kernel=k).fit(iris.data, iris.target)
assert_greater(np.mean(clf.predict(iris.data) == iris.target), 0.9)
assert_array_equal(clf.classes_, np.sort(clf.classes_))
# check also the low-level API
model = svm.libsvm.fit(iris.data, iris.target.astype(np.float64))
pred = svm.libsvm.predict(iris.data, *model)
assert_greater(np.mean(pred == iris.target), .95)
model = svm.libsvm.fit(iris.data, iris.target.astype(np.float64),
kernel='linear')
pred = svm.libsvm.predict(iris.data, *model, kernel='linear')
assert_greater(np.mean(pred == iris.target), .95)
pred = svm.libsvm.cross_validation(iris.data,
iris.target.astype(np.float64), 5,
kernel='linear',
random_seed=0)
assert_greater(np.mean(pred == iris.target), .95)
# If random_seed >= 0, the libsvm rng is seeded (by calling `srand`), hence
# we should get deteriministic results (assuming that there is no other
# thread calling this wrapper calling `srand` concurrently).
pred2 = svm.libsvm.cross_validation(iris.data,
iris.target.astype(np.float64), 5,
kernel='linear',
random_seed=0)
assert_array_equal(pred, pred2)
@ignore_warnings
def test_single_sample_1d():
# Test whether SVCs work on a single sample given as a 1-d array
clf = svm.SVC().fit(X, Y)
clf.predict(X[0])
clf = svm.LinearSVC(random_state=0).fit(X, Y)
clf.predict(X[0])
def test_precomputed():
# SVC with a precomputed kernel.
# We test it with a toy dataset and with iris.
clf = svm.SVC(kernel='precomputed')
# Gram matrix for train data (square matrix)
# (we use just a linear kernel)
K = np.dot(X, np.array(X).T)
clf.fit(K, Y)
# Gram matrix for test data (rectangular matrix)
KT = np.dot(T, np.array(X).T)
pred = clf.predict(KT)
assert_raises(ValueError, clf.predict, KT.T)
assert_array_equal(clf.dual_coef_, [[-0.25, .25]])
assert_array_equal(clf.support_, [1, 3])
assert_array_equal(clf.intercept_, [0])
assert_array_almost_equal(clf.support_, [1, 3])
assert_array_equal(pred, true_result)
# Gram matrix for test data but compute KT[i,j]
# for support vectors j only.
KT = np.zeros_like(KT)
for i in range(len(T)):
for j in clf.support_:
KT[i, j] = np.dot(T[i], X[j])
pred = clf.predict(KT)
assert_array_equal(pred, true_result)
# same as before, but using a callable function instead of the kernel
# matrix. kernel is just a linear kernel
kfunc = lambda x, y: np.dot(x, y.T)
clf = svm.SVC(kernel=kfunc)
clf.fit(X, Y)
pred = clf.predict(T)
assert_array_equal(clf.dual_coef_, [[-0.25, .25]])
assert_array_equal(clf.intercept_, [0])
assert_array_almost_equal(clf.support_, [1, 3])
assert_array_equal(pred, true_result)
# test a precomputed kernel with the iris dataset
# and check parameters against a linear SVC
clf = svm.SVC(kernel='precomputed')
clf2 = svm.SVC(kernel='linear')
K = np.dot(iris.data, iris.data.T)
clf.fit(K, iris.target)
clf2.fit(iris.data, iris.target)
pred = clf.predict(K)
assert_array_almost_equal(clf.support_, clf2.support_)
assert_array_almost_equal(clf.dual_coef_, clf2.dual_coef_)
assert_array_almost_equal(clf.intercept_, clf2.intercept_)
assert_almost_equal(np.mean(pred == iris.target), .99, decimal=2)
# Gram matrix for test data but compute KT[i,j]
# for support vectors j only.
K = np.zeros_like(K)
for i in range(len(iris.data)):
for j in clf.support_:
K[i, j] = np.dot(iris.data[i], iris.data[j])
pred = clf.predict(K)
assert_almost_equal(np.mean(pred == iris.target), .99, decimal=2)
clf = svm.SVC(kernel=kfunc)
clf.fit(iris.data, iris.target)
assert_almost_equal(np.mean(pred == iris.target), .99, decimal=2)
def test_svr():
# Test Support Vector Regression
diabetes = datasets.load_diabetes()
for clf in (svm.NuSVR(kernel='linear', nu=.4, C=1.0),
svm.NuSVR(kernel='linear', nu=.4, C=10.),
svm.SVR(kernel='linear', C=10.),
svm.LinearSVR(C=10.),
svm.LinearSVR(C=10.),
):
clf.fit(diabetes.data, diabetes.target)
assert_greater(clf.score(diabetes.data, diabetes.target), 0.02)
# non-regression test; previously, BaseLibSVM would check that
# len(np.unique(y)) < 2, which must only be done for SVC
svm.SVR().fit(diabetes.data, np.ones(len(diabetes.data)))
svm.LinearSVR().fit(diabetes.data, np.ones(len(diabetes.data)))
def test_linearsvr():
# check that SVR(kernel='linear') and LinearSVC() give
# comparable results
diabetes = datasets.load_diabetes()
lsvr = svm.LinearSVR(C=1e3).fit(diabetes.data, diabetes.target)
score1 = lsvr.score(diabetes.data, diabetes.target)
svr = svm.SVR(kernel='linear', C=1e3).fit(diabetes.data, diabetes.target)
score2 = svr.score(diabetes.data, diabetes.target)
assert np.linalg.norm(lsvr.coef_ - svr.coef_) / np.linalg.norm(svr.coef_) < .1
assert np.abs(score1 - score2) < 0.1
def test_svr_errors():
X = [[0.0], [1.0]]
y = [0.0, 0.5]
# Bad kernel
clf = svm.SVR(kernel=lambda x, y: np.array([[1.0]]))
clf.fit(X, y)
assert_raises(ValueError, clf.predict, X)
def test_oneclass():
# Test OneClassSVM
clf = svm.OneClassSVM()
clf.fit(X)
pred = clf.predict(T)
assert_array_almost_equal(pred, [-1, -1, -1])
assert_array_almost_equal(clf.intercept_, [-1.008], decimal=3)
assert_array_almost_equal(clf.dual_coef_,
[[0.632, 0.233, 0.633, 0.234, 0.632, 0.633]],
decimal=3)
assert_raises(ValueError, lambda: clf.coef_)
def test_oneclass_decision_function():
# Test OneClassSVM decision function
clf = svm.OneClassSVM()
rnd = check_random_state(2)
# Generate train data
X = 0.3 * rnd.randn(100, 2)
X_train = np.r_[X + 2, X - 2]
# Generate some regular novel observations
X = 0.3 * rnd.randn(20, 2)
X_test = np.r_[X + 2, X - 2]
# Generate some abnormal novel observations
X_outliers = rnd.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)
# predict things
y_pred_test = clf.predict(X_test)
assert_greater(np.mean(y_pred_test == 1), .9)
y_pred_outliers = clf.predict(X_outliers)
assert_greater(np.mean(y_pred_outliers == -1), .9)
dec_func_test = clf.decision_function(X_test)
assert_array_equal((dec_func_test > 0).ravel(), y_pred_test == 1)
dec_func_outliers = clf.decision_function(X_outliers)
assert_array_equal((dec_func_outliers > 0).ravel(), y_pred_outliers == 1)
def test_tweak_params():
# Make sure some tweaking of parameters works.
# We change clf.dual_coef_ at run time and expect .predict() to change
# accordingly. Notice that this is not trivial since it involves a lot
# of C/Python copying in the libsvm bindings.
# The success of this test ensures that the mapping between libsvm and
# the python classifier is complete.
clf = svm.SVC(kernel='linear', C=1.0)
clf.fit(X, Y)
assert_array_equal(clf.dual_coef_, [[-.25, .25]])
assert_array_equal(clf.predict([[-.1, -.1]]), [1])
clf._dual_coef_ = np.array([[.0, 1.]])
assert_array_equal(clf.predict([[-.1, -.1]]), [2])
def test_probability():
# Predict probabilities using SVC
# This uses cross validation, so we use a slightly bigger testing set.
for clf in (svm.SVC(probability=True, random_state=0, C=1.0),
svm.NuSVC(probability=True, random_state=0)):
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]))
assert_true(np.mean(np.argmax(prob_predict, 1)
== clf.predict(iris.data)) > 0.9)
assert_almost_equal(clf.predict_proba(iris.data),
np.exp(clf.predict_log_proba(iris.data)), 8)
def test_decision_function():
# Test decision_function
# Sanity check, test that decision_function implemented in python
# returns the same as the one in libsvm
# multi class:
clf = svm.SVC(kernel='linear', C=0.1,
decision_function_shape='ovo').fit(iris.data, iris.target)
dec = np.dot(iris.data, clf.coef_.T) + clf.intercept_
assert_array_almost_equal(dec, clf.decision_function(iris.data))
# binary:
clf.fit(X, Y)
dec = np.dot(X, clf.coef_.T) + clf.intercept_
prediction = clf.predict(X)
assert_array_almost_equal(dec.ravel(), clf.decision_function(X))
assert_array_almost_equal(
prediction,
clf.classes_[(clf.decision_function(X) > 0).astype(np.int)])
expected = np.array([-1., -0.66, -1., 0.66, 1., 1.])
assert_array_almost_equal(clf.decision_function(X), expected, 2)
# kernel binary:
clf = svm.SVC(kernel='rbf', gamma=1, decision_function_shape='ovo')
clf.fit(X, Y)
rbfs = rbf_kernel(X, clf.support_vectors_, gamma=clf.gamma)
dec = np.dot(rbfs, clf.dual_coef_.T) + clf.intercept_
assert_array_almost_equal(dec.ravel(), clf.decision_function(X))
def test_decision_function_shape():
# check that decision_function_shape='ovr' gives
# correct shape and is consistent with predict
clf = svm.SVC(kernel='linear', C=0.1,
decision_function_shape='ovr').fit(iris.data, iris.target)
dec = clf.decision_function(iris.data)
assert_equal(dec.shape, (len(iris.data), 3))
assert_array_equal(clf.predict(iris.data), np.argmax(dec, axis=1))
# with five classes:
X, y = make_blobs(n_samples=80, centers=5, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
clf = svm.SVC(kernel='linear', C=0.1,
decision_function_shape='ovr').fit(X_train, y_train)
dec = clf.decision_function(X_test)
assert_equal(dec.shape, (len(X_test), 5))
assert_array_equal(clf.predict(X_test), np.argmax(dec, axis=1))
# check shape of ovo_decition_function=True
clf = svm.SVC(kernel='linear', C=0.1,
decision_function_shape='ovo').fit(X_train, y_train)
dec = clf.decision_function(X_train)
assert_equal(dec.shape, (len(X_train), 10))
# check deprecation warning
clf.decision_function_shape = None
msg = "change the shape of the decision function"
dec = assert_warns_message(ChangedBehaviorWarning, msg,
clf.decision_function, X_train)
assert_equal(dec.shape, (len(X_train), 10))
def test_svr_decision_function():
# Test SVR's decision_function
# Sanity check, test that decision_function implemented in python
# returns the same as the one in libsvm
X = iris.data
y = iris.target
# linear kernel
reg = svm.SVR(kernel='linear', C=0.1).fit(X, y)
dec = np.dot(X, reg.coef_.T) + reg.intercept_
assert_array_almost_equal(dec.ravel(), reg.decision_function(X).ravel())
# rbf kernel
reg = svm.SVR(kernel='rbf', gamma=1).fit(X, y)
rbfs = rbf_kernel(X, reg.support_vectors_, gamma=reg.gamma)
dec = np.dot(rbfs, reg.dual_coef_.T) + reg.intercept_
assert_array_almost_equal(dec.ravel(), reg.decision_function(X).ravel())
def test_weight():
# Test class weights
clf = svm.SVC(class_weight={1: 0.1})
# we give a small weights to class 1
clf.fit(X, Y)
# so all predicted values belong to class 2
assert_array_almost_equal(clf.predict(X), [2] * 6)
X_, y_ = make_classification(n_samples=200, n_features=10,
weights=[0.833, 0.167], random_state=2)
for clf in (linear_model.LogisticRegression(),
svm.LinearSVC(random_state=0), svm.SVC()):
clf.set_params(class_weight={0: .1, 1: 10})
clf.fit(X_[:100], y_[:100])
y_pred = clf.predict(X_[100:])
assert_true(f1_score(y_[100:], y_pred) > .3)
def test_sample_weights():
# Test weights on individual samples
# TODO: check on NuSVR, OneClass, etc.
clf = svm.SVC()
clf.fit(X, Y)
assert_array_equal(clf.predict([X[2]]), [1.])
sample_weight = [.1] * 3 + [10] * 3
clf.fit(X, Y, sample_weight=sample_weight)
assert_array_equal(clf.predict([X[2]]), [2.])
# test that rescaling all samples is the same as changing C
clf = svm.SVC()
clf.fit(X, Y)
dual_coef_no_weight = clf.dual_coef_
clf.set_params(C=100)
clf.fit(X, Y, sample_weight=np.repeat(0.01, len(X)))
assert_array_almost_equal(dual_coef_no_weight, clf.dual_coef_)
def test_auto_weight():
# Test class weights for imbalanced data
from sklearn.linear_model import LogisticRegression
# We take as dataset the two-dimensional projection of iris so
# that it is not separable and remove half of predictors from
# class 1.
# We add one to the targets as a non-regression test: class_weight="balanced"
# used to work only when the labels where a range [0..K).
from sklearn.utils import compute_class_weight
X, y = iris.data[:, :2], iris.target + 1
unbalanced = np.delete(np.arange(y.size), np.where(y > 2)[0][::2])
classes = np.unique(y[unbalanced])
class_weights = compute_class_weight('balanced', classes, y[unbalanced])
assert_true(np.argmax(class_weights) == 2)
for clf in (svm.SVC(kernel='linear'), svm.LinearSVC(random_state=0),
LogisticRegression()):
# check that score is better when class='balanced' is set.
y_pred = clf.fit(X[unbalanced], y[unbalanced]).predict(X)
clf.set_params(class_weight='balanced')
y_pred_balanced = clf.fit(X[unbalanced], y[unbalanced],).predict(X)
assert_true(metrics.f1_score(y, y_pred, average='weighted')
<= metrics.f1_score(y, y_pred_balanced,
average='weighted'))
def test_bad_input():
# Test that it gives proper exception on deficient input
# impossible value of C
assert_raises(ValueError, svm.SVC(C=-1).fit, X, Y)
# impossible value of nu
clf = svm.NuSVC(nu=0.0)
assert_raises(ValueError, clf.fit, X, Y)
Y2 = Y[:-1] # wrong dimensions for labels
assert_raises(ValueError, clf.fit, X, Y2)
# Test with arrays that are non-contiguous.
for clf in (svm.SVC(), svm.LinearSVC(random_state=0)):
Xf = np.asfortranarray(X)
assert_false(Xf.flags['C_CONTIGUOUS'])
yf = np.ascontiguousarray(np.tile(Y, (2, 1)).T)
yf = yf[:, -1]
assert_false(yf.flags['F_CONTIGUOUS'])
assert_false(yf.flags['C_CONTIGUOUS'])
clf.fit(Xf, yf)
assert_array_equal(clf.predict(T), true_result)
# error for precomputed kernelsx
clf = svm.SVC(kernel='precomputed')
assert_raises(ValueError, clf.fit, X, Y)
# sample_weight bad dimensions
clf = svm.SVC()
assert_raises(ValueError, clf.fit, X, Y, sample_weight=range(len(X) - 1))
# predict with sparse input when trained with dense
clf = svm.SVC().fit(X, Y)
assert_raises(ValueError, clf.predict, sparse.lil_matrix(X))
Xt = np.array(X).T
clf.fit(np.dot(X, Xt), Y)
assert_raises(ValueError, clf.predict, X)
clf = svm.SVC()
clf.fit(X, Y)
assert_raises(ValueError, clf.predict, Xt)
def test_sparse_precomputed():
clf = svm.SVC(kernel='precomputed')
sparse_gram = sparse.csr_matrix([[1, 0], [0, 1]])
try:
clf.fit(sparse_gram, [0, 1])
assert not "reached"
except TypeError as e:
assert_in("Sparse precomputed", str(e))
def test_linearsvc_parameters():
# Test possible parameter combinations in LinearSVC
# Generate list of possible parameter combinations
losses = ['hinge', 'squared_hinge', 'logistic_regression', 'foo']
penalties, duals = ['l1', 'l2', 'bar'], [True, False]
X, y = make_classification(n_samples=5, n_features=5)
for loss, penalty, dual in itertools.product(losses, penalties, duals):
clf = svm.LinearSVC(penalty=penalty, loss=loss, dual=dual)
if ((loss, penalty) == ('hinge', 'l1') or
(loss, penalty, dual) == ('hinge', 'l2', False) or
(penalty, dual) == ('l1', True) or
loss == 'foo' or penalty == 'bar'):
assert_raises_regexp(ValueError,
"Unsupported set of arguments.*penalty='%s.*"
"loss='%s.*dual=%s"
% (penalty, loss, dual),
clf.fit, X, y)
else:
clf.fit(X, y)
# Incorrect loss value - test if explicit error message is raised
assert_raises_regexp(ValueError, ".*loss='l3' is not supported.*",
svm.LinearSVC(loss="l3").fit, X, y)
# FIXME remove in 1.0
def test_linearsvx_loss_penalty_deprecations():
X, y = [[0.0], [1.0]], [0, 1]
msg = ("loss='%s' has been deprecated in favor of "
"loss='%s' as of 0.16. Backward compatibility"
" for the %s will be removed in %s")
# LinearSVC
# loss l1/L1 --> hinge
assert_warns_message(DeprecationWarning,
msg % ("l1", "hinge", "loss='l1'", "1.0"),
svm.LinearSVC(loss="l1").fit, X, y)
# loss l2/L2 --> squared_hinge
assert_warns_message(DeprecationWarning,
msg % ("L2", "squared_hinge", "loss='L2'", "1.0"),
svm.LinearSVC(loss="L2").fit, X, y)
# LinearSVR
# loss l1/L1 --> epsilon_insensitive
assert_warns_message(DeprecationWarning,
msg % ("L1", "epsilon_insensitive", "loss='L1'",
"1.0"),
svm.LinearSVR(loss="L1").fit, X, y)
# loss l2/L2 --> squared_epsilon_insensitive
assert_warns_message(DeprecationWarning,
msg % ("l2", "squared_epsilon_insensitive",
"loss='l2'", "1.0"),
svm.LinearSVR(loss="l2").fit, X, y)
# FIXME remove in 0.18
def test_linear_svx_uppercase_loss_penalty():
# Check if Upper case notation is supported by _fit_liblinear
# which is called by fit
X, y = [[0.0], [1.0]], [0, 1]
msg = ("loss='%s' has been deprecated in favor of "
"loss='%s' as of 0.16. Backward compatibility"
" for the uppercase notation will be removed in %s")
# loss SQUARED_hinge --> squared_hinge
assert_warns_message(DeprecationWarning,
msg % ("SQUARED_hinge", "squared_hinge", "0.18"),
svm.LinearSVC(loss="SQUARED_hinge").fit, X, y)
# penalty L2 --> l2
assert_warns_message(DeprecationWarning,
msg.replace("loss", "penalty")
% ("L2", "l2", "0.18"),
svm.LinearSVC(penalty="L2").fit, X, y)
# loss EPSILON_INSENSITIVE --> epsilon_insensitive
assert_warns_message(DeprecationWarning,
msg % ("EPSILON_INSENSITIVE", "epsilon_insensitive",
"0.18"),
svm.LinearSVR(loss="EPSILON_INSENSITIVE").fit, X, y)
def test_linearsvc():
# Test basic routines using LinearSVC
clf = svm.LinearSVC(random_state=0).fit(X, Y)
# by default should have intercept
assert_true(clf.fit_intercept)
assert_array_equal(clf.predict(T), true_result)
assert_array_almost_equal(clf.intercept_, [0], decimal=3)
# the same with l1 penalty
clf = svm.LinearSVC(penalty='l1', loss='squared_hinge', dual=False, random_state=0).fit(X, Y)
assert_array_equal(clf.predict(T), true_result)
# l2 penalty with dual formulation
clf = svm.LinearSVC(penalty='l2', dual=True, random_state=0).fit(X, Y)
assert_array_equal(clf.predict(T), true_result)
# l2 penalty, l1 loss
clf = svm.LinearSVC(penalty='l2', loss='hinge', dual=True, random_state=0)
clf.fit(X, Y)
assert_array_equal(clf.predict(T), true_result)
# test also decision function
dec = clf.decision_function(T)
res = (dec > 0).astype(np.int) + 1
assert_array_equal(res, true_result)
def test_linearsvc_crammer_singer():
# Test LinearSVC with crammer_singer multi-class svm
ovr_clf = svm.LinearSVC(random_state=0).fit(iris.data, iris.target)
cs_clf = svm.LinearSVC(multi_class='crammer_singer', random_state=0)
cs_clf.fit(iris.data, iris.target)
# similar prediction for ovr and crammer-singer:
assert_true((ovr_clf.predict(iris.data) ==
cs_clf.predict(iris.data)).mean() > .9)
# classifiers shouldn't be the same
assert_true((ovr_clf.coef_ != cs_clf.coef_).all())
# test decision function
assert_array_equal(cs_clf.predict(iris.data),
np.argmax(cs_clf.decision_function(iris.data), axis=1))
dec_func = np.dot(iris.data, cs_clf.coef_.T) + cs_clf.intercept_
assert_array_almost_equal(dec_func, cs_clf.decision_function(iris.data))
def test_crammer_singer_binary():
# Test Crammer-Singer formulation in the binary case
X, y = make_classification(n_classes=2, random_state=0)
for fit_intercept in (True, False):
acc = svm.LinearSVC(fit_intercept=fit_intercept,
multi_class="crammer_singer",
random_state=0).fit(X, y).score(X, y)
assert_greater(acc, 0.9)
def test_linearsvc_iris():
# Test that LinearSVC gives plausible predictions on the iris dataset
# Also, test symbolic class names (classes_).
target = iris.target_names[iris.target]
clf = svm.LinearSVC(random_state=0).fit(iris.data, target)
assert_equal(set(clf.classes_), set(iris.target_names))
assert_greater(np.mean(clf.predict(iris.data) == target), 0.8)
dec = clf.decision_function(iris.data)
pred = iris.target_names[np.argmax(dec, 1)]
assert_array_equal(pred, clf.predict(iris.data))
def test_dense_liblinear_intercept_handling(classifier=svm.LinearSVC):
# Test that dense liblinear honours intercept_scaling param
X = [[2, 1],
[3, 1],
[1, 3],
[2, 3]]
y = [0, 0, 1, 1]
clf = classifier(fit_intercept=True, penalty='l1', loss='squared_hinge',
dual=False, C=4, tol=1e-7, random_state=0)
assert_true(clf.intercept_scaling == 1, clf.intercept_scaling)
assert_true(clf.fit_intercept)
# when intercept_scaling is low the intercept value is highly "penalized"
# by regularization
clf.intercept_scaling = 1
clf.fit(X, y)
assert_almost_equal(clf.intercept_, 0, decimal=5)
# when intercept_scaling is sufficiently high, the intercept value
# is not affected by regularization
clf.intercept_scaling = 100
clf.fit(X, y)
intercept1 = clf.intercept_
assert_less(intercept1, -1)
# when intercept_scaling is sufficiently high, the intercept value
# doesn't depend on intercept_scaling value
clf.intercept_scaling = 1000
clf.fit(X, y)
intercept2 = clf.intercept_
assert_array_almost_equal(intercept1, intercept2, decimal=2)
def test_liblinear_set_coef():
# multi-class case
clf = svm.LinearSVC().fit(iris.data, iris.target)
values = clf.decision_function(iris.data)
clf.coef_ = clf.coef_.copy()
clf.intercept_ = clf.intercept_.copy()
values2 = clf.decision_function(iris.data)
assert_array_almost_equal(values, values2)
# binary-class case
X = [[2, 1],
[3, 1],
[1, 3],
[2, 3]]
y = [0, 0, 1, 1]
clf = svm.LinearSVC().fit(X, y)
values = clf.decision_function(X)
clf.coef_ = clf.coef_.copy()
clf.intercept_ = clf.intercept_.copy()
values2 = clf.decision_function(X)
assert_array_equal(values, values2)
def test_immutable_coef_property():
# Check that primal coef modification are not silently ignored
svms = [
svm.SVC(kernel='linear').fit(iris.data, iris.target),
svm.NuSVC(kernel='linear').fit(iris.data, iris.target),
svm.SVR(kernel='linear').fit(iris.data, iris.target),
svm.NuSVR(kernel='linear').fit(iris.data, iris.target),
svm.OneClassSVM(kernel='linear').fit(iris.data),
]
for clf in svms:
assert_raises(AttributeError, clf.__setattr__, 'coef_', np.arange(3))
assert_raises((RuntimeError, ValueError),
clf.coef_.__setitem__, (0, 0), 0)
def test_linearsvc_verbose():
# stdout: redirect
import os
stdout = os.dup(1) # save original stdout
os.dup2(os.pipe()[1], 1) # replace it
# actual call
clf = svm.LinearSVC(verbose=1)
clf.fit(X, Y)
# stdout: restore
os.dup2(stdout, 1) # restore original stdout
def test_svc_clone_with_callable_kernel():
# create SVM with callable linear kernel, check that results are the same
# as with built-in linear kernel
svm_callable = svm.SVC(kernel=lambda x, y: np.dot(x, y.T),
probability=True, random_state=0,
decision_function_shape='ovr')
# clone for checking clonability with lambda functions..
svm_cloned = base.clone(svm_callable)
svm_cloned.fit(iris.data, iris.target)
svm_builtin = svm.SVC(kernel='linear', probability=True, random_state=0,
decision_function_shape='ovr')
svm_builtin.fit(iris.data, iris.target)
assert_array_almost_equal(svm_cloned.dual_coef_,
svm_builtin.dual_coef_)
assert_array_almost_equal(svm_cloned.intercept_,
svm_builtin.intercept_)
assert_array_equal(svm_cloned.predict(iris.data),
svm_builtin.predict(iris.data))
assert_array_almost_equal(svm_cloned.predict_proba(iris.data),
svm_builtin.predict_proba(iris.data),
decimal=4)
assert_array_almost_equal(svm_cloned.decision_function(iris.data),
svm_builtin.decision_function(iris.data))
def test_svc_bad_kernel():
svc = svm.SVC(kernel=lambda x, y: x)
assert_raises(ValueError, svc.fit, X, Y)
def test_timeout():
a = svm.SVC(kernel=lambda x, y: np.dot(x, y.T), probability=True,
random_state=0, max_iter=1)
assert_warns(ConvergenceWarning, a.fit, X, Y)
def test_unfitted():
X = "foo!" # input validation not required when SVM not fitted
clf = svm.SVC()
assert_raises_regexp(Exception, r".*\bSVC\b.*\bnot\b.*\bfitted\b",
clf.predict, X)
clf = svm.NuSVR()
assert_raises_regexp(Exception, r".*\bNuSVR\b.*\bnot\b.*\bfitted\b",
clf.predict, X)
# ignore convergence warnings from max_iter=1
@ignore_warnings
def test_consistent_proba():
a = svm.SVC(probability=True, max_iter=1, random_state=0)
proba_1 = a.fit(X, Y).predict_proba(X)
a = svm.SVC(probability=True, max_iter=1, random_state=0)
proba_2 = a.fit(X, Y).predict_proba(X)
assert_array_almost_equal(proba_1, proba_2)
def test_linear_svc_convergence_warnings():
# Test that warnings are raised if model does not converge
lsvc = svm.LinearSVC(max_iter=2, verbose=1)
assert_warns(ConvergenceWarning, lsvc.fit, X, Y)
assert_equal(lsvc.n_iter_, 2)
def test_svr_coef_sign():
# Test that SVR(kernel="linear") has coef_ with the right sign.
# Non-regression test for #2933.
X = np.random.RandomState(21).randn(10, 3)
y = np.random.RandomState(12).randn(10)
for svr in [svm.SVR(kernel='linear'), svm.NuSVR(kernel='linear'),
svm.LinearSVR()]:
svr.fit(X, y)
assert_array_almost_equal(svr.predict(X),
np.dot(X, svr.coef_.ravel()) + svr.intercept_)
def test_linear_svc_intercept_scaling():
# Test that the right error message is thrown when intercept_scaling <= 0
for i in [-1, 0]:
lsvc = svm.LinearSVC(intercept_scaling=i)
msg = ('Intercept scaling is %r but needs to be greater than 0.'
' To disable fitting an intercept,'
' set fit_intercept=False.' % lsvc.intercept_scaling)
assert_raise_message(ValueError, msg, lsvc.fit, X, Y)
def test_lsvc_intercept_scaling_zero():
# Test that intercept_scaling is ignored when fit_intercept is False
lsvc = svm.LinearSVC(fit_intercept=False)
lsvc.fit(X, Y)
assert_equal(lsvc.intercept_, 0.)
def test_hasattr_predict_proba():
# Method must be (un)available before or after fit, switched by
# `probability` param
G = svm.SVC(probability=True)
assert_true(hasattr(G, 'predict_proba'))
G.fit(iris.data, iris.target)
assert_true(hasattr(G, 'predict_proba'))
G = svm.SVC(probability=False)
assert_false(hasattr(G, 'predict_proba'))
G.fit(iris.data, iris.target)
assert_false(hasattr(G, 'predict_proba'))
# Switching to `probability=True` after fitting should make
# predict_proba available, but calling it must not work:
G.probability = True
assert_true(hasattr(G, 'predict_proba'))
msg = "predict_proba is not available when fitted with probability=False"
assert_raise_message(NotFittedError, msg, G.predict_proba, iris.data)
|
bsd-3-clause
|
mikebenfield/scikit-learn
|
sklearn/neighbors/tests/test_nearest_centroid.py
|
305
|
4121
|
"""
Testing for the nearest centroid module.
"""
import numpy as np
from scipy import sparse as sp
from numpy.testing import assert_array_equal
from numpy.testing import assert_equal
from sklearn.neighbors import NearestCentroid
from sklearn import datasets
from sklearn.metrics.pairwise import pairwise_distances
# toy sample
X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]]
X_csr = sp.csr_matrix(X) # Sparse matrix
y = [-1, -1, -1, 1, 1, 1]
T = [[-1, -1], [2, 2], [3, 2]]
T_csr = sp.csr_matrix(T)
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]
def test_classification_toy():
# Check classification on a toy dataset, including sparse versions.
clf = NearestCentroid()
clf.fit(X, y)
assert_array_equal(clf.predict(T), true_result)
# Same test, but with a sparse matrix to fit and test.
clf = NearestCentroid()
clf.fit(X_csr, y)
assert_array_equal(clf.predict(T_csr), true_result)
# Fit with sparse, test with non-sparse
clf = NearestCentroid()
clf.fit(X_csr, y)
assert_array_equal(clf.predict(T), true_result)
# Fit with non-sparse, test with sparse
clf = NearestCentroid()
clf.fit(X, y)
assert_array_equal(clf.predict(T_csr), true_result)
# Fit and predict with non-CSR sparse matrices
clf = NearestCentroid()
clf.fit(X_csr.tocoo(), y)
assert_array_equal(clf.predict(T_csr.tolil()), true_result)
def test_precomputed():
clf = NearestCentroid(metric="precomputed")
clf.fit(X, y)
S = pairwise_distances(T, clf.centroids_)
assert_array_equal(clf.predict(S), true_result)
def test_iris():
# Check consistency on dataset iris.
for metric in ('euclidean', 'cosine'):
clf = NearestCentroid(metric=metric).fit(iris.data, iris.target)
score = np.mean(clf.predict(iris.data) == iris.target)
assert score > 0.9, "Failed with score = " + str(score)
def test_iris_shrinkage():
# Check consistency on dataset iris, when using shrinkage.
for metric in ('euclidean', 'cosine'):
for shrink_threshold in [None, 0.1, 0.5]:
clf = NearestCentroid(metric=metric,
shrink_threshold=shrink_threshold)
clf = clf.fit(iris.data, iris.target)
score = np.mean(clf.predict(iris.data) == iris.target)
assert score > 0.8, "Failed with score = " + str(score)
def test_pickle():
import pickle
# classification
obj = NearestCentroid()
obj.fit(iris.data, iris.target)
score = obj.score(iris.data, iris.target)
s = pickle.dumps(obj)
obj2 = pickle.loads(s)
assert_equal(type(obj2), obj.__class__)
score2 = obj2.score(iris.data, iris.target)
assert_array_equal(score, score2,
"Failed to generate same score"
" after pickling (classification).")
def test_shrinkage_threshold_decoded_y():
clf = NearestCentroid(shrink_threshold=0.01)
y_ind = np.asarray(y)
y_ind[y_ind == -1] = 0
clf.fit(X, y_ind)
centroid_encoded = clf.centroids_
clf.fit(X, y)
assert_array_equal(centroid_encoded, clf.centroids_)
def test_predict_translated_data():
# Test that NearestCentroid gives same results on translated data
rng = np.random.RandomState(0)
X = rng.rand(50, 50)
y = rng.randint(0, 3, 50)
noise = rng.rand(50)
clf = NearestCentroid(shrink_threshold=0.1)
clf.fit(X, y)
y_init = clf.predict(X)
clf = NearestCentroid(shrink_threshold=0.1)
X_noise = X + noise
clf.fit(X_noise, y)
y_translate = clf.predict(X_noise)
assert_array_equal(y_init, y_translate)
def test_manhattan_metric():
# Test the manhattan metric.
clf = NearestCentroid(metric='manhattan')
clf.fit(X, y)
dense_centroid = clf.centroids_
clf.fit(X_csr, y)
assert_array_equal(clf.centroids_, dense_centroid)
assert_array_equal(dense_centroid, [[-1, -1], [1, 1]])
|
bsd-3-clause
|
myinxd/agn-ae
|
utils/cross-match.py
|
1
|
7407
|
# Copyright (C) 2017 Zhixian MA <[email protected]>
"""
Do cross mathcing between labeled samples and the unlabled ones.
methods
=======
icrs2galactic: J2000 sky coordinate to splitted coordinate
galactic2icrs: splitted to J2000 sky coordinate
save_result: save the result to txt
"""
import os
import numpy as np
import argparse
import time
from astropy import units as u
from astropy.coordinates import SkyCoord
from pandas import read_csv
from pandas import read_excel
def coord2split(ra,dec):
"""
Transform coordinates from icrs to galactic
inputs
======
ra: float
dec: float
outputs
=======
coord_str
"""
c = SkyCoord(ra=ra*u.degree, dec=dec*u.degree, frame='icrs')
ra_rms = tuple(c.ra.hms)
dec_dms = tuple(c.dec.dms)
ra_h = "%02d" % (int(ra_rms[0]))
ra_m = "%02d" % (int(ra_rms[1]))
ra_s_i = np.fix(np.round(ra_rms[2]*100)/100)
ra_s_f = np.round(ra_rms[2]*100)/100 - ra_s_i
ra_s = "%02d.%02d" % (int(ra_s_i),int(ra_s_f*100))
if dec_dms[0] > 0:
de_d = "+%02d" % (int(dec_dms[0]))
else:
de_d = "-%02d" % (abs(int(dec_dms[0])))
de_m = "%02d" % (abs(int(dec_dms[1])))
de_s_i = np.fix(np.abs(np.round(dec_dms[2]*10)/10))
de_s_f = np.abs(np.round(dec_dms[2]*10)/10) - de_s_i
de_s = "%02d.%01d" % (int(de_s_i),np.round(de_s_f*10))
coord_str = 'J' + ''.join([ra_h,ra_m,ra_s,de_d,de_m,de_s]) + '.fits'
return coord_str
def split2coord(ra_hms, dec_dms):
"""
Transform from icrs to galactic
inputs
======
ra_hms: str
dec_dms: str
outputs
=======
ra: float
dec: float
"""
c = SkyCoord(ra=ra_hms, dec=dec_dms, frame='icrs')
return c.ra.value, c.dec.value
def save2csv(samplelist,csvname):
"""
Save result to csv
inputs
======
samplelist: dict
The cross matched samplelist
{"labeled": [], "unlabeled": [], "RA": [], "DEC": [], "idx": []}
csvname: str
path to save the result
"""
from pandas import DataFrame
numsamples = len(samplelist['labeled'])
sample_frame = DataFrame(samplelist, index=range(0,numsamples))
# write
sample_frame.to_csv(csvname, sep=' ')
def findmatch(s_match,s_all, bias=0.001):
"""
Find matched samples
s_match: tuple
icrs coordinate of the sample to be matched, (ra, dec)
s_all: list
The list of all the unlabeled samples
bias: float
The largest bias between two matched sample
"""
s_ra = s_all[0,:] - s_match[0]
s_dec = s_all[1,:] - s_match[1]
s_dist = np.sqrt(s_ra*s_ra + s_dec*s_dec)
s_dist_min = s_dist.min()
if s_dist_min > bias:
s_idx = [-1]
fname_all = "nomatching"
else:
s_idx = np.where(s_dist == s_dist_min)[0]
fname_all = coord2split(ra=s_all[0, s_idx],dec=s_all[1,s_idx[0]])
# get coord strings
fname_match = coord2split(ra=s_match[0],dec=s_match[1])
return [fname_match, fname_all, s_match[0], s_match[1], s_idx[0]]
def main():
# Init
parser = argparse.ArgumentParser(description="Cross matching samples")
# parameters
parser.add_argument("pathmatch",help="Path of samples to be cross matched.")
parser.add_argument("pathall",help="path of the samplelist.")
parser.add_argument("csvpath",help="path to save the matched result.")
parser.add_argument("bias",help="Minimum bias between to matched objects."
args = parser.parse_args()
pathmatch = args.pathmatch
pathall = args.pathall
csvpath = args.csvpath
bias = args.bias
# sample_frame
sample_frame = {"labeled": [],
"unlabeled": [],
"RA": [],
"DEC": [],
"idx": []}
# read list of all
listall = read_csv(pathall, sep=' ')
s_all_ra = listall['RAJ2000']
s_all_dec = listall['DEJ2000']
s_all = np.vstack([s_all_ra, s_all_dec])
print(s_all.shape)
# read list of samples to be matched
# FRICAT
"""
f = read_excel(pathmatch)
samples = f.get_values()
ra = samples[:,1]
for i in range(len(ra)):
t = time.strftime('%Y-%m-%d: %H:%M:%S', time.localtime(time.time()))
# get parameters
s_ra = "%sh%sm%ss" % (ra[i][2:4], ra[i][4:6], ra[i][6:11])
s_dec= "%sd%sm%ss" % (ra[i][11:14],ra[i][14:16],ra[i][16:20])
print("[%s] Matching sample locates at %s\t%s" % (t,s_ra,s_dec))
match_str = findmatch(s_match=split2coord(s_ra,s_dec), s_all=s_all, bias=bias)
sample_frame["labeled"].append(match_str[0])
sample_frame["unlabeled"].append(match_str[1])
sample_frame["RA"].append(match_str[2])
sample_frame["DEC"].append(match_str[3])
sample_frame["idx"].append(match_str[4])
# FRIICAT
fp = open(pathmatch, 'r')
samples = fp.readlines()
for i in range(len(samples)):
t = time.strftime('%Y-%m-%d: %H:%M:%S', time.localtime(time.time()))
s = samples[i].split(" ")
ra = s[1]
# get parameters
s_ra = "%sh%sm%ss" % (ra[1:3], ra[3:5], ra[5:10])
s_dec= "%sd%sm%ss" % (ra[10:13],ra[13:15],ra[15:19])
print("[%s] Matching sample locates at %s\t%s" % (t,s_ra,s_dec))
match_str = findmatch(s_match=split2coord(s_ra,s_dec), s_all=s_all, bias=bias)
sample_frame["labeled"].append(match_str[0])
sample_frame["unlabeled"].append(match_str[1])
sample_frame["RA"].append(match_str[2])
sample_frame["DEC"].append(match_str[3])
sample_frame["idx"].append(match_str[4])
# X-shaped
f = read_excel(pathmatch)
samples = f.get_values()
ra = samples[:,1]
dec = samples[:,2]
for i in range(len(ra)):
t = time.strftime('%Y-%m-%d: %H:%M:%S', time.localtime(time.time()))
RA = ra[i][1:-2].split(' ')
DEC = dec[i][1:-2].split(' ')
# get parameters
if DEC[0][0] == '−':
DEC[0] = '-'+DEC[0][1:]
s_ra = "%sh%sm%ss" % (RA[0], RA[1], RA[2])
s_dec= "%sd%sm%ss" % (DEC[0], DEC[1], DEC[2])
print("[%s] Matching sample locates at %s\t%s" % (t,s_ra,s_dec))
match_str = findmatch(s_match=split2coord(s_ra,s_dec), s_all=s_all, bias=bias)
sample_frame["labeled"].append(match_str[0])
sample_frame["unlabeled"].append(match_str[1])
sample_frame["RA"].append(match_str[2])
sample_frame["DEC"].append(match_str[3])
sample_frame["idx"].append(match_str[4])
"""
# Proctor
fp = open(pathmatch, 'r')
samples = fp.readlines()
for i in range(len(samples)):
t = time.strftime('%Y-%m-%d: %H:%M:%S', time.localtime(time.time()))
s = samples[i].split(" ")
ra = s[4:7]
dec = s[8:11]
# get parameters
s_ra = "%sh%sm%ss" % (ra[0], ra[1], ra[2])
s_dec= "%sd%sm%ss" % (dec[0],dec[1], dec[2])
print("[%s] Matching sample locates at %s\t%s" % (t,s_ra,s_dec))
match_str = findmatch(s_match=split2coord(s_ra,s_dec), s_all=s_all, bias=bias)
sample_frame["labeled"].append(match_str[0])
sample_frame["unlabeled"].append(match_str[1])
sample_frame["RA"].append(match_str[2])
sample_frame["DEC"].append(match_str[3])
sample_frame["idx"].append(match_str[4])
# save
save2csv(sample_frame, csvpath)
if __name__ == "__main__":
main()
|
mit
|
jordipons/EUSIPCO2017
|
src/test.py
|
1
|
5867
|
import numpy as np
import common, train
import theano.tensor as T
import lasagne
from sklearn import metrics
import os, time, json
"""
test.py: evaluates how the trained model performs.
Requires the previous run of 'train.py'.
The results and parameters of this script are stored in common.DATA_FOLDER/test/
Step 5/5 of the pipeline.
"""
test_params = {
'partition' : 'test', # para ver en train cuando hace!! para medir overfitting.
'model_name' : ['dieleman_setup_eusipco2017_proposed2_v0_128172504761355761965820505631639987477'],
'test_name' : 'TEST_'+str(int(time.time()))
}
def compute_auc(estimated,true):
'''
AUC is computed at the tag level because there are many songs in the MTT having no annotations - zeros array.
Input dimensions:
- estimated: #songs x #outputNeurons
- true: #songs x #annotations
where #outputNeurons = #annotations
'''
aucs=[]
for count in range(estimated.shape[1]-1):
if np.min(true[:,count]) != np.max(true[:,count]):
auc = metrics.roc_auc_score(true[:,count],estimated[:,count])
aucs.append(auc)
else:
print 'WARNING: All 0s or 1s, can not compute AUC! Tag #'+str(count)
return np.mean(aucs)
if __name__ == '__main__':
print 'Number of models to test: '+str(len(test_params['model_name']))
first=True
for model in test_params['model_name']:
print '\nMODEL: '+model
print(" - Set environment..")
# load parameters from previous processing step: 'spectrograms.py', 'exp_setup.py' and 'patches.py'
config = json.load(open(common.DATA_FOLDER+'train/'+model+'.param'))
config['test_params'] = test_params
print '\t'+str(config)
idx_id_block_test=train.index_patches(common.DATA_FOLDER+config['patches']+test_params['partition']+'/all_patches_ids.tsv')
num_test_patches=len(idx_id_block_test)
print 'Number of testing examples (patches): '+str(num_test_patches)
if first:
patch_labels=np.empty((0,2+config['setup_params']['numOutputNeurons']*2))
# id [0], patch-number [1], prediction [2:numOutputNeurons+2], target [numOutputNeurons+2:]
first=False
print(" - Building network..")
input_var = T.tensor4('inputs')
target_var = T.imatrix('targets')
train_fn,val_fn,predict_fn,network,config=train.buildNet(input_var,target_var,config)
print(" - Loading model..")
# load model
with np.load(common.DATA_FOLDER+'train/'+model+'.npz') as f:
param_values = [f['arr_%d' % i] for i in range(len(f.files))]
lasagne.layers.set_all_param_values(network, param_values)
print(" - Running predictions..")
# test set: predict patches
test_err = []
test_auc = []
batch_counter=0
for batch in train.iterate_minibatches(config,idx_id_block_test, config['batchSize'],'test'):
inputs, targets, ids, patch_number = batch
batch_counter=batch_counter+config['batchSize']
if batch_counter%1000==0:
print str(batch_counter)+'/'+str(num_test_patches)
# compute error
err = val_fn(inputs, targets)
test_err.append(err[0])
# compute prediction
prediction = predict_fn(inputs)
for c in range(0,len(targets),1): # DO THIS BY MATRICES intead of using a for.
tmp=np.array([ids[c],patch_number[c]])
tmp=np.append(tmp,targets[c])
tmp=np.append(tmp,prediction[c])
patch_labels=np.append(patch_labels,tmp.reshape(1,2+config['setup_params']['numOutputNeurons']*2),axis=0)
print '\nRUN EVALUATION:'
# average with patches having same id
patch_labels_avg=np.empty((0,1+config['setup_params']['numOutputNeurons']*2))# id, prediction, target
ids_list=np.unique(patch_labels[:,0])
for id in ids_list:
idx=np.where(patch_labels[:,0]==id)
tmp=np.array([id])
tmp=np.append(tmp,patch_labels[idx[0][0],2:2+config['setup_params']['numOutputNeurons']])
tmp=np.append(tmp,np.average(patch_labels[idx,2+config['setup_params']['numOutputNeurons']:][0],axis=0))
patch_labels_avg=np.append(patch_labels_avg,tmp.reshape(1,1+config['setup_params']['numOutputNeurons']*2),axis=0)
# compute individual auc
auc_individual = compute_auc(patch_labels[:,2+config['setup_params']['numOutputNeurons']:],patch_labels[:,2:2+config['setup_params']['numOutputNeurons']])
auc_avg = compute_auc(patch_labels_avg[:,1+config['setup_params']['numOutputNeurons']:],patch_labels_avg[:,1:1+config['setup_params']['numOutputNeurons']])
# output
print(" Final results:")
print(" test loss:\t\t\t\t\t{:.6f}".format(np.mean(test_err)))
print(" patch level - test auc:\t\t{:.4f}".format(auc_individual))
print(" [AVG] song level - test auc:\t{:.4f}".format(auc_avg))
print(" number of weights: \t\t\t{:.0f}".format(config['numParamArchitecture']))
# storing data: tracking the results
test_folder = common.DATA_FOLDER+'test/'
if not os.path.exists(test_folder):
os.makedirs(test_folder)
res = open(test_folder+config['test_params']['test_name']+'_'+config['test_params']['partition']+'.result', 'a')
res.write("\nFinal results:\n")
res.write(" test loss:\t\t\t\t\t{:.6f}\n".format(np.mean(test_err)))
res.write(" patch level - test auc:\t\t{:.4f}\n".format(auc_individual))
res.write(" [AVG] song level - test auc:\t{:.4f}\n".format(auc_avg))
res.write(" number of weights: \t\t\t{:.0f}\n".format(config['numParamArchitecture']))
json.dump(test_params, open(test_folder+config['test_params']['test_name']+'_'+config['test_params']['partition']+'.param','w'))
|
mit
|
toobaz/pandas
|
pandas/tests/plotting/test_converter.py
|
1
|
12402
|
from datetime import date, datetime
import subprocess
import sys
import numpy as np
import pytest
import pandas._config.config as cf
from pandas.compat.numpy import np_datetime64_compat
from pandas import Index, Period, Series, Timestamp, date_range
import pandas.util.testing as tm
from pandas.plotting import (
deregister_matplotlib_converters,
register_matplotlib_converters,
)
from pandas.tseries.offsets import Day, Micro, Milli, Second
try:
from pandas.plotting._matplotlib import converter
except ImportError:
# try / except, rather than skip, to avoid internal refactoring
# causing an improprer skip
pass
pytest.importorskip("matplotlib.pyplot")
def test_initial_warning():
code = (
"import pandas as pd; import matplotlib.pyplot as plt; "
"s = pd.Series(1, pd.date_range('2000', periods=12)); "
"fig, ax = plt.subplots(); "
"ax.plot(s.index, s.values)"
)
call = [sys.executable, "-c", code]
out = subprocess.check_output(call, stderr=subprocess.STDOUT).decode()
assert "Using an implicitly" in out
def test_timtetonum_accepts_unicode():
assert converter.time2num("00:01") == converter.time2num("00:01")
class TestRegistration:
def test_register_by_default(self):
# Run in subprocess to ensure a clean state
code = (
"'import matplotlib.units; "
"import pandas as pd; "
"units = dict(matplotlib.units.registry); "
"assert pd.Timestamp in units)'"
)
call = [sys.executable, "-c", code]
assert subprocess.check_call(call) == 0
def test_warns(self):
plt = pytest.importorskip("matplotlib.pyplot")
s = Series(range(12), index=date_range("2017", periods=12))
_, ax = plt.subplots()
# Set to the "warning" state, in case this isn't the first test run
converter._WARN = True
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False) as w:
ax.plot(s.index, s.values)
plt.close()
assert len(w) == 1
assert "Using an implicitly registered datetime converter" in str(w[0])
def test_registering_no_warning(self):
plt = pytest.importorskip("matplotlib.pyplot")
s = Series(range(12), index=date_range("2017", periods=12))
_, ax = plt.subplots()
# Set to the "warn" state, in case this isn't the first test run
converter._WARN = True
register_matplotlib_converters()
with tm.assert_produces_warning(None) as w:
ax.plot(s.index, s.values)
assert len(w) == 0
def test_pandas_plots_register(self):
pytest.importorskip("matplotlib.pyplot")
s = Series(range(12), index=date_range("2017", periods=12))
# Set to the "warn" state, in case this isn't the first test run
converter._WARN = True
with tm.assert_produces_warning(None) as w:
s.plot()
assert len(w) == 0
def test_matplotlib_formatters(self):
units = pytest.importorskip("matplotlib.units")
assert Timestamp in units.registry
ctx = cf.option_context("plotting.matplotlib.register_converters", False)
with ctx:
assert Timestamp not in units.registry
assert Timestamp in units.registry
def test_option_no_warning(self):
pytest.importorskip("matplotlib.pyplot")
ctx = cf.option_context("plotting.matplotlib.register_converters", False)
plt = pytest.importorskip("matplotlib.pyplot")
s = Series(range(12), index=date_range("2017", periods=12))
_, ax = plt.subplots()
converter._WARN = True
# Test without registering first, no warning
with ctx:
with tm.assert_produces_warning(None) as w:
ax.plot(s.index, s.values)
assert len(w) == 0
# Now test with registering
converter._WARN = True
register_matplotlib_converters()
with ctx:
with tm.assert_produces_warning(None) as w:
ax.plot(s.index, s.values)
assert len(w) == 0
def test_registry_resets(self):
units = pytest.importorskip("matplotlib.units")
dates = pytest.importorskip("matplotlib.dates")
# make a copy, to reset to
original = dict(units.registry)
try:
# get to a known state
units.registry.clear()
date_converter = dates.DateConverter()
units.registry[datetime] = date_converter
units.registry[date] = date_converter
register_matplotlib_converters()
assert units.registry[date] is not date_converter
deregister_matplotlib_converters()
assert units.registry[date] is date_converter
finally:
# restore original stater
units.registry.clear()
for k, v in original.items():
units.registry[k] = v
def test_old_import_warns(self):
with tm.assert_produces_warning(FutureWarning) as w:
from pandas.tseries import converter
converter.register()
assert len(w)
assert "pandas.plotting.register_matplotlib_converters" in str(w[0].message)
class TestDateTimeConverter:
def setup_method(self, method):
self.dtc = converter.DatetimeConverter()
self.tc = converter.TimeFormatter(None)
def test_convert_accepts_unicode(self):
r1 = self.dtc.convert("12:22", None, None)
r2 = self.dtc.convert("12:22", None, None)
assert r1 == r2, "DatetimeConverter.convert should accept unicode"
def test_conversion(self):
rs = self.dtc.convert(["2012-1-1"], None, None)[0]
xp = datetime(2012, 1, 1).toordinal()
assert rs == xp
rs = self.dtc.convert("2012-1-1", None, None)
assert rs == xp
rs = self.dtc.convert(date(2012, 1, 1), None, None)
assert rs == xp
rs = self.dtc.convert(datetime(2012, 1, 1).toordinal(), None, None)
assert rs == xp
rs = self.dtc.convert("2012-1-1", None, None)
assert rs == xp
rs = self.dtc.convert(Timestamp("2012-1-1"), None, None)
assert rs == xp
# also testing datetime64 dtype (GH8614)
rs = self.dtc.convert(np_datetime64_compat("2012-01-01"), None, None)
assert rs == xp
rs = self.dtc.convert(
np_datetime64_compat("2012-01-01 00:00:00+0000"), None, None
)
assert rs == xp
rs = self.dtc.convert(
np.array(
[
np_datetime64_compat("2012-01-01 00:00:00+0000"),
np_datetime64_compat("2012-01-02 00:00:00+0000"),
]
),
None,
None,
)
assert rs[0] == xp
# we have a tz-aware date (constructed to that when we turn to utc it
# is the same as our sample)
ts = Timestamp("2012-01-01").tz_localize("UTC").tz_convert("US/Eastern")
rs = self.dtc.convert(ts, None, None)
assert rs == xp
rs = self.dtc.convert(ts.to_pydatetime(), None, None)
assert rs == xp
rs = self.dtc.convert(Index([ts - Day(1), ts]), None, None)
assert rs[1] == xp
rs = self.dtc.convert(Index([ts - Day(1), ts]).to_pydatetime(), None, None)
assert rs[1] == xp
def test_conversion_float(self):
decimals = 9
rs = self.dtc.convert(Timestamp("2012-1-1 01:02:03", tz="UTC"), None, None)
xp = converter.dates.date2num(Timestamp("2012-1-1 01:02:03", tz="UTC"))
tm.assert_almost_equal(rs, xp, decimals)
rs = self.dtc.convert(
Timestamp("2012-1-1 09:02:03", tz="Asia/Hong_Kong"), None, None
)
tm.assert_almost_equal(rs, xp, decimals)
rs = self.dtc.convert(datetime(2012, 1, 1, 1, 2, 3), None, None)
tm.assert_almost_equal(rs, xp, decimals)
def test_conversion_outofbounds_datetime(self):
# 2579
values = [date(1677, 1, 1), date(1677, 1, 2)]
rs = self.dtc.convert(values, None, None)
xp = converter.dates.date2num(values)
tm.assert_numpy_array_equal(rs, xp)
rs = self.dtc.convert(values[0], None, None)
xp = converter.dates.date2num(values[0])
assert rs == xp
values = [datetime(1677, 1, 1, 12), datetime(1677, 1, 2, 12)]
rs = self.dtc.convert(values, None, None)
xp = converter.dates.date2num(values)
tm.assert_numpy_array_equal(rs, xp)
rs = self.dtc.convert(values[0], None, None)
xp = converter.dates.date2num(values[0])
assert rs == xp
@pytest.mark.parametrize(
"time,format_expected",
[
(0, "00:00"), # time2num(datetime.time.min)
(86399.999999, "23:59:59.999999"), # time2num(datetime.time.max)
(90000, "01:00"),
(3723, "01:02:03"),
(39723.2, "11:02:03.200"),
],
)
def test_time_formatter(self, time, format_expected):
# issue 18478
result = self.tc(time)
assert result == format_expected
def test_dateindex_conversion(self):
decimals = 9
for freq in ("B", "L", "S"):
dateindex = tm.makeDateIndex(k=10, freq=freq)
rs = self.dtc.convert(dateindex, None, None)
xp = converter.dates.date2num(dateindex._mpl_repr())
tm.assert_almost_equal(rs, xp, decimals)
def test_resolution(self):
def _assert_less(ts1, ts2):
val1 = self.dtc.convert(ts1, None, None)
val2 = self.dtc.convert(ts2, None, None)
if not val1 < val2:
raise AssertionError("{0} is not less than {1}.".format(val1, val2))
# Matplotlib's time representation using floats cannot distinguish
# intervals smaller than ~10 microsecond in the common range of years.
ts = Timestamp("2012-1-1")
_assert_less(ts, ts + Second())
_assert_less(ts, ts + Milli())
_assert_less(ts, ts + Micro(50))
def test_convert_nested(self):
inner = [Timestamp("2017-01-01"), Timestamp("2017-01-02")]
data = [inner, inner]
result = self.dtc.convert(data, None, None)
expected = [self.dtc.convert(x, None, None) for x in data]
assert (np.array(result) == expected).all()
class TestPeriodConverter:
def setup_method(self, method):
self.pc = converter.PeriodConverter()
class Axis:
pass
self.axis = Axis()
self.axis.freq = "D"
def test_convert_accepts_unicode(self):
r1 = self.pc.convert("2012-1-1", None, self.axis)
r2 = self.pc.convert("2012-1-1", None, self.axis)
assert r1 == r2
def test_conversion(self):
rs = self.pc.convert(["2012-1-1"], None, self.axis)[0]
xp = Period("2012-1-1").ordinal
assert rs == xp
rs = self.pc.convert("2012-1-1", None, self.axis)
assert rs == xp
rs = self.pc.convert([date(2012, 1, 1)], None, self.axis)[0]
assert rs == xp
rs = self.pc.convert(date(2012, 1, 1), None, self.axis)
assert rs == xp
rs = self.pc.convert([Timestamp("2012-1-1")], None, self.axis)[0]
assert rs == xp
rs = self.pc.convert(Timestamp("2012-1-1"), None, self.axis)
assert rs == xp
rs = self.pc.convert(np_datetime64_compat("2012-01-01"), None, self.axis)
assert rs == xp
rs = self.pc.convert(
np_datetime64_compat("2012-01-01 00:00:00+0000"), None, self.axis
)
assert rs == xp
rs = self.pc.convert(
np.array(
[
np_datetime64_compat("2012-01-01 00:00:00+0000"),
np_datetime64_compat("2012-01-02 00:00:00+0000"),
]
),
None,
self.axis,
)
assert rs[0] == xp
def test_integer_passthrough(self):
# GH9012
rs = self.pc.convert([0, 1], None, self.axis)
xp = [0, 1]
assert rs == xp
def test_convert_nested(self):
data = ["2012-1-1", "2012-1-2"]
r1 = self.pc.convert([data, data], None, self.axis)
r2 = [self.pc.convert(data, None, self.axis) for _ in range(2)]
assert r1 == r2
|
bsd-3-clause
|
ky822/scikit-learn
|
examples/mixture/plot_gmm_classifier.py
|
250
|
3918
|
"""
==================
GMM classification
==================
Demonstration of Gaussian mixture models for classification.
See :ref:`gmm` for more information on the estimator.
Plots predicted labels on both training and held out test data using a
variety of GMM classifiers on the iris dataset.
Compares GMMs with spherical, diagonal, full, and tied covariance
matrices in increasing order of performance. Although one would
expect full covariance to perform best in general, it is prone to
overfitting on small datasets and does not generalize well to held out
test data.
On the plots, train data is shown as dots, while test data is shown as
crosses. The iris dataset is four-dimensional. Only the first two
dimensions are shown here, and thus some points are separated in other
dimensions.
"""
print(__doc__)
# Author: Ron Weiss <[email protected]>, Gael Varoquaux
# License: BSD 3 clause
# $Id$
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from sklearn import datasets
from sklearn.cross_validation import StratifiedKFold
from sklearn.externals.six.moves import xrange
from sklearn.mixture import GMM
def make_ellipses(gmm, ax):
for n, color in enumerate('rgb'):
v, w = np.linalg.eigh(gmm._get_covars()[n][:2, :2])
u = w[0] / np.linalg.norm(w[0])
angle = np.arctan2(u[1], u[0])
angle = 180 * angle / np.pi # convert to degrees
v *= 9
ell = mpl.patches.Ellipse(gmm.means_[n, :2], v[0], v[1],
180 + angle, color=color)
ell.set_clip_box(ax.bbox)
ell.set_alpha(0.5)
ax.add_artist(ell)
iris = datasets.load_iris()
# Break up the dataset into non-overlapping training (75%) and testing
# (25%) sets.
skf = StratifiedKFold(iris.target, n_folds=4)
# Only take the first fold.
train_index, test_index = next(iter(skf))
X_train = iris.data[train_index]
y_train = iris.target[train_index]
X_test = iris.data[test_index]
y_test = iris.target[test_index]
n_classes = len(np.unique(y_train))
# Try GMMs using different types of covariances.
classifiers = dict((covar_type, GMM(n_components=n_classes,
covariance_type=covar_type, init_params='wc', n_iter=20))
for covar_type in ['spherical', 'diag', 'tied', 'full'])
n_classifiers = len(classifiers)
plt.figure(figsize=(3 * n_classifiers / 2, 6))
plt.subplots_adjust(bottom=.01, top=0.95, hspace=.15, wspace=.05,
left=.01, right=.99)
for index, (name, classifier) in enumerate(classifiers.items()):
# Since we have class labels for the training data, we can
# initialize the GMM parameters in a supervised manner.
classifier.means_ = np.array([X_train[y_train == i].mean(axis=0)
for i in xrange(n_classes)])
# Train the other parameters using the EM algorithm.
classifier.fit(X_train)
h = plt.subplot(2, n_classifiers / 2, index + 1)
make_ellipses(classifier, h)
for n, color in enumerate('rgb'):
data = iris.data[iris.target == n]
plt.scatter(data[:, 0], data[:, 1], 0.8, color=color,
label=iris.target_names[n])
# Plot the test data with crosses
for n, color in enumerate('rgb'):
data = X_test[y_test == n]
plt.plot(data[:, 0], data[:, 1], 'x', color=color)
y_train_pred = classifier.predict(X_train)
train_accuracy = np.mean(y_train_pred.ravel() == y_train.ravel()) * 100
plt.text(0.05, 0.9, 'Train accuracy: %.1f' % train_accuracy,
transform=h.transAxes)
y_test_pred = classifier.predict(X_test)
test_accuracy = np.mean(y_test_pred.ravel() == y_test.ravel()) * 100
plt.text(0.05, 0.8, 'Test accuracy: %.1f' % test_accuracy,
transform=h.transAxes)
plt.xticks(())
plt.yticks(())
plt.title(name)
plt.legend(loc='lower right', prop=dict(size=12))
plt.show()
|
bsd-3-clause
|
YinongLong/scikit-learn
|
sklearn/preprocessing/data.py
|
5
|
69949
|
# Authors: Alexandre Gramfort <[email protected]>
# Mathieu Blondel <[email protected]>
# Olivier Grisel <[email protected]>
# Andreas Mueller <[email protected]>
# Eric Martin <[email protected]>
# Giorgio Patrini <[email protected]>
# License: BSD 3 clause
from itertools import chain, combinations
import numbers
import warnings
import numpy as np
from scipy import sparse
from ..base import BaseEstimator, TransformerMixin
from ..externals import six
from ..utils import check_array
from ..utils import deprecated
from ..utils.extmath import row_norms
from ..utils.extmath import _incremental_mean_and_var
from ..utils.fixes import combinations_with_replacement as combinations_w_r
from ..utils.fixes import bincount
from ..utils.sparsefuncs_fast import (inplace_csr_row_normalize_l1,
inplace_csr_row_normalize_l2)
from ..utils.sparsefuncs import (inplace_column_scale,
mean_variance_axis, incr_mean_variance_axis,
min_max_axis)
from ..utils.validation import check_is_fitted, FLOAT_DTYPES
zip = six.moves.zip
map = six.moves.map
range = six.moves.range
__all__ = [
'Binarizer',
'KernelCenterer',
'MinMaxScaler',
'MaxAbsScaler',
'Normalizer',
'OneHotEncoder',
'RobustScaler',
'StandardScaler',
'add_dummy_feature',
'binarize',
'normalize',
'scale',
'robust_scale',
'maxabs_scale',
'minmax_scale',
]
DEPRECATION_MSG_1D = (
"Passing 1d arrays as data is deprecated in 0.17 and will "
"raise ValueError in 0.19. Reshape your data either using "
"X.reshape(-1, 1) if your data has a single feature or "
"X.reshape(1, -1) if it contains a single sample."
)
def _handle_zeros_in_scale(scale, copy=True):
''' Makes sure that whenever scale is zero, we handle it correctly.
This happens in most scalers when we have constant features.'''
# if we are fitting on 1D arrays, scale might be a scalar
if np.isscalar(scale):
if scale == .0:
scale = 1.
return scale
elif isinstance(scale, np.ndarray):
if copy:
# New array to avoid side-effects
scale = scale.copy()
scale[scale == 0.0] = 1.0
return scale
def scale(X, axis=0, with_mean=True, with_std=True, copy=True):
"""Standardize a dataset along any axis
Center to the mean and component wise scale to unit variance.
Read more in the :ref:`User Guide <preprocessing_scaler>`.
Parameters
----------
X : {array-like, sparse matrix}
The data to center and scale.
axis : int (0 by default)
axis used to compute the means and standard deviations along. If 0,
independently standardize each feature, otherwise (if 1) standardize
each sample.
with_mean : boolean, True by default
If True, center the data before scaling.
with_std : boolean, True by default
If True, scale the data to unit variance (or equivalently,
unit standard deviation).
copy : boolean, optional, default True
set to False to perform inplace row normalization and avoid a
copy (if the input is already a numpy array or a scipy.sparse
CSC matrix and if axis is 1).
Notes
-----
This implementation will refuse to center scipy.sparse matrices
since it would make them non-sparse and would potentially crash the
program with memory exhaustion problems.
Instead the caller is expected to either set explicitly
`with_mean=False` (in that case, only variance scaling will be
performed on the features of the CSC matrix) or to call `X.toarray()`
if he/she expects the materialized dense array to fit in memory.
To avoid memory copy the caller should pass a CSC matrix.
See also
--------
StandardScaler: Performs scaling to unit variance using the``Transformer`` API
(e.g. as part of a preprocessing :class:`sklearn.pipeline.Pipeline`).
""" # noqa
X = check_array(X, accept_sparse='csc', copy=copy, ensure_2d=False,
warn_on_dtype=True, estimator='the scale function',
dtype=FLOAT_DTYPES)
if sparse.issparse(X):
if with_mean:
raise ValueError(
"Cannot center sparse matrices: pass `with_mean=False` instead"
" See docstring for motivation and alternatives.")
if axis != 0:
raise ValueError("Can only scale sparse matrix on axis=0, "
" got axis=%d" % axis)
if with_std:
_, var = mean_variance_axis(X, axis=0)
var = _handle_zeros_in_scale(var, copy=False)
inplace_column_scale(X, 1 / np.sqrt(var))
else:
X = np.asarray(X)
if with_mean:
mean_ = np.mean(X, axis)
if with_std:
scale_ = np.std(X, axis)
# Xr is a view on the original array that enables easy use of
# broadcasting on the axis in which we are interested in
Xr = np.rollaxis(X, axis)
if with_mean:
Xr -= mean_
mean_1 = Xr.mean(axis=0)
# Verify that mean_1 is 'close to zero'. If X contains very
# large values, mean_1 can also be very large, due to a lack of
# precision of mean_. In this case, a pre-scaling of the
# concerned feature is efficient, for instance by its mean or
# maximum.
if not np.allclose(mean_1, 0):
warnings.warn("Numerical issues were encountered "
"when centering the data "
"and might not be solved. Dataset may "
"contain too large values. You may need "
"to prescale your features.")
Xr -= mean_1
if with_std:
scale_ = _handle_zeros_in_scale(scale_, copy=False)
Xr /= scale_
if with_mean:
mean_2 = Xr.mean(axis=0)
# If mean_2 is not 'close to zero', it comes from the fact that
# scale_ is very small so that mean_2 = mean_1/scale_ > 0, even
# if mean_1 was close to zero. The problem is thus essentially
# due to the lack of precision of mean_. A solution is then to
# subtract the mean again:
if not np.allclose(mean_2, 0):
warnings.warn("Numerical issues were encountered "
"when scaling the data "
"and might not be solved. The standard "
"deviation of the data is probably "
"very close to 0. ")
Xr -= mean_2
return X
class MinMaxScaler(BaseEstimator, TransformerMixin):
"""Transforms features by scaling each feature to a given range.
This estimator scales and translates each feature individually such
that it is in the given range on the training set, i.e. between
zero and one.
The transformation is given by::
X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0))
X_scaled = X_std * (max - min) + min
where min, max = feature_range.
This transformation is often used as an alternative to zero mean,
unit variance scaling.
Read more in the :ref:`User Guide <preprocessing_scaler>`.
Parameters
----------
feature_range: tuple (min, max), default=(0, 1)
Desired range of transformed data.
copy : boolean, optional, default True
Set to False to perform inplace row normalization and avoid a
copy (if the input is already a numpy array).
Attributes
----------
min_ : ndarray, shape (n_features,)
Per feature adjustment for minimum.
scale_ : ndarray, shape (n_features,)
Per feature relative scaling of the data.
.. versionadded:: 0.17
*scale_* attribute.
data_min_ : ndarray, shape (n_features,)
Per feature minimum seen in the data
.. versionadded:: 0.17
*data_min_* instead of deprecated *data_min*.
data_max_ : ndarray, shape (n_features,)
Per feature maximum seen in the data
.. versionadded:: 0.17
*data_max_* instead of deprecated *data_max*.
data_range_ : ndarray, shape (n_features,)
Per feature range ``(data_max_ - data_min_)`` seen in the data
.. versionadded:: 0.17
*data_range_* instead of deprecated *data_range*.
See also
--------
minmax_scale: Equivalent function without the object oriented API.
"""
def __init__(self, feature_range=(0, 1), copy=True):
self.feature_range = feature_range
self.copy = copy
@property
@deprecated("Attribute data_range will be removed in "
"0.19. Use ``data_range_`` instead")
def data_range(self):
return self.data_range_
@property
@deprecated("Attribute data_min will be removed in "
"0.19. Use ``data_min_`` instead")
def data_min(self):
return self.data_min_
def _reset(self):
"""Reset internal data-dependent state of the scaler, if necessary.
__init__ parameters are not touched.
"""
# Checking one attribute is enough, becase they are all set together
# in partial_fit
if hasattr(self, 'scale_'):
del self.scale_
del self.min_
del self.n_samples_seen_
del self.data_min_
del self.data_max_
del self.data_range_
def fit(self, X, y=None):
"""Compute the minimum and maximum to be used for later scaling.
Parameters
----------
X : array-like, shape [n_samples, n_features]
The data used to compute the per-feature minimum and maximum
used for later scaling along the features axis.
"""
# Reset internal state before fitting
self._reset()
return self.partial_fit(X, y)
def partial_fit(self, X, y=None):
"""Online computation of min and max on X for later scaling.
All of X is processed as a single batch. This is intended for cases
when `fit` is not feasible due to very large number of `n_samples`
or because X is read from a continuous stream.
Parameters
----------
X : array-like, shape [n_samples, n_features]
The data used to compute the mean and standard deviation
used for later scaling along the features axis.
y : Passthrough for ``Pipeline`` compatibility.
"""
feature_range = self.feature_range
if feature_range[0] >= feature_range[1]:
raise ValueError("Minimum of desired feature range must be smaller"
" than maximum. Got %s." % str(feature_range))
if sparse.issparse(X):
raise TypeError("MinMaxScaler does no support sparse input. "
"You may consider to use MaxAbsScaler instead.")
X = check_array(X, copy=self.copy, ensure_2d=False, warn_on_dtype=True,
estimator=self, dtype=FLOAT_DTYPES)
if X.ndim == 1:
warnings.warn(DEPRECATION_MSG_1D, DeprecationWarning)
data_min = np.min(X, axis=0)
data_max = np.max(X, axis=0)
# First pass
if not hasattr(self, 'n_samples_seen_'):
self.n_samples_seen_ = X.shape[0]
# Next steps
else:
data_min = np.minimum(self.data_min_, data_min)
data_max = np.maximum(self.data_max_, data_max)
self.n_samples_seen_ += X.shape[0]
data_range = data_max - data_min
self.scale_ = ((feature_range[1] - feature_range[0]) /
_handle_zeros_in_scale(data_range))
self.min_ = feature_range[0] - data_min * self.scale_
self.data_min_ = data_min
self.data_max_ = data_max
self.data_range_ = data_range
return self
def transform(self, X):
"""Scaling features of X according to feature_range.
Parameters
----------
X : array-like, shape [n_samples, n_features]
Input data that will be transformed.
"""
check_is_fitted(self, 'scale_')
X = check_array(X, copy=self.copy, ensure_2d=False, dtype=FLOAT_DTYPES)
if X.ndim == 1:
warnings.warn(DEPRECATION_MSG_1D, DeprecationWarning)
X *= self.scale_
X += self.min_
return X
def inverse_transform(self, X):
"""Undo the scaling of X according to feature_range.
Parameters
----------
X : array-like, shape [n_samples, n_features]
Input data that will be transformed. It cannot be sparse.
"""
check_is_fitted(self, 'scale_')
X = check_array(X, copy=self.copy, ensure_2d=False, dtype=FLOAT_DTYPES)
if X.ndim == 1:
warnings.warn(DEPRECATION_MSG_1D, DeprecationWarning)
X -= self.min_
X /= self.scale_
return X
def minmax_scale(X, feature_range=(0, 1), axis=0, copy=True):
"""Transforms features by scaling each feature to a given range.
This estimator scales and translates each feature individually such
that it is in the given range on the training set, i.e. between
zero and one.
The transformation is given by::
X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0))
X_scaled = X_std * (max - min) + min
where min, max = feature_range.
This transformation is often used as an alternative to zero mean,
unit variance scaling.
Read more in the :ref:`User Guide <preprocessing_scaler>`.
.. versionadded:: 0.17
*minmax_scale* function interface
to :class:`sklearn.preprocessing.MinMaxScaler`.
Parameters
----------
feature_range: tuple (min, max), default=(0, 1)
Desired range of transformed data.
axis : int (0 by default)
axis used to scale along. If 0, independently scale each feature,
otherwise (if 1) scale each sample.
copy : boolean, optional, default is True
Set to False to perform inplace scaling and avoid a copy (if the input
is already a numpy array).
See also
--------
MinMaxScaler: Performs scaling to a given range using the``Transformer`` API
(e.g. as part of a preprocessing :class:`sklearn.pipeline.Pipeline`).
""" # noqa
# To allow retro-compatibility, we handle here the case of 1D-input
# From 0.17, 1D-input are deprecated in scaler objects
# Although, we want to allow the users to keep calling this function
# with 1D-input.
# Cast input to array, as we need to check ndim. Prior to 0.17, that was
# done inside the scaler object fit_transform.
# If copy is required, it will be done inside the scaler object.
X = check_array(X, copy=False, ensure_2d=False, warn_on_dtype=True,
dtype=FLOAT_DTYPES)
original_ndim = X.ndim
if original_ndim == 1:
X = X.reshape(X.shape[0], 1)
s = MinMaxScaler(feature_range=feature_range, copy=copy)
if axis == 0:
X = s.fit_transform(X)
else:
X = s.fit_transform(X.T).T
if original_ndim == 1:
X = X.ravel()
return X
class StandardScaler(BaseEstimator, TransformerMixin):
"""Standardize features by removing the mean and scaling to unit variance
Centering and scaling happen independently on each feature by computing
the relevant statistics on the samples in the training set. Mean and
standard deviation are then stored to be used on later data using the
`transform` method.
Standardization of a dataset is a common requirement for many
machine learning estimators: they might behave badly if the
individual feature do not more or less look like standard normally
distributed data (e.g. Gaussian with 0 mean and unit variance).
For instance many elements used in the objective function of
a learning algorithm (such as the RBF kernel of Support Vector
Machines or the L1 and L2 regularizers of linear models) assume that
all features are centered around 0 and have variance in the same
order. If a feature has a variance that is orders of magnitude larger
that others, it might dominate the objective function and make the
estimator unable to learn from other features correctly as expected.
This scaler can also be applied to sparse CSR or CSC matrices by passing
`with_mean=False` to avoid breaking the sparsity structure of the data.
Read more in the :ref:`User Guide <preprocessing_scaler>`.
Parameters
----------
with_mean : boolean, True by default
If True, center the data before scaling.
This does not work (and will raise an exception) when attempted on
sparse matrices, because centering them entails building a dense
matrix which in common use cases is likely to be too large to fit in
memory.
with_std : boolean, True by default
If True, scale the data to unit variance (or equivalently,
unit standard deviation).
copy : boolean, optional, default True
If False, try to avoid a copy and do inplace scaling instead.
This is not guaranteed to always work inplace; e.g. if the data is
not a NumPy array or scipy.sparse CSR matrix, a copy may still be
returned.
Attributes
----------
scale_ : ndarray, shape (n_features,)
Per feature relative scaling of the data.
.. versionadded:: 0.17
*scale_* is recommended instead of deprecated *std_*.
mean_ : array of floats with shape [n_features]
The mean value for each feature in the training set.
var_ : array of floats with shape [n_features]
The variance for each feature in the training set. Used to compute
`scale_`
n_samples_seen_ : int
The number of samples processed by the estimator. Will be reset on
new calls to fit, but increments across ``partial_fit`` calls.
See also
--------
scale: Equivalent function without the object oriented API.
:class:`sklearn.decomposition.PCA`
Further removes the linear correlation across features with 'whiten=True'.
""" # noqa
def __init__(self, copy=True, with_mean=True, with_std=True):
self.with_mean = with_mean
self.with_std = with_std
self.copy = copy
@property
@deprecated("Attribute ``std_`` will be removed in 0.19. "
"Use ``scale_`` instead")
def std_(self):
return self.scale_
def _reset(self):
"""Reset internal data-dependent state of the scaler, if necessary.
__init__ parameters are not touched.
"""
# Checking one attribute is enough, becase they are all set together
# in partial_fit
if hasattr(self, 'scale_'):
del self.scale_
del self.n_samples_seen_
del self.mean_
del self.var_
def fit(self, X, y=None):
"""Compute the mean and std to be used for later scaling.
Parameters
----------
X : {array-like, sparse matrix}, shape [n_samples, n_features]
The data used to compute the mean and standard deviation
used for later scaling along the features axis.
y: Passthrough for ``Pipeline`` compatibility.
"""
# Reset internal state before fitting
self._reset()
return self.partial_fit(X, y)
def partial_fit(self, X, y=None):
"""Online computation of mean and std on X for later scaling.
All of X is processed as a single batch. This is intended for cases
when `fit` is not feasible due to very large number of `n_samples`
or because X is read from a continuous stream.
The algorithm for incremental mean and std is given in Equation 1.5a,b
in Chan, Tony F., Gene H. Golub, and Randall J. LeVeque. "Algorithms
for computing the sample variance: Analysis and recommendations."
The American Statistician 37.3 (1983): 242-247:
Parameters
----------
X : {array-like, sparse matrix}, shape [n_samples, n_features]
The data used to compute the mean and standard deviation
used for later scaling along the features axis.
y: Passthrough for ``Pipeline`` compatibility.
"""
X = check_array(X, accept_sparse=('csr', 'csc'), copy=self.copy,
ensure_2d=False, warn_on_dtype=True,
estimator=self, dtype=FLOAT_DTYPES)
if X.ndim == 1:
warnings.warn(DEPRECATION_MSG_1D, DeprecationWarning)
# Even in the case of `with_mean=False`, we update the mean anyway
# This is needed for the incremental computation of the var
# See incr_mean_variance_axis and _incremental_mean_variance_axis
if sparse.issparse(X):
if self.with_mean:
raise ValueError(
"Cannot center sparse matrices: pass `with_mean=False` "
"instead. See docstring for motivation and alternatives.")
if self.with_std:
# First pass
if not hasattr(self, 'n_samples_seen_'):
self.mean_, self.var_ = mean_variance_axis(X, axis=0)
self.n_samples_seen_ = X.shape[0]
# Next passes
else:
self.mean_, self.var_, self.n_samples_seen_ = \
incr_mean_variance_axis(X, axis=0,
last_mean=self.mean_,
last_var=self.var_,
last_n=self.n_samples_seen_)
else:
self.mean_ = None
self.var_ = None
else:
# First pass
if not hasattr(self, 'n_samples_seen_'):
self.mean_ = .0
self.n_samples_seen_ = 0
if self.with_std:
self.var_ = .0
else:
self.var_ = None
self.mean_, self.var_, self.n_samples_seen_ = \
_incremental_mean_and_var(X, self.mean_, self.var_,
self.n_samples_seen_)
if self.with_std:
self.scale_ = _handle_zeros_in_scale(np.sqrt(self.var_))
else:
self.scale_ = None
return self
def transform(self, X, y=None, copy=None):
"""Perform standardization by centering and scaling
Parameters
----------
X : array-like, shape [n_samples, n_features]
The data used to scale along the features axis.
"""
check_is_fitted(self, 'scale_')
copy = copy if copy is not None else self.copy
X = check_array(X, accept_sparse='csr', copy=copy,
ensure_2d=False, warn_on_dtype=True,
estimator=self, dtype=FLOAT_DTYPES)
if X.ndim == 1:
warnings.warn(DEPRECATION_MSG_1D, DeprecationWarning)
if sparse.issparse(X):
if self.with_mean:
raise ValueError(
"Cannot center sparse matrices: pass `with_mean=False` "
"instead. See docstring for motivation and alternatives.")
if self.scale_ is not None:
inplace_column_scale(X, 1 / self.scale_)
else:
if self.with_mean:
X -= self.mean_
if self.with_std:
X /= self.scale_
return X
def inverse_transform(self, X, copy=None):
"""Scale back the data to the original representation
Parameters
----------
X : array-like, shape [n_samples, n_features]
The data used to scale along the features axis.
"""
check_is_fitted(self, 'scale_')
copy = copy if copy is not None else self.copy
if sparse.issparse(X):
if self.with_mean:
raise ValueError(
"Cannot uncenter sparse matrices: pass `with_mean=False` "
"instead See docstring for motivation and alternatives.")
if not sparse.isspmatrix_csr(X):
X = X.tocsr()
copy = False
if copy:
X = X.copy()
if self.scale_ is not None:
inplace_column_scale(X, self.scale_)
else:
X = np.asarray(X)
if copy:
X = X.copy()
if self.with_std:
X *= self.scale_
if self.with_mean:
X += self.mean_
return X
class MaxAbsScaler(BaseEstimator, TransformerMixin):
"""Scale each feature by its maximum absolute value.
This estimator scales and translates each feature individually such
that the maximal absolute value of each feature in the
training set will be 1.0. It does not shift/center the data, and
thus does not destroy any sparsity.
This scaler can also be applied to sparse CSR or CSC matrices.
.. versionadded:: 0.17
Parameters
----------
copy : boolean, optional, default is True
Set to False to perform inplace scaling and avoid a copy (if the input
is already a numpy array).
Attributes
----------
scale_ : ndarray, shape (n_features,)
Per feature relative scaling of the data.
.. versionadded:: 0.17
*scale_* attribute.
max_abs_ : ndarray, shape (n_features,)
Per feature maximum absolute value.
n_samples_seen_ : int
The number of samples processed by the estimator. Will be reset on
new calls to fit, but increments across ``partial_fit`` calls.
See also
--------
maxabs_scale: Equivalent function without the object oriented API.
"""
def __init__(self, copy=True):
self.copy = copy
def _reset(self):
"""Reset internal data-dependent state of the scaler, if necessary.
__init__ parameters are not touched.
"""
# Checking one attribute is enough, becase they are all set together
# in partial_fit
if hasattr(self, 'scale_'):
del self.scale_
del self.n_samples_seen_
del self.max_abs_
def fit(self, X, y=None):
"""Compute the maximum absolute value to be used for later scaling.
Parameters
----------
X : {array-like, sparse matrix}, shape [n_samples, n_features]
The data used to compute the per-feature minimum and maximum
used for later scaling along the features axis.
"""
# Reset internal state before fitting
self._reset()
return self.partial_fit(X, y)
def partial_fit(self, X, y=None):
"""Online computation of max absolute value of X for later scaling.
All of X is processed as a single batch. This is intended for cases
when `fit` is not feasible due to very large number of `n_samples`
or because X is read from a continuous stream.
Parameters
----------
X : {array-like, sparse matrix}, shape [n_samples, n_features]
The data used to compute the mean and standard deviation
used for later scaling along the features axis.
y: Passthrough for ``Pipeline`` compatibility.
"""
X = check_array(X, accept_sparse=('csr', 'csc'), copy=self.copy,
ensure_2d=False, estimator=self, dtype=FLOAT_DTYPES)
if X.ndim == 1:
warnings.warn(DEPRECATION_MSG_1D, DeprecationWarning)
if sparse.issparse(X):
mins, maxs = min_max_axis(X, axis=0)
max_abs = np.maximum(np.abs(mins), np.abs(maxs))
else:
max_abs = np.abs(X).max(axis=0)
# First pass
if not hasattr(self, 'n_samples_seen_'):
self.n_samples_seen_ = X.shape[0]
# Next passes
else:
max_abs = np.maximum(self.max_abs_, max_abs)
self.n_samples_seen_ += X.shape[0]
self.max_abs_ = max_abs
self.scale_ = _handle_zeros_in_scale(max_abs)
return self
def transform(self, X, y=None):
"""Scale the data
Parameters
----------
X : {array-like, sparse matrix}
The data that should be scaled.
"""
check_is_fitted(self, 'scale_')
X = check_array(X, accept_sparse=('csr', 'csc'), copy=self.copy,
ensure_2d=False, estimator=self, dtype=FLOAT_DTYPES)
if X.ndim == 1:
warnings.warn(DEPRECATION_MSG_1D, DeprecationWarning)
if sparse.issparse(X):
inplace_column_scale(X, 1.0 / self.scale_)
else:
X /= self.scale_
return X
def inverse_transform(self, X):
"""Scale back the data to the original representation
Parameters
----------
X : {array-like, sparse matrix}
The data that should be transformed back.
"""
check_is_fitted(self, 'scale_')
X = check_array(X, accept_sparse=('csr', 'csc'), copy=self.copy,
ensure_2d=False, estimator=self, dtype=FLOAT_DTYPES)
if X.ndim == 1:
warnings.warn(DEPRECATION_MSG_1D, DeprecationWarning)
if sparse.issparse(X):
inplace_column_scale(X, self.scale_)
else:
X *= self.scale_
return X
def maxabs_scale(X, axis=0, copy=True):
"""Scale each feature to the [-1, 1] range without breaking the sparsity.
This estimator scales each feature individually such
that the maximal absolute value of each feature in the
training set will be 1.0.
This scaler can also be applied to sparse CSR or CSC matrices.
Parameters
----------
axis : int (0 by default)
axis used to scale along. If 0, independently scale each feature,
otherwise (if 1) scale each sample.
copy : boolean, optional, default is True
Set to False to perform inplace scaling and avoid a copy (if the input
is already a numpy array).
See also
--------
MaxAbsScaler: Performs scaling to the [-1, 1] range using the``Transformer`` API
(e.g. as part of a preprocessing :class:`sklearn.pipeline.Pipeline`).
""" # noqa
# To allow retro-compatibility, we handle here the case of 1D-input
# From 0.17, 1D-input are deprecated in scaler objects
# Although, we want to allow the users to keep calling this function
# with 1D-input.
# Cast input to array, as we need to check ndim. Prior to 0.17, that was
# done inside the scaler object fit_transform.
# If copy is required, it will be done inside the scaler object.
X = check_array(X, accept_sparse=('csr', 'csc'), copy=False,
ensure_2d=False, dtype=FLOAT_DTYPES)
original_ndim = X.ndim
if original_ndim == 1:
X = X.reshape(X.shape[0], 1)
s = MaxAbsScaler(copy=copy)
if axis == 0:
X = s.fit_transform(X)
else:
X = s.fit_transform(X.T).T
if original_ndim == 1:
X = X.ravel()
return X
class RobustScaler(BaseEstimator, TransformerMixin):
"""Scale features using statistics that are robust to outliers.
This Scaler removes the median and scales the data according to
the quantile range (defaults to IQR: Interquartile Range).
The IQR is the range between the 1st quartile (25th quantile)
and the 3rd quartile (75th quantile).
Centering and scaling happen independently on each feature (or each
sample, depending on the `axis` argument) by computing the relevant
statistics on the samples in the training set. Median and interquartile
range are then stored to be used on later data using the `transform`
method.
Standardization of a dataset is a common requirement for many
machine learning estimators. Typically this is done by removing the mean
and scaling to unit variance. However, outliers can often influence the
sample mean / variance in a negative way. In such cases, the median and
the interquartile range often give better results.
.. versionadded:: 0.17
Read more in the :ref:`User Guide <preprocessing_scaler>`.
Parameters
----------
with_centering : boolean, True by default
If True, center the data before scaling.
This does not work (and will raise an exception) when attempted on
sparse matrices, because centering them entails building a dense
matrix which in common use cases is likely to be too large to fit in
memory.
with_scaling : boolean, True by default
If True, scale the data to interquartile range.
quantile_range : tuple (q_min, q_max), 0.0 < q_min < q_max < 100.0
Default: (25.0, 75.0) = (1st quantile, 3rd quantile) = IQR
Quantile range used to calculate ``scale_``.
.. versionadded:: 0.18
copy : boolean, optional, default is True
If False, try to avoid a copy and do inplace scaling instead.
This is not guaranteed to always work inplace; e.g. if the data is
not a NumPy array or scipy.sparse CSR matrix, a copy may still be
returned.
Attributes
----------
center_ : array of floats
The median value for each feature in the training set.
scale_ : array of floats
The (scaled) interquartile range for each feature in the training set.
.. versionadded:: 0.17
*scale_* attribute.
See also
--------
robust_scale: Equivalent function without the object oriented API.
:class:`sklearn.decomposition.PCA`
Further removes the linear correlation across features with
'whiten=True'.
Notes
-----
See examples/preprocessing/plot_robust_scaling.py for an example.
https://en.wikipedia.org/wiki/Median_(statistics)
https://en.wikipedia.org/wiki/Interquartile_range
"""
def __init__(self, with_centering=True, with_scaling=True,
quantile_range=(25.0, 75.0), copy=True):
self.with_centering = with_centering
self.with_scaling = with_scaling
self.quantile_range = quantile_range
self.copy = copy
def _check_array(self, X, copy):
"""Makes sure centering is not enabled for sparse matrices."""
X = check_array(X, accept_sparse=('csr', 'csc'), copy=self.copy,
ensure_2d=False, estimator=self, dtype=FLOAT_DTYPES)
if X.ndim == 1:
warnings.warn(DEPRECATION_MSG_1D, DeprecationWarning)
if sparse.issparse(X):
if self.with_centering:
raise ValueError(
"Cannot center sparse matrices: use `with_centering=False`"
" instead. See docstring for motivation and alternatives.")
return X
def fit(self, X, y=None):
"""Compute the median and quantiles to be used for scaling.
Parameters
----------
X : array-like, shape [n_samples, n_features]
The data used to compute the median and quantiles
used for later scaling along the features axis.
"""
if sparse.issparse(X):
raise TypeError("RobustScaler cannot be fitted on sparse inputs")
X = self._check_array(X, self.copy)
if X.ndim == 1:
warnings.warn(DEPRECATION_MSG_1D, DeprecationWarning)
if self.with_centering:
self.center_ = np.median(X, axis=0)
if self.with_scaling:
q_min, q_max = self.quantile_range
if not 0 <= q_min <= q_max <= 100:
raise ValueError("Invalid quantile range: %s" %
str(self.quantile_range))
q = np.percentile(X, self.quantile_range, axis=0)
self.scale_ = (q[1] - q[0])
self.scale_ = _handle_zeros_in_scale(self.scale_, copy=False)
return self
def transform(self, X, y=None):
"""Center and scale the data
Parameters
----------
X : array-like
The data used to scale along the specified axis.
"""
if self.with_centering:
check_is_fitted(self, 'center_')
if self.with_scaling:
check_is_fitted(self, 'scale_')
X = self._check_array(X, self.copy)
if X.ndim == 1:
warnings.warn(DEPRECATION_MSG_1D, DeprecationWarning)
if sparse.issparse(X):
if self.with_scaling:
inplace_column_scale(X, 1.0 / self.scale_)
else:
if self.with_centering:
X -= self.center_
if self.with_scaling:
X /= self.scale_
return X
def inverse_transform(self, X):
"""Scale back the data to the original representation
Parameters
----------
X : array-like
The data used to scale along the specified axis.
"""
if self.with_centering:
check_is_fitted(self, 'center_')
if self.with_scaling:
check_is_fitted(self, 'scale_')
X = self._check_array(X, self.copy)
if X.ndim == 1:
warnings.warn(DEPRECATION_MSG_1D, DeprecationWarning)
if sparse.issparse(X):
if self.with_scaling:
inplace_column_scale(X, self.scale_)
else:
if self.with_scaling:
X *= self.scale_
if self.with_centering:
X += self.center_
return X
def robust_scale(X, axis=0, with_centering=True, with_scaling=True,
quantile_range=(25.0, 75.0), copy=True):
"""Standardize a dataset along any axis
Center to the median and component wise scale
according to the interquartile range.
Read more in the :ref:`User Guide <preprocessing_scaler>`.
Parameters
----------
X : array-like
The data to center and scale.
axis : int (0 by default)
axis used to compute the medians and IQR along. If 0,
independently scale each feature, otherwise (if 1) scale
each sample.
with_centering : boolean, True by default
If True, center the data before scaling.
with_scaling : boolean, True by default
If True, scale the data to unit variance (or equivalently,
unit standard deviation).
quantile_range : tuple (q_min, q_max), 0.0 < q_min < q_max < 100.0
Default: (25.0, 75.0) = (1st quantile, 3rd quantile) = IQR
Quantile range used to calculate ``scale_``.
.. versionadded:: 0.18
copy : boolean, optional, default is True
set to False to perform inplace row normalization and avoid a
copy (if the input is already a numpy array or a scipy.sparse
CSR matrix and if axis is 1).
Notes
-----
This implementation will refuse to center scipy.sparse matrices
since it would make them non-sparse and would potentially crash the
program with memory exhaustion problems.
Instead the caller is expected to either set explicitly
`with_centering=False` (in that case, only variance scaling will be
performed on the features of the CSR matrix) or to call `X.toarray()`
if he/she expects the materialized dense array to fit in memory.
To avoid memory copy the caller should pass a CSR matrix.
See also
--------
RobustScaler: Performs centering and scaling using the ``Transformer`` API
(e.g. as part of a preprocessing :class:`sklearn.pipeline.Pipeline`).
"""
s = RobustScaler(with_centering=with_centering, with_scaling=with_scaling,
quantile_range=quantile_range, copy=copy)
if axis == 0:
return s.fit_transform(X)
else:
return s.fit_transform(X.T).T
class PolynomialFeatures(BaseEstimator, TransformerMixin):
"""Generate polynomial and interaction features.
Generate a new feature matrix consisting of all polynomial combinations
of the features with degree less than or equal to the specified degree.
For example, if an input sample is two dimensional and of the form
[a, b], the degree-2 polynomial features are [1, a, b, a^2, ab, b^2].
Parameters
----------
degree : integer
The degree of the polynomial features. Default = 2.
interaction_only : boolean, default = False
If true, only interaction features are produced: features that are
products of at most ``degree`` *distinct* input features (so not
``x[1] ** 2``, ``x[0] * x[2] ** 3``, etc.).
include_bias : boolean
If True (default), then include a bias column, the feature in which
all polynomial powers are zero (i.e. a column of ones - acts as an
intercept term in a linear model).
Examples
--------
>>> X = np.arange(6).reshape(3, 2)
>>> X
array([[0, 1],
[2, 3],
[4, 5]])
>>> poly = PolynomialFeatures(2)
>>> poly.fit_transform(X)
array([[ 1., 0., 1., 0., 0., 1.],
[ 1., 2., 3., 4., 6., 9.],
[ 1., 4., 5., 16., 20., 25.]])
>>> poly = PolynomialFeatures(interaction_only=True)
>>> poly.fit_transform(X)
array([[ 1., 0., 1., 0.],
[ 1., 2., 3., 6.],
[ 1., 4., 5., 20.]])
Attributes
----------
powers_ : array, shape (n_output_features, n_input_features)
powers_[i, j] is the exponent of the jth input in the ith output.
n_input_features_ : int
The total number of input features.
n_output_features_ : int
The total number of polynomial output features. The number of output
features is computed by iterating over all suitably sized combinations
of input features.
Notes
-----
Be aware that the number of features in the output array scales
polynomially in the number of features of the input array, and
exponentially in the degree. High degrees can cause overfitting.
See :ref:`examples/linear_model/plot_polynomial_interpolation.py
<sphx_glr_auto_examples_linear_model_plot_polynomial_interpolation.py>`
"""
def __init__(self, degree=2, interaction_only=False, include_bias=True):
self.degree = degree
self.interaction_only = interaction_only
self.include_bias = include_bias
@staticmethod
def _combinations(n_features, degree, interaction_only, include_bias):
comb = (combinations if interaction_only else combinations_w_r)
start = int(not include_bias)
return chain.from_iterable(comb(range(n_features), i)
for i in range(start, degree + 1))
@property
def powers_(self):
check_is_fitted(self, 'n_input_features_')
combinations = self._combinations(self.n_input_features_, self.degree,
self.interaction_only,
self.include_bias)
return np.vstack(bincount(c, minlength=self.n_input_features_)
for c in combinations)
def get_feature_names(self, input_features=None):
"""
Return feature names for output features
Parameters
----------
input_features : list of string, length n_features, optional
String names for input features if available. By default,
"x0", "x1", ... "xn_features" is used.
Returns
-------
output_feature_names : list of string, length n_output_features
"""
powers = self.powers_
if input_features is None:
input_features = ['x%d' % i for i in range(powers.shape[1])]
feature_names = []
for row in powers:
inds = np.where(row)[0]
if len(inds):
name = " ".join("%s^%d" % (input_features[ind], exp)
if exp != 1 else input_features[ind]
for ind, exp in zip(inds, row[inds]))
else:
name = "1"
feature_names.append(name)
return feature_names
def fit(self, X, y=None):
"""
Compute number of output features.
"""
n_samples, n_features = check_array(X).shape
combinations = self._combinations(n_features, self.degree,
self.interaction_only,
self.include_bias)
self.n_input_features_ = n_features
self.n_output_features_ = sum(1 for _ in combinations)
return self
def transform(self, X, y=None):
"""Transform data to polynomial features
Parameters
----------
X : array-like, shape [n_samples, n_features]
The data to transform, row by row.
Returns
-------
XP : np.ndarray shape [n_samples, NP]
The matrix of features, where NP is the number of polynomial
features generated from the combination of inputs.
"""
check_is_fitted(self, ['n_input_features_', 'n_output_features_'])
X = check_array(X, dtype=FLOAT_DTYPES)
n_samples, n_features = X.shape
if n_features != self.n_input_features_:
raise ValueError("X shape does not match training shape")
# allocate output data
XP = np.empty((n_samples, self.n_output_features_), dtype=X.dtype)
combinations = self._combinations(n_features, self.degree,
self.interaction_only,
self.include_bias)
for i, c in enumerate(combinations):
XP[:, i] = X[:, c].prod(1)
return XP
def normalize(X, norm='l2', axis=1, copy=True, return_norm=False):
"""Scale input vectors individually to unit norm (vector length).
Read more in the :ref:`User Guide <preprocessing_normalization>`.
Parameters
----------
X : {array-like, sparse matrix}, shape [n_samples, n_features]
The data to normalize, element by element.
scipy.sparse matrices should be in CSR format to avoid an
un-necessary copy.
norm : 'l1', 'l2', or 'max', optional ('l2' by default)
The norm to use to normalize each non zero sample (or each non-zero
feature if axis is 0).
axis : 0 or 1, optional (1 by default)
axis used to normalize the data along. If 1, independently normalize
each sample, otherwise (if 0) normalize each feature.
copy : boolean, optional, default True
set to False to perform inplace row normalization and avoid a
copy (if the input is already a numpy array or a scipy.sparse
CSR matrix and if axis is 1).
return_norm : boolean, default False
whether to return the computed norms
See also
--------
Normalizer: Performs normalization using the ``Transformer`` API
(e.g. as part of a preprocessing :class:`sklearn.pipeline.Pipeline`).
"""
if norm not in ('l1', 'l2', 'max'):
raise ValueError("'%s' is not a supported norm" % norm)
if axis == 0:
sparse_format = 'csc'
elif axis == 1:
sparse_format = 'csr'
else:
raise ValueError("'%d' is not a supported axis" % axis)
X = check_array(X, sparse_format, copy=copy, warn_on_dtype=True,
estimator='the normalize function', dtype=FLOAT_DTYPES)
if axis == 0:
X = X.T
if sparse.issparse(X):
if norm == 'l1':
inplace_csr_row_normalize_l1(X)
elif norm == 'l2':
inplace_csr_row_normalize_l2(X)
elif norm == 'max':
_, norms = min_max_axis(X, 1)
norms = norms.repeat(np.diff(X.indptr))
mask = norms != 0
X.data[mask] /= norms[mask]
else:
if norm == 'l1':
norms = np.abs(X).sum(axis=1)
elif norm == 'l2':
norms = row_norms(X)
elif norm == 'max':
norms = np.max(X, axis=1)
norms = _handle_zeros_in_scale(norms, copy=False)
X /= norms[:, np.newaxis]
if axis == 0:
X = X.T
if return_norm:
return X, norms
else:
return X
class Normalizer(BaseEstimator, TransformerMixin):
"""Normalize samples individually to unit norm.
Each sample (i.e. each row of the data matrix) with at least one
non zero component is rescaled independently of other samples so
that its norm (l1 or l2) equals one.
This transformer is able to work both with dense numpy arrays and
scipy.sparse matrix (use CSR format if you want to avoid the burden of
a copy / conversion).
Scaling inputs to unit norms is a common operation for text
classification or clustering for instance. For instance the dot
product of two l2-normalized TF-IDF vectors is the cosine similarity
of the vectors and is the base similarity metric for the Vector
Space Model commonly used by the Information Retrieval community.
Read more in the :ref:`User Guide <preprocessing_normalization>`.
Parameters
----------
norm : 'l1', 'l2', or 'max', optional ('l2' by default)
The norm to use to normalize each non zero sample.
copy : boolean, optional, default True
set to False to perform inplace row normalization and avoid a
copy (if the input is already a numpy array or a scipy.sparse
CSR matrix).
Notes
-----
This estimator is stateless (besides constructor parameters), the
fit method does nothing but is useful when used in a pipeline.
See also
--------
normalize: Equivalent function without the object oriented API.
"""
def __init__(self, norm='l2', copy=True):
self.norm = norm
self.copy = copy
def fit(self, X, y=None):
"""Do nothing and return the estimator unchanged
This method is just there to implement the usual API and hence
work in pipelines.
"""
X = check_array(X, accept_sparse='csr')
return self
def transform(self, X, y=None, copy=None):
"""Scale each non zero row of X to unit norm
Parameters
----------
X : {array-like, sparse matrix}, shape [n_samples, n_features]
The data to normalize, row by row. scipy.sparse matrices should be
in CSR format to avoid an un-necessary copy.
"""
copy = copy if copy is not None else self.copy
X = check_array(X, accept_sparse='csr')
return normalize(X, norm=self.norm, axis=1, copy=copy)
def binarize(X, threshold=0.0, copy=True):
"""Boolean thresholding of array-like or scipy.sparse matrix
Read more in the :ref:`User Guide <preprocessing_binarization>`.
Parameters
----------
X : {array-like, sparse matrix}, shape [n_samples, n_features]
The data to binarize, element by element.
scipy.sparse matrices should be in CSR or CSC format to avoid an
un-necessary copy.
threshold : float, optional (0.0 by default)
Feature values below or equal to this are replaced by 0, above it by 1.
Threshold may not be less than 0 for operations on sparse matrices.
copy : boolean, optional, default True
set to False to perform inplace binarization and avoid a copy
(if the input is already a numpy array or a scipy.sparse CSR / CSC
matrix and if axis is 1).
See also
--------
Binarizer: Performs binarization using the ``Transformer`` API
(e.g. as part of a preprocessing :class:`sklearn.pipeline.Pipeline`).
"""
X = check_array(X, accept_sparse=['csr', 'csc'], copy=copy)
if sparse.issparse(X):
if threshold < 0:
raise ValueError('Cannot binarize a sparse matrix with threshold '
'< 0')
cond = X.data > threshold
not_cond = np.logical_not(cond)
X.data[cond] = 1
X.data[not_cond] = 0
X.eliminate_zeros()
else:
cond = X > threshold
not_cond = np.logical_not(cond)
X[cond] = 1
X[not_cond] = 0
return X
class Binarizer(BaseEstimator, TransformerMixin):
"""Binarize data (set feature values to 0 or 1) according to a threshold
Values greater than the threshold map to 1, while values less than
or equal to the threshold map to 0. With the default threshold of 0,
only positive values map to 1.
Binarization is a common operation on text count data where the
analyst can decide to only consider the presence or absence of a
feature rather than a quantified number of occurrences for instance.
It can also be used as a pre-processing step for estimators that
consider boolean random variables (e.g. modelled using the Bernoulli
distribution in a Bayesian setting).
Read more in the :ref:`User Guide <preprocessing_binarization>`.
Parameters
----------
threshold : float, optional (0.0 by default)
Feature values below or equal to this are replaced by 0, above it by 1.
Threshold may not be less than 0 for operations on sparse matrices.
copy : boolean, optional, default True
set to False to perform inplace binarization and avoid a copy (if
the input is already a numpy array or a scipy.sparse CSR matrix).
Notes
-----
If the input is a sparse matrix, only the non-zero values are subject
to update by the Binarizer class.
This estimator is stateless (besides constructor parameters), the
fit method does nothing but is useful when used in a pipeline.
See also
--------
binarize: Equivalent function without the object oriented API.
"""
def __init__(self, threshold=0.0, copy=True):
self.threshold = threshold
self.copy = copy
def fit(self, X, y=None):
"""Do nothing and return the estimator unchanged
This method is just there to implement the usual API and hence
work in pipelines.
"""
check_array(X, accept_sparse='csr')
return self
def transform(self, X, y=None, copy=None):
"""Binarize each element of X
Parameters
----------
X : {array-like, sparse matrix}, shape [n_samples, n_features]
The data to binarize, element by element.
scipy.sparse matrices should be in CSR format to avoid an
un-necessary copy.
"""
copy = copy if copy is not None else self.copy
return binarize(X, threshold=self.threshold, copy=copy)
class KernelCenterer(BaseEstimator, TransformerMixin):
"""Center a kernel matrix
Let K(x, z) be a kernel defined by phi(x)^T phi(z), where phi is a
function mapping x to a Hilbert space. KernelCenterer centers (i.e.,
normalize to have zero mean) the data without explicitly computing phi(x).
It is equivalent to centering phi(x) with
sklearn.preprocessing.StandardScaler(with_std=False).
Read more in the :ref:`User Guide <kernel_centering>`.
"""
def fit(self, K, y=None):
"""Fit KernelCenterer
Parameters
----------
K : numpy array of shape [n_samples, n_samples]
Kernel matrix.
Returns
-------
self : returns an instance of self.
"""
K = check_array(K, dtype=FLOAT_DTYPES)
n_samples = K.shape[0]
self.K_fit_rows_ = np.sum(K, axis=0) / n_samples
self.K_fit_all_ = self.K_fit_rows_.sum() / n_samples
return self
def transform(self, K, y=None, copy=True):
"""Center kernel matrix.
Parameters
----------
K : numpy array of shape [n_samples1, n_samples2]
Kernel matrix.
copy : boolean, optional, default True
Set to False to perform inplace computation.
Returns
-------
K_new : numpy array of shape [n_samples1, n_samples2]
"""
check_is_fitted(self, 'K_fit_all_')
K = check_array(K, copy=copy, dtype=FLOAT_DTYPES)
K_pred_cols = (np.sum(K, axis=1) /
self.K_fit_rows_.shape[0])[:, np.newaxis]
K -= self.K_fit_rows_
K -= K_pred_cols
K += self.K_fit_all_
return K
@property
def _pairwise(self):
return True
def add_dummy_feature(X, value=1.0):
"""Augment dataset with an additional dummy feature.
This is useful for fitting an intercept term with implementations which
cannot otherwise fit it directly.
Parameters
----------
X : {array-like, sparse matrix}, shape [n_samples, n_features]
Data.
value : float
Value to use for the dummy feature.
Returns
-------
X : {array, sparse matrix}, shape [n_samples, n_features + 1]
Same data with dummy feature added as first column.
Examples
--------
>>> from sklearn.preprocessing import add_dummy_feature
>>> add_dummy_feature([[0, 1], [1, 0]])
array([[ 1., 0., 1.],
[ 1., 1., 0.]])
"""
X = check_array(X, accept_sparse=['csc', 'csr', 'coo'], dtype=FLOAT_DTYPES)
n_samples, n_features = X.shape
shape = (n_samples, n_features + 1)
if sparse.issparse(X):
if sparse.isspmatrix_coo(X):
# Shift columns to the right.
col = X.col + 1
# Column indices of dummy feature are 0 everywhere.
col = np.concatenate((np.zeros(n_samples), col))
# Row indices of dummy feature are 0, ..., n_samples-1.
row = np.concatenate((np.arange(n_samples), X.row))
# Prepend the dummy feature n_samples times.
data = np.concatenate((np.ones(n_samples) * value, X.data))
return sparse.coo_matrix((data, (row, col)), shape)
elif sparse.isspmatrix_csc(X):
# Shift index pointers since we need to add n_samples elements.
indptr = X.indptr + n_samples
# indptr[0] must be 0.
indptr = np.concatenate((np.array([0]), indptr))
# Row indices of dummy feature are 0, ..., n_samples-1.
indices = np.concatenate((np.arange(n_samples), X.indices))
# Prepend the dummy feature n_samples times.
data = np.concatenate((np.ones(n_samples) * value, X.data))
return sparse.csc_matrix((data, indices, indptr), shape)
else:
klass = X.__class__
return klass(add_dummy_feature(X.tocoo(), value))
else:
return np.hstack((np.ones((n_samples, 1)) * value, X))
def _transform_selected(X, transform, selected="all", copy=True):
"""Apply a transform function to portion of selected features
Parameters
----------
X : {array-like, sparse matrix}, shape [n_samples, n_features]
Dense array or sparse matrix.
transform : callable
A callable transform(X) -> X_transformed
copy : boolean, optional
Copy X even if it could be avoided.
selected: "all" or array of indices or mask
Specify which features to apply the transform to.
Returns
-------
X : array or sparse matrix, shape=(n_samples, n_features_new)
"""
X = check_array(X, accept_sparse='csc', copy=copy, dtype=FLOAT_DTYPES)
if isinstance(selected, six.string_types) and selected == "all":
return transform(X)
if len(selected) == 0:
return X
n_features = X.shape[1]
ind = np.arange(n_features)
sel = np.zeros(n_features, dtype=bool)
sel[np.asarray(selected)] = True
not_sel = np.logical_not(sel)
n_selected = np.sum(sel)
if n_selected == 0:
# No features selected.
return X
elif n_selected == n_features:
# All features selected.
return transform(X)
else:
X_sel = transform(X[:, ind[sel]])
X_not_sel = X[:, ind[not_sel]]
if sparse.issparse(X_sel) or sparse.issparse(X_not_sel):
return sparse.hstack((X_sel, X_not_sel))
else:
return np.hstack((X_sel, X_not_sel))
class OneHotEncoder(BaseEstimator, TransformerMixin):
"""Encode categorical integer features using a one-hot aka one-of-K scheme.
The input to this transformer should be a matrix of integers, denoting
the values taken on by categorical (discrete) features. The output will be
a sparse matrix where each column corresponds to one possible value of one
feature. It is assumed that input features take on values in the range
[0, n_values).
This encoding is needed for feeding categorical data to many scikit-learn
estimators, notably linear models and SVMs with the standard kernels.
Read more in the :ref:`User Guide <preprocessing_categorical_features>`.
Parameters
----------
n_values : 'auto', int or array of ints
Number of values per feature.
- 'auto' : determine value range from training data.
- int : number of categorical values per feature.
Each feature value should be in ``range(n_values)``
- array : ``n_values[i]`` is the number of categorical values in
``X[:, i]``. Each feature value should be
in ``range(n_values[i])``
categorical_features: "all" or array of indices or mask
Specify what features are treated as categorical.
- 'all' (default): All features are treated as categorical.
- array of indices: Array of categorical feature indices.
- mask: Array of length n_features and with dtype=bool.
Non-categorical features are always stacked to the right of the matrix.
dtype : number type, default=np.float
Desired dtype of output.
sparse : boolean, default=True
Will return sparse matrix if set True else will return an array.
handle_unknown : str, 'error' or 'ignore'
Whether to raise an error or ignore if a unknown categorical feature is
present during transform.
Attributes
----------
active_features_ : array
Indices for active features, meaning values that actually occur
in the training set. Only available when n_values is ``'auto'``.
feature_indices_ : array of shape (n_features,)
Indices to feature ranges.
Feature ``i`` in the original data is mapped to features
from ``feature_indices_[i]`` to ``feature_indices_[i+1]``
(and then potentially masked by `active_features_` afterwards)
n_values_ : array of shape (n_features,)
Maximum number of values per feature.
Examples
--------
Given a dataset with three features and two samples, we let the encoder
find the maximum value per feature and transform the data to a binary
one-hot encoding.
>>> from sklearn.preprocessing import OneHotEncoder
>>> enc = OneHotEncoder()
>>> enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], \
[1, 0, 2]]) # doctest: +ELLIPSIS
OneHotEncoder(categorical_features='all', dtype=<... 'numpy.float64'>,
handle_unknown='error', n_values='auto', sparse=True)
>>> enc.n_values_
array([2, 3, 4])
>>> enc.feature_indices_
array([0, 2, 5, 9])
>>> enc.transform([[0, 1, 1]]).toarray()
array([[ 1., 0., 0., 1., 0., 0., 1., 0., 0.]])
See also
--------
sklearn.feature_extraction.DictVectorizer : performs a one-hot encoding of
dictionary items (also handles string-valued features).
sklearn.feature_extraction.FeatureHasher : performs an approximate one-hot
encoding of dictionary items or strings.
"""
def __init__(self, n_values="auto", categorical_features="all",
dtype=np.float64, sparse=True, handle_unknown='error'):
self.n_values = n_values
self.categorical_features = categorical_features
self.dtype = dtype
self.sparse = sparse
self.handle_unknown = handle_unknown
def fit(self, X, y=None):
"""Fit OneHotEncoder to X.
Parameters
----------
X : array-like, shape [n_samples, n_feature]
Input array of type int.
Returns
-------
self
"""
self.fit_transform(X)
return self
def _fit_transform(self, X):
"""Assumes X contains only categorical features."""
X = check_array(X, dtype=np.int)
if np.any(X < 0):
raise ValueError("X needs to contain only non-negative integers.")
n_samples, n_features = X.shape
if (isinstance(self.n_values, six.string_types) and
self.n_values == 'auto'):
n_values = np.max(X, axis=0) + 1
elif isinstance(self.n_values, numbers.Integral):
if (np.max(X, axis=0) >= self.n_values).any():
raise ValueError("Feature out of bounds for n_values=%d"
% self.n_values)
n_values = np.empty(n_features, dtype=np.int)
n_values.fill(self.n_values)
else:
try:
n_values = np.asarray(self.n_values, dtype=int)
except (ValueError, TypeError):
raise TypeError("Wrong type for parameter `n_values`. Expected"
" 'auto', int or array of ints, got %r"
% type(X))
if n_values.ndim < 1 or n_values.shape[0] != X.shape[1]:
raise ValueError("Shape mismatch: if n_values is an array,"
" it has to be of shape (n_features,).")
self.n_values_ = n_values
n_values = np.hstack([[0], n_values])
indices = np.cumsum(n_values)
self.feature_indices_ = indices
column_indices = (X + indices[:-1]).ravel()
row_indices = np.repeat(np.arange(n_samples, dtype=np.int32),
n_features)
data = np.ones(n_samples * n_features)
out = sparse.coo_matrix((data, (row_indices, column_indices)),
shape=(n_samples, indices[-1]),
dtype=self.dtype).tocsr()
if (isinstance(self.n_values, six.string_types) and
self.n_values == 'auto'):
mask = np.array(out.sum(axis=0)).ravel() != 0
active_features = np.where(mask)[0]
out = out[:, active_features]
self.active_features_ = active_features
return out if self.sparse else out.toarray()
def fit_transform(self, X, y=None):
"""Fit OneHotEncoder to X, then transform X.
Equivalent to self.fit(X).transform(X), but more convenient and more
efficient. See fit for the parameters, transform for the return value.
"""
return _transform_selected(X, self._fit_transform,
self.categorical_features, copy=True)
def _transform(self, X):
"""Assumes X contains only categorical features."""
X = check_array(X, dtype=np.int)
if np.any(X < 0):
raise ValueError("X needs to contain only non-negative integers.")
n_samples, n_features = X.shape
indices = self.feature_indices_
if n_features != indices.shape[0] - 1:
raise ValueError("X has different shape than during fitting."
" Expected %d, got %d."
% (indices.shape[0] - 1, n_features))
# We use only those categorical features of X that are known using fit.
# i.e lesser than n_values_ using mask.
# This means, if self.handle_unknown is "ignore", the row_indices and
# col_indices corresponding to the unknown categorical feature are
# ignored.
mask = (X < self.n_values_).ravel()
if np.any(~mask):
if self.handle_unknown not in ['error', 'ignore']:
raise ValueError("handle_unknown should be either error or "
"unknown got %s" % self.handle_unknown)
if self.handle_unknown == 'error':
raise ValueError("unknown categorical feature present %s "
"during transform." % X.ravel()[~mask])
column_indices = (X + indices[:-1]).ravel()[mask]
row_indices = np.repeat(np.arange(n_samples, dtype=np.int32),
n_features)[mask]
data = np.ones(np.sum(mask))
out = sparse.coo_matrix((data, (row_indices, column_indices)),
shape=(n_samples, indices[-1]),
dtype=self.dtype).tocsr()
if (isinstance(self.n_values, six.string_types) and
self.n_values == 'auto'):
out = out[:, self.active_features_]
return out if self.sparse else out.toarray()
def transform(self, X):
"""Transform X using one-hot encoding.
Parameters
----------
X : array-like, shape [n_samples, n_features]
Input array of type int.
Returns
-------
X_out : sparse matrix if sparse=True else a 2-d array, dtype=int
Transformed input.
"""
return _transform_selected(X, self._transform,
self.categorical_features, copy=True)
|
bsd-3-clause
|
MartinsMednis/dynamic-modelling-tools
|
modelling_utilities.py
|
1
|
23115
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from pandas import DataFrame, Series
from scipy import stats
import os.path
import math
import statistics
# plt.rcParams.update({'font.size': 12, 'font.family': 'STIXGeneral', 'mathtext.fontset': 'stix'})
plt.rcParams.update({'font.size': 12, 'font.family': 'sans-serif'})
def removenans(data, modelled):
"""remove NaN values from measurements and corresponding modeled values"""
nans = np.isnan(data)
return np.compress(~nans,data), np.compress(~nans,modelled)
def load_experimental_data(sourceDataFrame,expnoList):
df = sourceDataFrame
all_data = list()
for expno in expnoList:
exp_data = df[df['id']==expno] # select the right experiment
dataset = [exp_data['X'].values, exp_data['S'].values, exp_data['P'].values, exp_data['h'].values]
all_data.append(dataset)
return all_data
def mySafeR2(Y,Y_pred):
""" Safe because it removes Nans."""
# yi_list, fi_list = removenans(yi_list, fi_list) # here we don not skip first values, only nans
Y = np.array(Y)
Y_pred = np.array(Y_pred)
Y, Y_pred = removenans(Y, Y_pred)
slope, intercept, r_value, p_value, std_err = stats.linregress(Y,Y_pred)
return r_value**2
def mySafeR2_obsolete(Y,Y_pred):
""" Safe because it removes Nans."""
# yi_list, fi_list = removenans(yi_list, fi_list) # here we don not skip first values, only nans
yi_list, fi_list = removenans(Y, Y_pred)
y_mean = sum(yi_list)/float(len(yi_list))
ss_tot = sum((yi-y_mean)**2 for yi in yi_list)
ss_err = sum((yi-fi)**2 for yi,fi in zip(yi_list,fi_list))
r2 = 1 - (ss_err/ss_tot)
return r2
def mySafeMSE(Y, Y_pred):
""" Safe because it removes Nans and normalizes values. """
y, y_pred = removenans(Y, Y_pred)
y, y_pred = feature_scaling(y, y_pred)
# y, y_pred = zero_mean_variance(y, y_pred)
residual = np.sum( np.power(y - y_pred, 2) )
return 1./(len(y)) * residual
def resc(a,r): # a is array, r is related array. The "r" should always be OBS data.
"""Normalize (rescale) an array"""
def gmax(*args):
lmax = [] # local max values
for l in args:
lmax.append(max(l))
return max(lmax) # find global max value in the list of local max values
def gmin(*args):
lmin = [] # local max values
for l in args:
lmin.append(min(l))
return min(lmin) # find global max value in the list of local max values
b = [] # empty list to store scaled values
for i in a:
if np.isnan(i): # deal with missing data
b.append(np.nan)
else:
b.append( (i-gmin(a,r))/(gmax(a,r) - gmin(a,r)) ) #modeled and measured values the array have to be rescaled using the same min and max values
return np.hstack(b) # create numpy array from list
def feature_scaling(Y, Y_pred):
"""Normalize (rescale) an array"""
Y = np.array(Y)
Y_pred = np.array(Y_pred)
minY = min(Y)
maxY = max(Y)
return (Y - minY)/(maxY - minY), (Y_pred - minY)/(maxY - minY)
def feature_scaling_safe(Y, Y_pred):
"""Normalize (rescale) an array"""
# y ,y_pred = removenans(Y, Y_pred)
Y = np.array(Y)
Y_pred = np.array(Y_pred)
minY = min(y)
maxY = max(y_pred)
return (Y - minY)/(maxY - minY), (Y_pred - minY)/(maxY - minY)
def zero_mean_variance(Y, Y_pred):
y, y_pred = removenans(Y, Y_pred)
Deviation = math.sqrt(statistics.pvariance(y))
Mean = statistics.mean(y)
# print("Mean=={0}, Deviation=={1}".format(Mean,Deviation))
Y = np.array(Y)
Y_pred = np.array(Y_pred)
# return y, y_pred
return (Y - Mean)/Deviation, (Y_pred - Mean)/Deviation
def prepare_modeling_results(model,all_data,expnoList,path,exptitle):
results_table = DataFrame(columns=['h','X','X model','S', 'S model', 'P', 'P model', 'expno', 'XnOBS', 'XnPRED', 'SnOBS', 'SnPRED', 'PnOBS', 'PnPRED'])
for dataset1,expno1 in zip(all_data,expnoList):
results_table1 = model.simulation(dataset1, expno=expno1)
# calculate normalized values
# XnOBS, XnPRED = feature_scaling(results_table1['X'].values,results_table1['X model'].values)
# SnOBS, SnPRED = feature_scaling(results_table1['S'].values,results_table1['S model'].values)
# PnOBS, PnPRED = feature_scaling(results_table1['P'].values,results_table1['P model'].values)
# standardization
XnOBS, XnPRED = zero_mean_variance(results_table1['X'].values,results_table1['X model'].values)
SnOBS, SnPRED = zero_mean_variance(results_table1['S'].values,results_table1['S model'].values)
PnOBS, PnPRED = zero_mean_variance(results_table1['P'].values,results_table1['P model'].values)
# and add them to the table as new columns
results_table1['XnOBS'] = XnOBS
results_table1['XnPRED'] = XnPRED
results_table1['SnOBS'] = SnOBS
results_table1['SnPRED'] = SnPRED
results_table1['PnOBS'] = PnOBS
results_table1['PnPRED'] = PnPRED
# now add the current experiment to the big table of all experiments
results_table = results_table.append(results_table1)
results_table.to_html("{0}results_table_{1}.html".format(path,exptitle))
return results_table
def plot_all_results(model,all_data,expnoList,path):
for dataset1,expno1 in zip(all_data,expnoList):
last_time_point = dataset1[3][-1] + 0.1
t = np.arange(0, last_time_point, 0.1) # smalkaak
parameters = model.parameters
results = model.solution(parameters, t, start_X=dataset1[0][0], start_S = dataset1[1][0], start_E=dataset1[2][0])
plot_results(t,results,dataset1,expno=expno1, path=path)
def plot_all_results_print(model,all_data,expnoList,path):
for dataset1,expno1 in zip(all_data,expnoList):
last_time_point = dataset1[3][-1] + 0.1
t = np.arange(0, last_time_point, 0.1) # smalkaak
parameters = model.parameters
results = model.solution(parameters, t, start_X=dataset1[0][0], start_S = dataset1[1][0], start_E=dataset1[2][0])
plot_results_print(t,results,dataset1,expno=expno1, path=path)
def generate_simulation_results(model,all_data,expnoList,path,exptitle):
results_table_h = DataFrame(columns=['h','X model','S model', 'P model', 'expno'])
for dataset1,expno1 in zip(all_data,expnoList):
last_time_point = dataset1[3][-1] + 0.1
t = np.arange(0, last_time_point, 0.5) # smalkaak
parameters = model.parameters
modeled_values = model.solution(parameters, t, start_X=dataset1[0][0], start_S = dataset1[1][0], start_E=dataset1[2][0])
modeled_values = np.transpose(modeled_values)
results_table = DataFrame(modeled_values)
results_table.columns = ['X model','S model','P model']
results_table['h'] = t
##round values
results_table['X model'] = results_table['X model'].round(4)
results_table['S model'] = results_table['S model'].round(4)
results_table['P model'] = results_table['P model'].round(4)
results_table['expno'] = expno1
results_table_h = results_table_h.append(results_table)
results_table_h = DataFrame(results_table_h, columns=['h','X model','S model', 'P model', 'expno'])
results_table_h.to_html("{0}simulation_{1}.html".format(path,exptitle))
def mycorrelation(data_X,X):
nans = np.isnan(data_X)
data_X = np.compress(~nans,data_X)
X = np.compress(~nans,X)
return np.corrcoef(data_X,X)[0, 1]
def estiamte_miu(h,x):
"""Estimate miu from experimental data"""
all_miu = []
for i in range(len(h)-1):
# miu= (X2-X1)/(t2-t1) * 1/((X2+X1)/2)
miu = ((x[i+1] - x[i])/(h[i+1] - h[i])) * 1./((x[i+1] + x[i])/2)
all_miu.append( miu )
all_miu = [np.nan] + all_miu
return np.hstack(all_miu)
def estiamte_miu_high(h,x):
all_miu = estiamte_miu(h,x)
return max(all_miu[1:-1])
def estiamte_Yxs(x,s):
dx = max(x)-min(x)
ds = max(s)-min(s)
return dx/ds
def estiamte_Yps(p,s):
dp = max(p)-min(p)
ds = max(s)-min(s)
return dp/ds
def nice_charact(results_table1, **kwargs):
"""Returns nicely formatted DataFrame with process characteristics calculated from experimental data"""
miu_high = estiamte_miu_high(results_table1['h'].values, results_table1['X'].values)
Yxs = estiamte_Yxs(results_table1['X'].values, results_table1['S'].values)
Yps = estiamte_Yxs(results_table1['P'].values, results_table1['S'].values)
data_ch = DataFrame({'Parameters':['miu_high', 'Yxs', 'Yps']})
data_ch[kwargs['expno']] = [miu_high, Yxs, Yps]
if 'path' in kwargs:
# print("Saving requested...")
if os.path.isfile(kwargs['path']+'.pickle'):
# print("File exists...")
all_data_ch = pd.read_pickle(kwargs['path']+'.pickle')
all_data_ch[kwargs['expno']] = 0
all_data_ch.drop(kwargs['expno'], axis=1, inplace=True)
all_data_ch = all_data_ch.merge(data_ch, on='Parameters')
all_data_ch.to_pickle(kwargs['path']+'.pickle')
all_data_ch.to_html(kwargs['path']+'.html')
# print("File saved...")
return all_data_ch
else:
print("File for characteristics does not exist...creating a new one.")
data_ch.to_pickle(kwargs['path']+'.pickle')
data_ch.to_html(kwargs['path']+'.html')
# print("New file saved...")
# print("Saving none...")
return data_ch
def plot_correlation(t,results,dataset1,results_table1, **kwargs):
biomass, substrate, product = results
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(10,3))
# miu = (miu_max * S) / (Ks + S + (np.power(S,2)/Ki) ) * Kx/(Kx+np.power(X,nX)) * Kip/(Kip+P) # Haldane + biomass inhibition
## Correlation plots in the same window
axes[0].plot([0,results_table1['X'].max()],[0,results_table1['X'].max()], color = '0.75')
axes[0].plot(results_table1['X'],results_table1['X model'], "o")
axes[0].set_xlabel("measured")
axes[0].set_ylabel("modeled")
# axes[0].set_title("Biomass")
cor = round(mycorrelation(results_table1['X'],results_table1['X model']),4)
corcolor = ('red' if (cor<0.97) else 'black')
axes[0].text(0.9, 0.1, r'Biomass $r^2=$'+format(cor), fontsize=12,transform=axes[0].transAxes, horizontalalignment='right', color=corcolor)
axes[1].plot([0,results_table1['S'].max()],[0,results_table1['S'].max()], color = '0.75')
axes[1].plot(results_table1['S'],results_table1['S model'], "o")
# axes[1].set_title("Substrate")
cor = round(mycorrelation(results_table1['S'],results_table1['S model']),4)
corcolor = ('red' if (cor<0.97) else 'black')
axes[1].text(0.9, 0.1, r'Substrate $r^2=$'+format(cor), fontsize=12,transform=axes[1].transAxes, horizontalalignment='right', color=corcolor)
axes[2].plot([0,results_table1['P'].max()],[0,results_table1['P'].max()], color = '0.75')
axes[2].plot(results_table1['P'],results_table1['P model'], "o")
# axes[2].set_title("Product")
cor = round(mycorrelation(results_table1['P'],results_table1['P model']),4)
corcolor = ('red' if (cor<0.97) else 'black')
axes[2].text(0.9, 0.1, r'Product $r^2=$'+format(cor), fontsize=12,transform=axes[2].transAxes, horizontalalignment='right', color=corcolor)
initialsubstrate = "{0}".format(dataset1[1][0])
if 'title' in kwargs:
fig.suptitle(kwargs['title']+', S='+initialsubstrate+' - '+kwargs['expno'], fontsize=18)
else:
fig.suptitle(kwargs['expno']+', S='+initialsubstrate, fontsize=18)
fig.tight_layout()
if 'path' in kwargs:
plt.savefig(kwargs['path']+'_'+kwargs['expno']+'.png',dpi=100)
pass
# def plot_results(t,results,dataset1,results_table1, **kwargs):
def plot_results(t,results,dataset1, **kwargs):
biomass, substrate, product = results
fig = plt.figure(figsize=(10,8))
ax0 = plt.subplot2grid((3,3), (0,0), colspan=3, rowspan=2)
ax1 = plt.subplot2grid((3,3), (2,0))
ax2 = plt.subplot2grid((3,3), (2,1))
ax3 = plt.subplot2grid((3,3), (2,2))
# ax4 = plt.subplot2grid((4,3), (3,0))
# ax5 = plt.subplot2grid((4,3), (3,1))
# ax6 = plt.subplot2grid((4,3), (3,2))
ax0.plot(t, biomass, 'g-', label='X model')
ax0.plot(t, substrate, 'y-', label='S model')
ax0.plot(t, product, 'b-', label='P model')
ax0.plot(dataset1[3], dataset1[0], 'go', label='X data', markersize=8, alpha=0.8)
ax0.plot(dataset1[3], dataset1[1], 'ys', label='S data', markersize=8, alpha=0.8)
ax0.plot(dataset1[3], dataset1[2], 'b^', label='P data', markersize=8, alpha=0.8)
ax0.set_xlabel("hours")
ax0.set_ylabel("g/l")
ax0.grid(True)
ax0.legend(loc='best', fontsize=10)
# Small biomass plot
ax1.set_title("Biomass conc.", fontsize=10)
ax1.plot(dataset1[3], dataset1[0], 'go', label='Biomass data', markersize=3, alpha=0.8)
ax1.plot(t, biomass, 'g-', label='Biomass')
ax1.set_xlabel("hours", fontsize=10)
ax1.set_ylabel('g/l', fontsize=10)
miu_data = estiamte_miu(dataset1[3],dataset1[0])
miu_model= estiamte_miu(t,biomass)
ax2.set_title(r'$\mu/t$')
ax2.plot(dataset1[3], miu_data, ls=':',marker='o', color="purple", label='Mi data', markersize=3, alpha=0.8)
ax2.plot(t, miu_model, ls='-', color="purple", label='Mi model')
ax2.set_xlabel("hours", fontsize=10)
ax2.set_ylabel(r'$\mu$', fontsize=10)
ax3.set_title(r'$\mu/S$')
ax3.plot(dataset1[1], miu_data, ls=':',marker='o', color="purple", label='Mi data', markersize=3, alpha=0.8)
ax3.plot(substrate, miu_model, ls='-', color="purple", label='Mi model')
ax3.set_xlabel("Substrate g/L", fontsize=10)
ax3.set_ylabel(r'$\mu$', fontsize=10)
ax1.grid(True)
ax2.grid(True)
ax3.grid(True)
# correlation plots
# ax4.plot([0,results_table1['X'].max()],[0,results_table1['X'].max()], color = '0.75')
# ax4.plot(results_table1['X'],results_table1['X model'], "o")
# ax4.set_xlabel("measured")
# ax4.set_ylabel("modeled")
# # axes[0].set_title("Biomass")
# cor = round(mycorrelation(results_table1['X'],results_table1['X model']),4)
# corcolor = ('red' if (cor<0.97) else 'black')
# ax4.text(0.9, 0.1, r'Biomass $r^2=$'+format(cor), fontsize=12,transform=ax4.transAxes, horizontalalignment='right', color=corcolor)
# ax5.plot([0,results_table1['S'].max()],[0,results_table1['S'].max()], color = '0.75')
# ax5.plot(results_table1['S'],results_table1['S model'], "o")
# # axes[1].set_title("Substrate")
# cor = round(mycorrelation(results_table1['S'],results_table1['S model']),4)
# corcolor = ('red' if (cor<0.97) else 'black')
# ax5.text(0.9, 0.1, r'Substrate $r^2=$'+format(cor), fontsize=12,transform=ax5.transAxes, horizontalalignment='right', color=corcolor)
# ax6.plot([0,results_table1['P'].max()],[0,results_table1['P'].max()], color = '0.75')
# ax6.plot(results_table1['P'],results_table1['P model'], "o")
# # axes[2].set_title("Product")
# cor = round(mycorrelation(results_table1['P'],results_table1['P model']),4)
# corcolor = ('red' if (cor<0.97) else 'black')
# ax6.text(0.9, 0.1, r'Product $r^2=$'+format(cor), fontsize=12,transform=ax6.transAxes, horizontalalignment='right', color=corcolor)
initialsubstrate = "{0}".format(dataset1[1][0])
if 'title' in kwargs:
fig.suptitle(kwargs['title']+', S='+initialsubstrate+' - '+kwargs['expno'], fontsize=18)
else:
fig.suptitle(kwargs['expno']+', S='+initialsubstrate, fontsize=18)
fig.tight_layout()
if 'path' in kwargs:
plt.savefig(kwargs['path']+'plot_'+kwargs['expno']+'.png',dpi=100)
pass
def plot_results_print(t,results,dataset1, **kwargs):
biomass, substrate, product = results
# fig = plt.figure(figsize=(10,8))
fig, ax0 = plt.subplots(figsize=(10,8))
ax1 = ax0.twinx()
# ax0 = plt.subplot2grid((3,3), (0,0), colspan=3, rowspan=2)
# ax1 = plt.subplot2grid((3,3), (2,0))
# ax2 = plt.subplot2grid((3,3), (2,1))
# ax3 = plt.subplot2grid((3,3), (2,2))
ax0.set_ylim([0, dataset1[1][0]+5])
line_X, = ax1.plot(t, biomass, color='green', ls='--', lw=2, label='Biomass, model')
line_S, = ax0.plot(t, substrate, color='#a08500', ls='-.', lw=4, label='Substrate, model')
dashes = [3, 5, 3, 5] # 10 points on, 5 off, 10 on, 5 off
line_S.set_dashes(dashes)
line_P, = ax1.plot(t, product, color='blue', ls='-', lw=3, label='Ethanol, model')
line_Xm, = ax1.plot(dataset1[3], dataset1[0], color='green', ls='', marker='o', label='Biomass, experiment', markersize=10, alpha=0.8, markerfacecolor="white", markeredgewidth=2, markeredgecolor="green")
ax1.set_ylabel(r"Biomass, product concentration $(g/l)$", fontsize=18, color="green")
line_Sm, = ax0.plot(dataset1[3], dataset1[1], color='#a08500', ls='', marker='s', label='Substrate, experiment', markersize=10, alpha=0.8, markerfacecolor="white", markeredgewidth=2, markeredgecolor="#a08500")
line_Pm, = ax1.plot(dataset1[3], dataset1[2], color='blue', ls='', marker='^', label='Ethanol, experiment', markersize=10, alpha=0.8, markerfacecolor="white", markeredgewidth=2, markeredgecolor="blue")
ax0.set_ylabel(r"Substrate concentration $(g/l)$", fontsize=18)
ax0.set_xlabel("hours")
# ax0.set_ylabel("g/l")
ax0.grid(True)
# ax0.legend(loc='best', fontsize=10)
# ax0.legend(bbox_to_anchor=(0., 1.12, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.)
# ax1.legend(loc='best', fontsize=10)
# ax1.legend(bbox_to_anchor=(0., 1.12, 1., .205), loc=3, ncol=2, mode="expand", borderaxespad=0.)
# Create a legend for the first line.
legend1 = plt.legend(handles=[line_X, line_Xm, line_S, line_Sm, line_P, line_Pm], loc=0, fontsize=12, bbox_to_anchor=(0., 1.02, 1., .102), ncol=3)
# Add the legend manually to the current Axes.
# ax0 = plt.gca().add_artist(legend1)
# Create another legend for the second line.
# legend2 = plt.legend(handles=[line_S], loc=1)
# plt.legend(handles=[line_Sm], loc=0)
# ax0 = plt.gca().add_artist(legend2)
# legend3 = plt.legend(handles=[line_P], loc=0)
# # plt.legend(handles=[line_Sm], loc=0)
# ax0 = plt.gca().add_artist(legend3)
# ax0.grid(True)
# ax1.grid(True)
# initialsubstrate = "{0}".format(dataset1[1][0])
# if 'title' in kwargs:
# fig.suptitle(kwargs['title']+', S='+initialsubstrate+' - '+kwargs['expno'], fontsize=18)
# else:
# fig.suptitle(kwargs['expno']+', S='+initialsubstrate, fontsize=18)
# fig.tight_layout()
if 'path' in kwargs:
plt.savefig(kwargs['path']+'print_plot_'+kwargs['expno']+'.png',dpi=100)
pass
def plot_results4(t,results,dataset1,results_table1, **kwargs):
biomass, substrate, product1, product2 = results
fig = plt.figure(figsize=(10,10))
ax0 = plt.subplot2grid((4,3), (0,0), colspan=3, rowspan=2)
ax1 = plt.subplot2grid((4,3), (2,0))
ax2 = plt.subplot2grid((4,3), (2,1))
ax3 = plt.subplot2grid((4,3), (2,2))
ax4 = plt.subplot2grid((4,3), (3,0))
ax5 = plt.subplot2grid((4,3), (3,1))
ax6 = plt.subplot2grid((4,3), (3,2))
ax0.plot(t, biomass, 'g-', label='X model')
ax0.plot(t, substrate, 'y-', label='S model')
ax0.plot(t, product1, 'b-', label='P1 model')
ax0.plot(t, product2, 'r-', label='P2 model')
ax0.plot(dataset1[0], dataset1[1], 'go', label='X data', markersize=8, alpha=0.8)
ax0.plot(dataset1[0], dataset1[2], 'ys', label='S data', markersize=8, alpha=0.8)
ax0.plot(dataset1[0], dataset1[3], 'b^', label='P1 data', markersize=8, alpha=0.8)
ax0.plot(dataset1[0], dataset1[4], 'r^', label='P2 data', markersize=8, alpha=0.8)
ax0.set_xlabel("hours")
ax0.set_ylabel("g/l")
ax0.grid(True)
ax0.legend(loc='best', fontsize=10)
# Small biomass plot
ax1.set_title("Biomass conc.", fontsize=10)
ax1.plot(dataset1[0], dataset1[1], 'go', label='Biomass data', markersize=3, alpha=0.8)
ax1.plot(t, biomass, 'g-', label='Biomass')
ax1.set_xlabel("hours", fontsize=10)
ax1.set_ylabel('g/l', fontsize=10)
miu_data = estiamte_miu(dataset1[0],dataset1[1])
miu_model= estiamte_miu(t,biomass)
ax2.set_title(r'$\mu/t$')
ax2.plot(dataset1[0], miu_data, ls=':',marker='o', color="purple", label='Mi data', markersize=3, alpha=0.8)
ax2.plot(t, miu_model, ls='-', color="purple", label='Mi model')
ax2.set_xlabel("hours", fontsize=10)
ax2.set_ylabel(r'$\mu$', fontsize=10)
ax3.set_title(r'$\mu/S$')
ax3.plot(dataset1[2], miu_data, ls=':',marker='o', color="purple", label='Mi data', markersize=3, alpha=0.8)
ax3.plot(substrate, miu_model, ls='-', color="purple", label='Mi model')
ax3.set_xlabel("Substrate g/L", fontsize=10)
ax3.set_ylabel(r'$\mu$', fontsize=10)
ax1.grid(True)
# correlation plots
ax4.plot([0,results_table1['X'].max()],[0,results_table1['X'].max()], color = '0.75')
ax4.plot(results_table1['X'],results_table1['X model'], "o")
ax4.set_xlabel("measured")
ax4.set_ylabel("modeled")
# axes[0].set_title("Biomass")
cor = round(mycorrelation(results_table1['X'],results_table1['X model']),4)
corcolor = ('red' if (cor<0.97) else 'black')
ax4.text(0.9, 0.1, r'Biomass $r^2=$'+format(cor), fontsize=12,transform=ax4.transAxes, horizontalalignment='right', color=corcolor)
ax5.plot([0,results_table1['S'].max()],[0,results_table1['S'].max()], color = '0.75')
ax5.plot(results_table1['S'],results_table1['S model'], "o")
# axes[1].set_title("Substrate")
cor = round(mycorrelation(results_table1['S'],results_table1['S model']),4)
corcolor = ('red' if (cor<0.97) else 'black')
ax5.text(0.9, 0.1, r'Substrate $r^2=$'+format(cor), fontsize=12,transform=ax5.transAxes, horizontalalignment='right', color=corcolor)
ax6.plot([0,results_table1['P1'].max()],[0,results_table1['P1'].max()], color = '0.75')
ax6.plot(results_table1['P1'],results_table1['P1 model'], "o")
# axes[2].set_title("Product")
cor = round(mycorrelation(results_table1['P1'],results_table1['P1 model']),4)
corcolor = ('red' if (cor<0.97) else 'black')
ax6.text(0.9, 0.1, r'Product $r^2=$'+format(cor), fontsize=12,transform=ax6.transAxes, horizontalalignment='right', color=corcolor)
initialsubstrate = "{0}".format(dataset1[2][0])
if 'title' in kwargs:
fig.suptitle(kwargs['title']+', S='+initialsubstrate+' - '+kwargs['expno'], fontsize=18)
else:
fig.suptitle(kwargs['expno']+', S='+initialsubstrate, fontsize=18)
fig.tight_layout()
if 'path' in kwargs:
plt.savefig(kwargs['path']+'_'+kwargs['expno']+'.png',dpi=100)
pass
def plot_results4_print(t,results,dataset1,results_table1, **kwargs):
biomass, substrate, product1, product2 = results
initialsubstrate = "{0}".format(dataset1[2][0])
fig, ax0 = plt.subplots(figsize=(10,8))
ax0.plot(t, biomass, color='green', ls='--', lw=2, label='Biomass, model')
line, = ax0.plot(t, substrate, color='#a08500', ls='-.', lw=4, label='Substrate, model')
ax0.plot(t, product1, color='blue', ls='-', lw=3, label='Product1, model')
ax0.plot(t, product2, color='red', ls='-', lw=3, label='Product2, model')
dashes = [3, 5, 3, 5] # 10 points on, 5 off, 10 on, 5 off
line.set_dashes(dashes)
ax0.plot(dataset1[0], dataset1[1], color='green', ls='', marker='o', label='Biomass, experiment', markersize=10, alpha=0.8)
ax0.plot(dataset1[0], dataset1[2], color='#a08500', ls='', marker='s', label='Substrate, experiment', markersize=10, alpha=0.8)
ax0.plot(dataset1[0], dataset1[3], color='blue', ls='', marker='^', label='Product1, experiment', markersize=10, alpha=0.8)
ax0.plot(dataset1[0], dataset1[4], color='red', ls='', marker='^', label='Product2, experiment', markersize=10, alpha=0.8)
ax0.set_xlabel("hours")
ax0.set_ylabel("g/l")
# ax0.grid(True)
ax0.legend(loc='best', fontsize=14)
# ax0.set_ylim([0, 60])
ax0.set_ylim([0, dataset1[2][0]+5])
ax0.set_xlim([0, t[-1]+1])
if 'title' in kwargs:
pass
# fig.suptitle(kwargs['title']+', S='+initialsubstrate+' - '+kwargs['expno'], fontsize=18)
else:
pass
# fig.suptitle(kwargs['expno']+', S='+initialsubstrate, fontsize=18)
fig.tight_layout()
if 'path' in kwargs:
plt.savefig(kwargs['path']+'_'+kwargs['expno']+'.png',dpi=90)
plt.savefig(kwargs['path']+'_'+kwargs['expno']+'.pdf')
pass
|
unlicense
|
DSLituiev/scikit-learn
|
examples/linear_model/plot_sgd_loss_functions.py
|
73
|
1232
|
"""
==========================
SGD: convex loss functions
==========================
A plot that compares the various convex loss functions supported by
:class:`sklearn.linear_model.SGDClassifier` .
"""
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
def modified_huber_loss(y_true, y_pred):
z = y_pred * y_true
loss = -4 * z
loss[z >= -1] = (1 - z[z >= -1]) ** 2
loss[z >= 1.] = 0
return loss
xmin, xmax = -4, 4
xx = np.linspace(xmin, xmax, 100)
lw = 2
plt.plot([xmin, 0, 0, xmax], [1, 1, 0, 0], color='gold', lw=lw,
label="Zero-one loss")
plt.plot(xx, np.where(xx < 1, 1 - xx, 0), color='teal', lw=lw,
label="Hinge loss")
plt.plot(xx, -np.minimum(xx, 0), color='yellowgreen', lw=lw,
label="Perceptron loss")
plt.plot(xx, np.log2(1 + np.exp(-xx)), color='cornflowerblue', lw=lw,
label="Log loss")
plt.plot(xx, np.where(xx < 1, 1 - xx, 0) ** 2, color='orange', lw=lw,
label="Squared hinge loss")
plt.plot(xx, modified_huber_loss(xx, 1), color='darkorchid', lw=lw,
linestyle='--', label="Modified Huber loss")
plt.ylim((0, 8))
plt.legend(loc="upper right")
plt.xlabel(r"Decision function $f(x)$")
plt.ylabel("$L(y, f(x))$")
plt.show()
|
bsd-3-clause
|
johnmcdowall/procedural_city_generation
|
procedural_city_generation/building_generation/getFoundation.py
|
3
|
2136
|
import numpy as np
from procedural_city_generation.polygons.Polygon2D import Polygon2D, Edge
def getFoundation(poly, grid_width=0.01, eps=10**-8):
rect_area = 0
rect_height = 0
rect_x = [0,0]
rect_base = None
#Iterate through edges which are bordering a road, find largest
#rectangle for each one
for base in sorted([edge for edge in poly.edges if edge.bordering_road],
key=lambda x: -x.length):
#Initialize height
height = grid_width
done = False
while not done:
cuts = []
for other in poly.edges:
#Find all intersections
if other is not base:
x = [0,0]
try:
x = np.linalg.solve(np.array(((base.dir_vector), (-other.dir_vector))).T,
other[0] - (base[0] + base.n * height))
except np.linalg.LinAlgError:
pass
if eps < x[1] < 1 - eps:
#intersection found
if x[0] < eps:
cuts.append(0)
elif x[0] > 1 - eps:
cuts.append(1)
else:
cuts.append(x[0])
if len(cuts) == 2:
#Possible rectangle found
width = abs(base.length*cuts[1] - base.length*cuts[0])
this_area = width * height
if this_area > rect_area:
rect_area = this_area
rect_height = height
rect_x = cuts
rect_base = base
height += grid_width
else:
done = True
break
if rect_height:
p1 = rect_base[0] + rect_x[1] * rect_base.dir_vector
p2 = rect_base[0] + rect_x[0] * rect_base.dir_vector
p3 = p2 + rect_height * rect_base.n
p4 = p1 + rect_height * rect_base.n
return Polygon2D([p1,p2,p3,p4])
else:
#TODO: assign issue to lenny ... why return false
return False
if __name__=="__main__":
import matplotlib.pyplot as plt
from plot_poly import plot_poly
from getBlock import getBlock
from getLots import getLots
import construct_polygons as cp
polys, vertices = cp.main()
lots = getLots(polys[:20], vertices)
for poly in lots:
if poly.poly_type == "lot":
f = getFoundation(poly)
if f:
plot_poly(poly, mode="k")
plot_poly(f, mode="g")
else:
plot_poly(poly, mode="r")
plt.show()
|
mpl-2.0
|
rabipanda/tensorflow
|
tensorflow/contrib/learn/python/learn/estimators/estimator.py
|
2
|
61411
|
# 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.
# ==============================================================================
"""Base Estimator class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import collections
import copy
import os
import tempfile
import numpy as np
import six
from google.protobuf import message
from tensorflow.contrib import layers
from tensorflow.contrib.framework import deprecated
from tensorflow.contrib.framework import deprecated_args
from tensorflow.contrib.framework import list_variables
from tensorflow.contrib.framework import load_variable
from tensorflow.contrib.learn.python.learn import evaluable
from tensorflow.contrib.learn.python.learn import metric_spec
from tensorflow.contrib.learn.python.learn import monitors as monitor_lib
from tensorflow.contrib.learn.python.learn import trainable
from tensorflow.contrib.learn.python.learn.estimators import _sklearn as sklearn
from tensorflow.contrib.learn.python.learn.estimators import constants
from tensorflow.contrib.learn.python.learn.estimators import metric_key
from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib
from tensorflow.contrib.learn.python.learn.estimators import run_config
from tensorflow.contrib.learn.python.learn.estimators import tensor_signature
from tensorflow.contrib.learn.python.learn.estimators._sklearn import NotFittedError
from tensorflow.contrib.learn.python.learn.learn_io import data_feeder
from tensorflow.contrib.learn.python.learn.utils import export
from tensorflow.contrib.learn.python.learn.utils import saved_model_export_utils
from tensorflow.contrib.meta_graph_transform import meta_graph_transform
from tensorflow.contrib.training.python.training import evaluation
from tensorflow.core.framework import summary_pb2
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.client import session as tf_session
from tensorflow.python.framework import ops
from tensorflow.python.framework import random_seed
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import lookup_ops
from tensorflow.python.ops import metrics as metrics_lib
from tensorflow.python.ops import resources
from tensorflow.python.ops import variables
from tensorflow.python.platform import gfile
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.saved_model import builder as saved_model_builder
from tensorflow.python.saved_model import tag_constants
from tensorflow.python.summary import summary as core_summary
from tensorflow.python.training import basic_session_run_hooks
from tensorflow.python.training import device_setter
from tensorflow.python.training import monitored_session
from tensorflow.python.training import saver
from tensorflow.python.training import training_util
from tensorflow.python.util import compat
from tensorflow.python.util import tf_decorator
from tensorflow.python.util import tf_inspect
AS_ITERABLE_DATE = '2016-09-15'
AS_ITERABLE_INSTRUCTIONS = (
'The default behavior of predict() is changing. The default value for\n'
'as_iterable will change to True, and then the flag will be removed\n'
'altogether. The behavior of this flag is described below.')
SCIKIT_DECOUPLE_DATE = '2016-12-01'
SCIKIT_DECOUPLE_INSTRUCTIONS = (
'Estimator is decoupled from Scikit Learn interface by moving into\n'
'separate class SKCompat. Arguments x, y and batch_size are only\n'
'available in the SKCompat class, Estimator will only accept input_fn.\n'
'Example conversion:\n'
' est = Estimator(...) -> est = SKCompat(Estimator(...))')
def _verify_input_args(x, y, input_fn, feed_fn, batch_size):
"""Verifies validity of co-existence of input arguments."""
if input_fn is None:
if x is None:
raise ValueError('Either x or input_fn must be provided.')
if tensor_util.is_tensor(x) or y is not None and tensor_util.is_tensor(y):
raise ValueError('Inputs cannot be tensors. Please provide input_fn.')
if feed_fn is not None:
raise ValueError('Can not provide both feed_fn and x or y.')
else:
if (x is not None) or (y is not None):
raise ValueError('Can not provide both input_fn and x or y.')
if batch_size is not None:
raise ValueError('Can not provide both input_fn and batch_size.')
def _get_input_fn(x, y, input_fn, feed_fn, batch_size, shuffle=False, epochs=1):
"""Make inputs into input and feed functions.
Args:
x: Numpy, Pandas or Dask matrix or iterable.
y: Numpy, Pandas or Dask matrix or iterable.
input_fn: Pre-defined input function for training data.
feed_fn: Pre-defined data feeder function.
batch_size: Size to split data into parts. Must be >= 1.
shuffle: Whether to shuffle the inputs.
epochs: Number of epochs to run.
Returns:
Data input and feeder function based on training data.
Raises:
ValueError: Only one of `(x & y)` or `input_fn` must be provided.
"""
_verify_input_args(x, y, input_fn, feed_fn, batch_size)
if input_fn is not None:
return input_fn, feed_fn
df = data_feeder.setup_train_data_feeder(
x,
y,
n_classes=None,
batch_size=batch_size,
shuffle=shuffle,
epochs=epochs)
return df.input_builder, df.get_feed_dict_fn()
def infer_real_valued_columns_from_input_fn(input_fn):
"""Creates `FeatureColumn` objects for inputs defined by `input_fn`.
This interprets all inputs as dense, fixed-length float values. This creates
a local graph in which it calls `input_fn` to build the tensors, then discards
it.
Args:
input_fn: Input function returning a tuple of:
features - Dictionary of string feature name to `Tensor` or `Tensor`.
labels - `Tensor` of label values.
Returns:
List of `FeatureColumn` objects.
"""
with ops.Graph().as_default():
features, _ = input_fn()
return layers.infer_real_valued_columns(features)
def infer_real_valued_columns_from_input(x):
"""Creates `FeatureColumn` objects for inputs defined by input `x`.
This interprets all inputs as dense, fixed-length float values.
Args:
x: Real-valued matrix of shape [n_samples, n_features...]. Can be
iterator that returns arrays of features.
Returns:
List of `FeatureColumn` objects.
"""
input_fn, _ = _get_input_fn(
x=x, y=None, input_fn=None, feed_fn=None, batch_size=None)
return infer_real_valued_columns_from_input_fn(input_fn)
def _model_fn_args(fn):
"""Get argument names for function-like object.
Args:
fn: Function, or function-like object (e.g., result of `functools.partial`).
Returns:
`tuple` of string argument names.
Raises:
ValueError: if partial function has positionally bound arguments
"""
_, fn = tf_decorator.unwrap(fn)
if hasattr(fn, 'func') and hasattr(fn, 'keywords') and hasattr(fn, 'args'):
# Handle functools.partial and similar objects.
return tuple([
arg for arg in tf_inspect.getargspec(fn.func).args[len(fn.args):]
if arg not in set(fn.keywords.keys())
])
# Handle function.
return tuple(tf_inspect.getargspec(fn).args)
def _get_replica_device_setter(config):
"""Creates a replica device setter if required.
Args:
config: A RunConfig instance.
Returns:
A replica device setter, or None.
"""
ps_ops = [
'Variable', 'VariableV2', 'AutoReloadVariable', 'MutableHashTable',
'MutableHashTableV2', 'MutableHashTableOfTensors',
'MutableHashTableOfTensorsV2', 'MutableDenseHashTable',
'MutableDenseHashTableV2'
]
if config.task_type:
worker_device = '/job:%s/task:%d' % (config.task_type, config.task_id)
else:
worker_device = '/job:worker'
if config.num_ps_replicas > 0:
return device_setter.replica_device_setter(
ps_tasks=config.num_ps_replicas,
worker_device=worker_device,
merge_devices=True,
ps_ops=ps_ops,
cluster=config.cluster_spec)
else:
return None
def _make_metrics_ops(metrics, features, labels, predictions):
"""Add metrics based on `features`, `labels`, and `predictions`.
`metrics` contains a specification for how to run metrics. It is a dict
mapping friendly names to either `MetricSpec` objects, or directly to a metric
function (assuming that `predictions` and `labels` are single tensors), or to
`(pred_name, metric)` `tuple`, which passes `predictions[pred_name]` and
`labels` to `metric` (assuming `labels` is a single tensor).
Users are encouraged to use `MetricSpec` objects, which are more flexible and
cleaner. They also lead to clearer errors.
Args:
metrics: A dict mapping names to metrics specification, for example
`MetricSpec` objects.
features: A dict of tensors returned from an input_fn as features/inputs.
labels: A single tensor or a dict of tensors returned from an input_fn as
labels.
predictions: A single tensor or a dict of tensors output from a model as
predictions.
Returns:
A dict mapping the friendly given in `metrics` to the result of calling the
given metric function.
Raises:
ValueError: If metrics specifications do not work with the type of
`features`, `labels`, or `predictions` provided. Mostly, a dict is given
but no pred_name specified.
"""
metrics = metrics or {}
# If labels is a dict with a single key, unpack into a single tensor.
labels_tensor_or_dict = labels
if isinstance(labels, dict) and len(labels) == 1:
labels_tensor_or_dict = labels[list(labels.keys())[0]]
result = {}
# Iterate in lexicographic order, so the graph is identical among runs.
for name, metric in sorted(six.iteritems(metrics)):
if isinstance(metric, metric_spec.MetricSpec):
result[name] = metric.create_metric_ops(features, labels, predictions)
continue
# TODO(b/31229024): Remove the rest of this loop
logging.warning('Please specify metrics using MetricSpec. Using bare '
'functions or (key, fn) tuples is deprecated and support '
'for it will be removed on Oct 1, 2016.')
if isinstance(name, tuple):
# Multi-head metrics.
if len(name) != 2:
raise ValueError('Invalid metric for {}. It returned a tuple with '
'len {}, expected 2.'.format(name, len(name)))
if not isinstance(predictions, dict):
raise ValueError('Metrics passed provide (name, prediction), '
'but predictions are not dict. '
'Metrics: %s, Predictions: %s.' % (metrics,
predictions))
# Here are two options: labels are single Tensor or a dict.
if isinstance(labels, dict) and name[1] in labels:
# If labels are dict and the prediction name is in it, apply metric.
result[name[0]] = metric(predictions[name[1]], labels[name[1]])
else:
# Otherwise pass the labels to the metric.
result[name[0]] = metric(predictions[name[1]], labels_tensor_or_dict)
else:
# Single head metrics.
if isinstance(predictions, dict):
raise ValueError('Metrics passed provide only name, no prediction, '
'but predictions are dict. '
'Metrics: %s, Labels: %s.' % (metrics,
labels_tensor_or_dict))
result[name] = metric(predictions, labels_tensor_or_dict)
return result
def _dict_to_str(dictionary):
"""Get a `str` representation of a `dict`.
Args:
dictionary: The `dict` to be represented as `str`.
Returns:
A `str` representing the `dictionary`.
"""
results = []
for k, v in sorted(dictionary.items()):
if isinstance(v, float) or isinstance(v, np.float32) or isinstance(
v, int) or isinstance(v, np.int64) or isinstance(v, np.int32):
results.append('%s = %s' % (k, v))
else:
results.append('Type of %s = %s' % (k, type(v)))
return ', '.join(results)
def _write_dict_to_summary(output_dir, dictionary, current_global_step):
"""Writes a `dict` into summary file in given output directory.
Args:
output_dir: `str`, directory to write the summary file in.
dictionary: the `dict` to be written to summary file.
current_global_step: `int`, the current global step.
"""
logging.info('Saving dict for global step %d: %s', current_global_step,
_dict_to_str(dictionary))
summary_writer = core_summary.FileWriterCache.get(output_dir)
summary_proto = summary_pb2.Summary()
for key in dictionary:
if dictionary[key] is None:
continue
if key == 'global_step':
continue
if (isinstance(dictionary[key], np.float32) or
isinstance(dictionary[key], float)):
summary_proto.value.add(tag=key, simple_value=float(dictionary[key]))
elif (isinstance(dictionary[key], np.int64) or
isinstance(dictionary[key], np.int32) or
isinstance(dictionary[key], int)):
summary_proto.value.add(tag=key, simple_value=int(dictionary[key]))
elif isinstance(dictionary[key], six.string_types):
try:
summ = summary_pb2.Summary.FromString(dictionary[key])
for i, _ in enumerate(summ.value):
summ.value[i].tag = key
summary_proto.value.extend(summ.value)
except message.DecodeError:
logging.warn('Skipping summary for %s, cannot parse string to Summary.',
key)
continue
elif isinstance(dictionary[key], np.ndarray):
value = summary_proto.value.add()
value.tag = key
value.node_name = key
tensor_proto = tensor_util.make_tensor_proto(dictionary[key])
value.tensor.CopyFrom(tensor_proto)
logging.info(
'Summary for np.ndarray is not visible in Tensorboard by default. '
'Consider using a Tensorboard plugin for visualization (see '
'https://github.com/tensorflow/tensorboard-plugin-example/blob/master/README.md'
' for more information).')
else:
logging.warn(
'Skipping summary for %s, must be a float, np.float32, np.int64, '
'np.int32 or int or np.ndarray or a serialized string of Summary.',
key)
summary_writer.add_summary(summary_proto, current_global_step)
summary_writer.flush()
GraphRewriteSpec = collections.namedtuple('GraphRewriteSpec',
['tags', 'transforms'])
class BaseEstimator(sklearn.BaseEstimator, evaluable.Evaluable,
trainable.Trainable):
"""Abstract BaseEstimator class to train and evaluate TensorFlow models.
Users should not instantiate or subclass this class. Instead, use an
`Estimator`.
"""
__metaclass__ = abc.ABCMeta
# Note that for Google users, this is overridden with
# learn_runner.EstimatorConfig.
# TODO(wicke): Remove this once launcher takes over config functionality
_Config = run_config.RunConfig # pylint: disable=invalid-name
def __init__(self, model_dir=None, config=None):
"""Initializes a BaseEstimator instance.
Args:
model_dir: Directory to save model parameters, graph and etc. This can
also be used to load checkpoints from the directory into a estimator to
continue training a previously saved model. If `None`, the model_dir in
`config` will be used if set. If both are set, they must be same.
config: A RunConfig instance.
"""
# Create a run configuration.
if config is None:
self._config = BaseEstimator._Config()
logging.info('Using default config.')
else:
self._config = config
if self._config.session_config is None:
self._session_config = config_pb2.ConfigProto(allow_soft_placement=True)
else:
self._session_config = self._config.session_config
# Model directory.
if (model_dir is not None) and (self._config.model_dir is not None):
if model_dir != self._config.model_dir:
# TODO(b/9965722): remove this suppression after it is no longer
# necessary.
# pylint: disable=g-doc-exception
raise ValueError(
'model_dir are set both in constructor and RunConfig, but with '
"different values. In constructor: '{}', in RunConfig: "
"'{}' ".format(model_dir, self._config.model_dir))
# pylint: enable=g-doc-exception
self._model_dir = model_dir or self._config.model_dir
if self._model_dir is None:
self._model_dir = tempfile.mkdtemp()
logging.warning('Using temporary folder as model directory: %s',
self._model_dir)
if self._config.model_dir is None:
self._config = self._config.replace(model_dir=self._model_dir)
logging.info('Using config: %s', str(vars(self._config)))
# Set device function depending if there are replicas or not.
self._device_fn = _get_replica_device_setter(self._config)
# Features and labels TensorSignature objects.
# TODO(wicke): Rename these to something more descriptive
self._features_info = None
self._labels_info = None
self._graph = None
@property
def config(self):
# TODO(wicke): make RunConfig immutable, and then return it without a copy.
return copy.deepcopy(self._config)
@deprecated_args(SCIKIT_DECOUPLE_DATE, SCIKIT_DECOUPLE_INSTRUCTIONS,
('x', None), ('y', None), ('batch_size', None))
def fit(self,
x=None,
y=None,
input_fn=None,
steps=None,
batch_size=None,
monitors=None,
max_steps=None):
# pylint: disable=g-doc-args,g-doc-return-or-yield
"""See `Trainable`.
Raises:
ValueError: If `x` or `y` are not `None` while `input_fn` is not `None`.
ValueError: If both `steps` and `max_steps` are not `None`.
"""
if (steps is not None) and (max_steps is not None):
raise ValueError('Can not provide both steps and max_steps.')
_verify_input_args(x, y, input_fn, None, batch_size)
if x is not None:
SKCompat(self).fit(x, y, batch_size, steps, max_steps, monitors)
return self
if max_steps is not None:
try:
start_step = load_variable(self._model_dir, ops.GraphKeys.GLOBAL_STEP)
if max_steps <= start_step:
logging.info('Skipping training since max_steps has already saved.')
return self
except: # pylint: disable=bare-except
pass
hooks = monitor_lib.replace_monitors_with_hooks(monitors, self)
if steps is not None or max_steps is not None:
hooks.append(basic_session_run_hooks.StopAtStepHook(steps, max_steps))
loss = self._train_model(input_fn=input_fn, hooks=hooks)
logging.info('Loss for final step: %s.', loss)
return self
@deprecated_args(SCIKIT_DECOUPLE_DATE, SCIKIT_DECOUPLE_INSTRUCTIONS,
('x', None), ('y', None), ('batch_size', None))
def partial_fit(self,
x=None,
y=None,
input_fn=None,
steps=1,
batch_size=None,
monitors=None):
"""Incremental fit on a batch of samples.
This method is expected to be called several times consecutively
on different or the same chunks of the dataset. This either can
implement iterative training or out-of-core/online training.
This is especially useful when the whole dataset is too big to
fit in memory at the same time. Or when model is taking long time
to converge, and you want to split up training into subparts.
Args:
x: Matrix of shape [n_samples, n_features...]. Can be iterator that
returns arrays of features. The training input samples for fitting the
model. If set, `input_fn` must be `None`.
y: Vector or matrix [n_samples] or [n_samples, n_outputs]. Can be
iterator that returns array of labels. The training label values
(class labels in classification, real numbers in regression). If set,
`input_fn` must be `None`.
input_fn: Input function. If set, `x`, `y`, and `batch_size` must be
`None`.
steps: Number of steps for which to train model. If `None`, train forever.
batch_size: minibatch size to use on the input, defaults to first
dimension of `x`. Must be `None` if `input_fn` is provided.
monitors: List of `BaseMonitor` subclass instances. Used for callbacks
inside the training loop.
Returns:
`self`, for chaining.
Raises:
ValueError: If at least one of `x` and `y` is provided, and `input_fn` is
provided.
"""
logging.warning('The current implementation of partial_fit is not optimized'
' for use in a loop. Consider using fit() instead.')
return self.fit(
x=x,
y=y,
input_fn=input_fn,
steps=steps,
batch_size=batch_size,
monitors=monitors)
@deprecated_args(SCIKIT_DECOUPLE_DATE, SCIKIT_DECOUPLE_INSTRUCTIONS,
('x', None), ('y', None), ('batch_size', None))
def evaluate(self,
x=None,
y=None,
input_fn=None,
feed_fn=None,
batch_size=None,
steps=None,
metrics=None,
name=None,
checkpoint_path=None,
hooks=None,
log_progress=True):
# pylint: disable=g-doc-args,g-doc-return-or-yield
"""See `Evaluable`.
Raises:
ValueError: If at least one of `x` or `y` is provided, and at least one of
`input_fn` or `feed_fn` is provided.
Or if `metrics` is not `None` or `dict`.
"""
_verify_input_args(x, y, input_fn, feed_fn, batch_size)
if x is not None:
return SKCompat(self).score(x, y, batch_size, steps, metrics, name)
if metrics is not None and not isinstance(metrics, dict):
raise ValueError('Metrics argument should be None or dict. '
'Got %s.' % metrics)
eval_results, global_step = self._evaluate_model(
input_fn=input_fn,
feed_fn=feed_fn,
steps=steps,
metrics=metrics,
name=name,
checkpoint_path=checkpoint_path,
hooks=hooks,
log_progress=log_progress)
if eval_results is not None:
eval_results.update({'global_step': global_step})
return eval_results
@deprecated_args(SCIKIT_DECOUPLE_DATE, SCIKIT_DECOUPLE_INSTRUCTIONS,
('x', None), ('batch_size', None), ('as_iterable', True))
def predict(self,
x=None,
input_fn=None,
batch_size=None,
outputs=None,
as_iterable=True,
iterate_batches=False):
"""Returns predictions for given features.
Args:
x: Matrix of shape [n_samples, n_features...]. Can be iterator that
returns arrays of features. The training input samples for fitting the
model. If set, `input_fn` must be `None`.
input_fn: Input function. If set, `x` and 'batch_size' must be `None`.
batch_size: Override default batch size. If set, 'input_fn' must be
'None'.
outputs: list of `str`, name of the output to predict.
If `None`, returns all.
as_iterable: If True, return an iterable which keeps yielding predictions
for each example until inputs are exhausted. Note: The inputs must
terminate if you want the iterable to terminate (e.g. be sure to pass
num_epochs=1 if you are using something like read_batch_features).
iterate_batches: If True, yield the whole batch at once instead of
decomposing the batch into individual samples. Only relevant when
as_iterable is True.
Returns:
A numpy array of predicted classes or regression values if the
constructor's `model_fn` returns a `Tensor` for `predictions` or a `dict`
of numpy arrays if `model_fn` returns a `dict`. Returns an iterable of
predictions if as_iterable is True.
Raises:
ValueError: If x and input_fn are both provided or both `None`.
"""
_verify_input_args(x, None, input_fn, None, batch_size)
if x is not None and not as_iterable:
return SKCompat(self).predict(x, batch_size)
input_fn, feed_fn = _get_input_fn(x, None, input_fn, None, batch_size)
return self._infer_model(
input_fn=input_fn,
feed_fn=feed_fn,
outputs=outputs,
as_iterable=as_iterable,
iterate_batches=iterate_batches)
def get_variable_value(self, name):
"""Returns value of the variable given by name.
Args:
name: string, name of the tensor.
Returns:
Numpy array - value of the tensor.
"""
return load_variable(self.model_dir, name)
def get_variable_names(self):
"""Returns list of all variable names in this model.
Returns:
List of names.
"""
return [name for name, _ in list_variables(self.model_dir)]
@property
def model_dir(self):
return self._model_dir
@deprecated('2017-03-25', 'Please use Estimator.export_savedmodel() instead.')
def export(
self,
export_dir,
input_fn=export._default_input_fn, # pylint: disable=protected-access
input_feature_key=None,
use_deprecated_input_fn=True,
signature_fn=None,
prediction_key=None,
default_batch_size=1,
exports_to_keep=None,
checkpoint_path=None):
"""Exports inference graph into given dir.
Args:
export_dir: A string containing a directory to write the exported graph
and checkpoints.
input_fn: If `use_deprecated_input_fn` is true, then a function that given
`Tensor` of `Example` strings, parses it into features that are then
passed to the model. Otherwise, a function that takes no argument and
returns a tuple of (features, labels), where features is a dict of
string key to `Tensor` and labels is a `Tensor` that's currently not
used (and so can be `None`).
input_feature_key: Only used if `use_deprecated_input_fn` is false. String
key into the features dict returned by `input_fn` that corresponds to a
the raw `Example` strings `Tensor` that the exported model will take as
input. Can only be `None` if you're using a custom `signature_fn` that
does not use the first arg (examples).
use_deprecated_input_fn: Determines the signature format of `input_fn`.
signature_fn: Function that returns a default signature and a named
signature map, given `Tensor` of `Example` strings, `dict` of `Tensor`s
for features and `Tensor` or `dict` of `Tensor`s for predictions.
prediction_key: The key for a tensor in the `predictions` dict (output
from the `model_fn`) to use as the `predictions` input to the
`signature_fn`. Optional. If `None`, predictions will pass to
`signature_fn` without filtering.
default_batch_size: Default batch size of the `Example` placeholder.
exports_to_keep: Number of exports to keep.
checkpoint_path: the checkpoint path of the model to be exported. If it is
`None` (which is default), will use the latest checkpoint in
export_dir.
Returns:
The string path to the exported directory. NB: this functionality was
added ca. 2016/09/25; clients that depend on the return value may need
to handle the case where this function returns None because subclasses
are not returning a value.
"""
# pylint: disable=protected-access
return export._export_estimator(
estimator=self,
export_dir=export_dir,
signature_fn=signature_fn,
prediction_key=prediction_key,
input_fn=input_fn,
input_feature_key=input_feature_key,
use_deprecated_input_fn=use_deprecated_input_fn,
default_batch_size=default_batch_size,
exports_to_keep=exports_to_keep,
checkpoint_path=checkpoint_path)
@abc.abstractproperty
def _get_train_ops(self, features, labels):
"""Method that builds model graph and returns trainer ops.
Expected to be overridden by sub-classes that require custom support.
Args:
features: `Tensor` or `dict` of `Tensor` objects.
labels: `Tensor` or `dict` of `Tensor` objects.
Returns:
A `ModelFnOps` object.
"""
pass
@abc.abstractproperty
def _get_predict_ops(self, features):
"""Method that builds model graph and returns prediction ops.
Args:
features: `Tensor` or `dict` of `Tensor` objects.
Returns:
A `ModelFnOps` object.
"""
pass
def _get_eval_ops(self, features, labels, metrics):
"""Method that builds model graph and returns evaluation ops.
Expected to be overridden by sub-classes that require custom support.
Args:
features: `Tensor` or `dict` of `Tensor` objects.
labels: `Tensor` or `dict` of `Tensor` objects.
metrics: Dict of metrics to run. If None, the default metric functions
are used; if {}, no metrics are used. Otherwise, `metrics` should map
friendly names for the metric to a `MetricSpec` object defining which
model outputs to evaluate against which labels with which metric
function. Metric ops should support streaming, e.g., returning
update_op and value tensors. See more details in
`../../../../metrics/python/metrics/ops/streaming_metrics.py` and
`../metric_spec.py`.
Returns:
A `ModelFnOps` object.
"""
raise NotImplementedError('_get_eval_ops not implemented in BaseEstimator')
@deprecated(
'2016-09-23',
'The signature of the input_fn accepted by export is changing to be '
'consistent with what\'s used by tf.Learn Estimator\'s train/evaluate, '
'which makes this function useless. This will be removed after the '
'deprecation date.')
def _get_feature_ops_from_example(self, examples_batch):
"""Returns feature parser for given example batch using features info.
This function requires `fit()` has been called.
Args:
examples_batch: batch of tf.Example
Returns:
features: `Tensor` or `dict` of `Tensor` objects.
Raises:
ValueError: If `_features_info` attribute is not available (usually
because `fit()` has not been called).
"""
if self._features_info is None:
raise ValueError('Features information missing, was fit() ever called?')
return tensor_signature.create_example_parser_from_signatures(
self._features_info, examples_batch)
def _check_inputs(self, features, labels):
if self._features_info is not None:
logging.debug('Given features: %s, required signatures: %s.',
str(features), str(self._features_info))
if not tensor_signature.tensors_compatible(features, self._features_info):
raise ValueError('Features are incompatible with given information. '
'Given features: %s, required signatures: %s.' %
(str(features), str(self._features_info)))
else:
self._features_info = tensor_signature.create_signatures(features)
logging.debug('Setting feature info to %s.', str(self._features_info))
if labels is not None:
if self._labels_info is not None:
logging.debug('Given labels: %s, required signatures: %s.', str(labels),
str(self._labels_info))
if not tensor_signature.tensors_compatible(labels, self._labels_info):
raise ValueError('Labels are incompatible with given information. '
'Given labels: %s, required signatures: %s.' %
(str(labels), str(self._labels_info)))
else:
self._labels_info = tensor_signature.create_signatures(labels)
logging.debug('Setting labels info to %s', str(self._labels_info))
def _extract_metric_update_ops(self, eval_dict):
"""Separate update operations from metric value operations."""
update_ops = []
value_ops = {}
for name, metric_ops in six.iteritems(eval_dict):
if isinstance(metric_ops, (list, tuple)):
if len(metric_ops) == 2:
value_ops[name] = metric_ops[0]
update_ops.append(metric_ops[1])
else:
logging.warning(
'Ignoring metric {}. It returned a list|tuple with len {}, '
'expected 2'.format(name, len(metric_ops)))
value_ops[name] = metric_ops
else:
value_ops[name] = metric_ops
if update_ops:
update_ops = control_flow_ops.group(*update_ops)
else:
update_ops = None
return update_ops, value_ops
def _evaluate_model(self,
input_fn,
steps,
feed_fn=None,
metrics=None,
name='',
checkpoint_path=None,
hooks=None,
log_progress=True):
# TODO(wicke): Remove this once Model and associated code are gone.
if (hasattr(self._config, 'execution_mode') and
self._config.execution_mode not in ('all', 'evaluate', 'eval_evalset')):
return None, None
# Check that model has been trained (if nothing has been set explicitly).
if not checkpoint_path:
latest_path = saver.latest_checkpoint(self._model_dir)
if not latest_path:
raise NotFittedError(
"Couldn't find trained model at %s." % self._model_dir)
checkpoint_path = latest_path
# Setup output directory.
eval_dir = os.path.join(self._model_dir, 'eval'
if not name else 'eval_' + name)
with ops.Graph().as_default() as g:
random_seed.set_random_seed(self._config.tf_random_seed)
global_step = training_util.create_global_step(g)
features, labels = input_fn()
self._check_inputs(features, labels)
model_fn_results = self._get_eval_ops(features, labels, metrics)
eval_dict = model_fn_results.eval_metric_ops
update_op, eval_dict = self._extract_metric_update_ops(eval_dict)
# We need to copy the hook array as we modify it, thus [:].
hooks = hooks[:] if hooks else []
if feed_fn:
hooks.append(basic_session_run_hooks.FeedFnHook(feed_fn))
if steps == 0:
logging.warning('evaluation steps are 0. If `input_fn` does not raise'
'OutOfRangeError`, the evaluation will never stop.'
'Use steps=None if intended.')
if steps:
hooks.append(
evaluation.StopAfterNEvalsHook(steps, log_progress=log_progress))
global_step_key = 'global_step'
while global_step_key in eval_dict:
global_step_key = '_' + global_step_key
eval_dict[global_step_key] = global_step
eval_results = evaluation.evaluate_once(
checkpoint_path=checkpoint_path,
master=self._config.evaluation_master,
scaffold=model_fn_results.scaffold,
eval_ops=update_op,
final_ops=eval_dict,
hooks=hooks,
config=self._session_config)
current_global_step = eval_results[global_step_key]
_write_dict_to_summary(eval_dir, eval_results, current_global_step)
return eval_results, current_global_step
def _get_features_from_input_fn(self, input_fn):
result = input_fn()
if isinstance(result, (list, tuple)):
return result[0]
return result
def _infer_model(self,
input_fn,
feed_fn=None,
outputs=None,
as_iterable=True,
iterate_batches=False):
# Check that model has been trained.
checkpoint_path = saver.latest_checkpoint(self._model_dir)
if not checkpoint_path:
raise NotFittedError(
"Couldn't find trained model at %s." % self._model_dir)
with ops.Graph().as_default() as g:
random_seed.set_random_seed(self._config.tf_random_seed)
training_util.create_global_step(g)
features = self._get_features_from_input_fn(input_fn)
infer_ops = self._get_predict_ops(features)
predictions = self._filter_predictions(infer_ops.predictions, outputs)
mon_sess = monitored_session.MonitoredSession(
session_creator=monitored_session.ChiefSessionCreator(
checkpoint_filename_with_path=checkpoint_path,
scaffold=infer_ops.scaffold,
config=self._session_config))
if not as_iterable:
with mon_sess:
if not mon_sess.should_stop():
return mon_sess.run(predictions, feed_fn() if feed_fn else None)
else:
return self._predict_generator(mon_sess, predictions, feed_fn,
iterate_batches)
def _predict_generator(self, mon_sess, predictions, feed_fn, iterate_batches):
with mon_sess:
while not mon_sess.should_stop():
preds = mon_sess.run(predictions, feed_fn() if feed_fn else None)
if iterate_batches:
yield preds
elif not isinstance(predictions, dict):
for pred in preds:
yield pred
else:
first_tensor = list(preds.values())[0]
if isinstance(first_tensor, sparse_tensor.SparseTensorValue):
batch_length = first_tensor.dense_shape[0]
else:
batch_length = first_tensor.shape[0]
for i in range(batch_length):
yield {key: value[i] for key, value in six.iteritems(preds)}
if self._is_input_constant(feed_fn, mon_sess.graph):
return
def _is_input_constant(self, feed_fn, graph):
# If there are no queue_runners, the input `predictions` is a
# constant, and we should stop after the first epoch. If,
# instead, there are queue_runners, eventually they should throw
# an `OutOfRangeError`.
if graph.get_collection(ops.GraphKeys.QUEUE_RUNNERS):
return False
# data_feeder uses feed_fn to generate `OutOfRangeError`.
if feed_fn is not None:
return False
return True
def _filter_predictions(self, predictions, outputs):
if not outputs:
return predictions
if not isinstance(predictions, dict):
raise ValueError(
'outputs argument is not valid in case of non-dict predictions.')
existing_keys = predictions.keys()
predictions = {
key: value
for key, value in six.iteritems(predictions)
if key in outputs
}
if not predictions:
raise ValueError('Expected to run at least one output from %s, '
'provided %s.' % (existing_keys, outputs))
return predictions
def _train_model(self, input_fn, hooks):
all_hooks = []
self._graph = ops.Graph()
with self._graph.as_default() as g, g.device(self._device_fn):
random_seed.set_random_seed(self._config.tf_random_seed)
global_step = training_util.create_global_step(g)
features, labels = input_fn()
self._check_inputs(features, labels)
training_util._get_or_create_global_step_read() # pylint: disable=protected-access
model_fn_ops = self._get_train_ops(features, labels)
ops.add_to_collection(ops.GraphKeys.LOSSES, model_fn_ops.loss)
all_hooks.extend(hooks)
all_hooks.extend([
basic_session_run_hooks.NanTensorHook(model_fn_ops.loss),
basic_session_run_hooks.LoggingTensorHook(
{
'loss': model_fn_ops.loss,
'step': global_step
},
every_n_iter=100)
])
scaffold = model_fn_ops.scaffold or monitored_session.Scaffold()
if not (scaffold.saver or ops.get_collection(ops.GraphKeys.SAVERS)):
ops.add_to_collection(
ops.GraphKeys.SAVERS,
saver.Saver(
sharded=True,
max_to_keep=self._config.keep_checkpoint_max,
keep_checkpoint_every_n_hours=(
self._config.keep_checkpoint_every_n_hours),
defer_build=True,
save_relative_paths=True))
chief_hooks = []
if (self._config.save_checkpoints_secs or
self._config.save_checkpoints_steps):
saver_hook_exists = any([
isinstance(h, basic_session_run_hooks.CheckpointSaverHook)
for h in (all_hooks + model_fn_ops.training_hooks + chief_hooks +
model_fn_ops.training_chief_hooks)
])
if not saver_hook_exists:
chief_hooks = [
basic_session_run_hooks.CheckpointSaverHook(
self._model_dir,
save_secs=self._config.save_checkpoints_secs,
save_steps=self._config.save_checkpoints_steps,
scaffold=scaffold)
]
with monitored_session.MonitoredTrainingSession(
master=self._config.master,
is_chief=self._config.is_chief,
checkpoint_dir=self._model_dir,
scaffold=scaffold,
hooks=all_hooks + model_fn_ops.training_hooks,
chief_only_hooks=chief_hooks + model_fn_ops.training_chief_hooks,
save_checkpoint_secs=0, # Saving is handled by a hook.
save_summaries_steps=self._config.save_summary_steps,
config=self._session_config) as mon_sess:
loss = None
while not mon_sess.should_stop():
_, loss = mon_sess.run([model_fn_ops.train_op, model_fn_ops.loss])
return loss
def _identity_feature_engineering_fn(features, labels):
return features, labels
class Estimator(BaseEstimator):
"""Estimator class is the basic TensorFlow model trainer/evaluator.
"""
def __init__(self,
model_fn=None,
model_dir=None,
config=None,
params=None,
feature_engineering_fn=None):
"""Constructs an `Estimator` instance.
Args:
model_fn: Model function. Follows the signature:
* Args:
* `features`: single `Tensor` or `dict` of `Tensor`s
(depending on data passed to `fit`),
* `labels`: `Tensor` or `dict` of `Tensor`s (for multi-head
models). If mode is `ModeKeys.INFER`, `labels=None` will be
passed. If the `model_fn`'s signature does not accept
`mode`, the `model_fn` must still be able to handle
`labels=None`.
* `mode`: Optional. Specifies if this training, evaluation or
prediction. See `ModeKeys`.
* `params`: Optional `dict` of hyperparameters. Will receive what
is passed to Estimator in `params` parameter. This allows
to configure Estimators from hyper parameter tuning.
* `config`: Optional configuration object. Will receive what is passed
to Estimator in `config` parameter, or the default `config`.
Allows updating things in your model_fn based on configuration
such as `num_ps_replicas`.
* `model_dir`: Optional directory where model parameters, graph etc
are saved. Will receive what is passed to Estimator in
`model_dir` parameter, or the default `model_dir`. Allows
updating things in your model_fn that expect model_dir, such as
training hooks.
* Returns:
`ModelFnOps`
Also supports a legacy signature which returns tuple of:
* predictions: `Tensor`, `SparseTensor` or dictionary of same.
Can also be any type that is convertible to a `Tensor` or
`SparseTensor`, or dictionary of same.
* loss: Scalar loss `Tensor`.
* train_op: Training update `Tensor` or `Operation`.
Supports next three signatures for the function:
* `(features, labels) -> (predictions, loss, train_op)`
* `(features, labels, mode) -> (predictions, loss, train_op)`
* `(features, labels, mode, params) -> (predictions, loss, train_op)`
* `(features, labels, mode, params, config) ->
(predictions, loss, train_op)`
* `(features, labels, mode, params, config, model_dir) ->
(predictions, loss, train_op)`
model_dir: Directory to save model parameters, graph and etc. This can
also be used to load checkpoints from the directory into a estimator to
continue training a previously saved model.
config: Configuration object.
params: `dict` of hyper parameters that will be passed into `model_fn`.
Keys are names of parameters, values are basic python types.
feature_engineering_fn: Feature engineering function. Takes features and
labels which are the output of `input_fn` and
returns features and labels which will be fed
into `model_fn`. Please check `model_fn` for
a definition of features and labels.
Raises:
ValueError: parameters of `model_fn` don't match `params`.
"""
super(Estimator, self).__init__(model_dir=model_dir, config=config)
if model_fn is not None:
# Check number of arguments of the given function matches requirements.
model_fn_args = _model_fn_args(model_fn)
if params is not None and 'params' not in model_fn_args:
raise ValueError('Estimator\'s model_fn (%s) does not have a params '
'argument, but params (%s) were passed to the '
'Estimator\'s constructor.' % (model_fn, params))
if params is None and 'params' in model_fn_args:
logging.warning('Estimator\'s model_fn (%s) includes params '
'argument, but params are not passed to Estimator.',
model_fn)
self._model_fn = model_fn
self.params = params
self._feature_engineering_fn = (
feature_engineering_fn or _identity_feature_engineering_fn)
def _call_model_fn(self, features, labels, mode, metrics=None):
"""Calls model function with support of 2, 3 or 4 arguments.
Args:
features: features dict.
labels: labels dict.
mode: ModeKeys
metrics: Dict of metrics.
Returns:
A `ModelFnOps` object. If model_fn returns a tuple, wraps them up in a
`ModelFnOps` object.
Raises:
ValueError: if model_fn returns invalid objects.
"""
features, labels = self._feature_engineering_fn(features, labels)
model_fn_args = _model_fn_args(self._model_fn)
kwargs = {}
if 'mode' in model_fn_args:
kwargs['mode'] = mode
if 'params' in model_fn_args:
kwargs['params'] = self.params
if 'config' in model_fn_args:
kwargs['config'] = self.config
if 'model_dir' in model_fn_args:
kwargs['model_dir'] = self.model_dir
model_fn_results = self._model_fn(features, labels, **kwargs)
if isinstance(model_fn_results, model_fn_lib.ModelFnOps):
model_fn_ops = model_fn_results
else:
# Here model_fn_results should be a tuple with 3 elements.
if len(model_fn_results) != 3:
raise ValueError('Unrecognized value returned by model_fn, '
'please return ModelFnOps.')
model_fn_ops = model_fn_lib.ModelFnOps(
mode=mode,
predictions=model_fn_results[0],
loss=model_fn_results[1],
train_op=model_fn_results[2])
# Custom metrics should overwrite defaults.
if metrics:
model_fn_ops.eval_metric_ops.update(
_make_metrics_ops(metrics, features, labels,
model_fn_ops.predictions))
return model_fn_ops
def _get_train_ops(self, features, labels):
"""Method that builds model graph and returns trainer ops.
Expected to be overridden by sub-classes that require custom support.
This implementation uses `model_fn` passed as parameter to constructor to
build model.
Args:
features: `Tensor` or `dict` of `Tensor` objects.
labels: `Tensor` or `dict` of `Tensor` objects.
Returns:
`ModelFnOps` object.
"""
return self._call_model_fn(features, labels, model_fn_lib.ModeKeys.TRAIN)
def _get_eval_ops(self, features, labels, metrics):
"""Method that builds model graph and returns evaluation ops.
Expected to be overridden by sub-classes that require custom support.
This implementation uses `model_fn` passed as parameter to constructor to
build model.
Args:
features: `Tensor` or `dict` of `Tensor` objects.
labels: `Tensor` or `dict` of `Tensor` objects.
metrics: Dict of metrics to run. If None, the default metric functions
are used; if {}, no metrics are used. Otherwise, `metrics` should map
friendly names for the metric to a `MetricSpec` object defining which
model outputs to evaluate against which labels with which metric
function. Metric ops should support streaming, e.g., returning
update_op and value tensors. See more details in
`../../../../metrics/python/metrics/ops/streaming_metrics.py` and
`../metric_spec.py`.
Returns:
`ModelFnOps` object.
Raises:
ValueError: if `metrics` don't match `labels`.
"""
model_fn_ops = self._call_model_fn(features, labels,
model_fn_lib.ModeKeys.EVAL, metrics)
if metric_key.MetricKey.LOSS not in model_fn_ops.eval_metric_ops:
model_fn_ops.eval_metric_ops[metric_key.MetricKey.LOSS] = (
metrics_lib.mean(model_fn_ops.loss))
return model_fn_ops
def _get_predict_ops(self, features):
"""Method that builds model graph and returns prediction ops.
Expected to be overridden by sub-classes that require custom support.
This implementation uses `model_fn` passed as parameter to constructor to
build model.
Args:
features: `Tensor` or `dict` of `Tensor` objects.
Returns:
`ModelFnOps` object.
"""
labels = tensor_signature.create_placeholders_from_signatures(
self._labels_info)
return self._call_model_fn(features, labels, model_fn_lib.ModeKeys.INFER)
def export_savedmodel(self,
export_dir_base,
serving_input_fn,
default_output_alternative_key=None,
assets_extra=None,
as_text=False,
checkpoint_path=None,
graph_rewrite_specs=(GraphRewriteSpec(
(tag_constants.SERVING,), ()),),
strip_default_attrs=False):
# pylint: disable=line-too-long
"""Exports inference graph as a SavedModel into given dir.
Args:
export_dir_base: A string containing a directory to write the exported
graph and checkpoints.
serving_input_fn: A function that takes no argument and
returns an `InputFnOps`.
default_output_alternative_key: the name of the head to serve when none is
specified. Not needed for single-headed models.
assets_extra: A dict specifying how to populate the assets.extra directory
within the exported SavedModel. Each key should give the destination
path (including the filename) relative to the assets.extra directory.
The corresponding value gives the full path of the source file to be
copied. For example, the simple case of copying a single file without
renaming it is specified as
`{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
as_text: whether to write the SavedModel proto in text format.
checkpoint_path: The checkpoint path to export. If None (the default),
the most recent checkpoint found within the model directory is chosen.
graph_rewrite_specs: an iterable of `GraphRewriteSpec`. Each element will
produce a separate MetaGraphDef within the exported SavedModel, tagged
and rewritten as specified. Defaults to a single entry using the
default serving tag ("serve") and no rewriting.
strip_default_attrs: Boolean. If `True`, default-valued attributes will be
removed from the NodeDefs. For a detailed guide, see
[Stripping Default-Valued
Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes).
Returns:
The string path to the exported directory.
Raises:
ValueError: if an unrecognized export_type is requested.
"""
# pylint: enable=line-too-long
if serving_input_fn is None:
raise ValueError('serving_input_fn must be defined.')
if not checkpoint_path:
# Locate the latest checkpoint
checkpoint_path = saver.latest_checkpoint(self._model_dir)
if not checkpoint_path:
raise NotFittedError(
"Couldn't find trained model at %s." % self._model_dir)
export_dir = saved_model_export_utils.get_timestamped_export_dir(
export_dir_base)
# We'll write the SavedModel to a temporary directory and then atomically
# rename it at the end. This helps to avoid corrupt / incomplete outputs,
# which could otherwise occur if the job is preempted or otherwise fails
# in the middle of SavedModel creation.
temp_export_dir = saved_model_export_utils.get_temp_export_dir(export_dir)
builder = saved_model_builder.SavedModelBuilder(temp_export_dir)
# Build the base graph
with ops.Graph().as_default() as g:
training_util.create_global_step(g)
# Call the serving_input_fn and collect the input alternatives.
input_ops = serving_input_fn()
input_alternatives, features = (
saved_model_export_utils.get_input_alternatives(input_ops))
# TODO(b/34388557) This is a stopgap, pending recording model provenance.
# Record which features are expected at serving time. It is assumed that
# these are the features that were used in training.
for feature_key in input_ops.features.keys():
ops.add_to_collection(
constants.COLLECTION_DEF_KEY_FOR_INPUT_FEATURE_KEYS, feature_key)
# Call the model_fn and collect the output alternatives.
model_fn_ops = self._call_model_fn(features, None,
model_fn_lib.ModeKeys.INFER)
output_alternatives, actual_default_output_alternative_key = (
saved_model_export_utils.get_output_alternatives(
model_fn_ops, default_output_alternative_key))
init_op = control_flow_ops.group(variables.local_variables_initializer(),
resources.initialize_resources(
resources.shared_resources()),
lookup_ops.tables_initializer())
# Build the SignatureDefs from all pairs of input and output alternatives
signature_def_map = saved_model_export_utils.build_all_signature_defs(
input_alternatives, output_alternatives,
actual_default_output_alternative_key)
# Export the first MetaGraphDef with variables, assets etc.
with tf_session.Session('') as session:
# pylint: disable=protected-access
saveables = variables._all_saveable_objects()
# pylint: enable=protected-access
if (model_fn_ops.scaffold is not None and
model_fn_ops.scaffold.saver is not None):
saver_for_restore = model_fn_ops.scaffold.saver
elif saveables:
saver_for_restore = saver.Saver(saveables, sharded=True)
saver_for_restore.restore(session, checkpoint_path)
# Perform the export
if not graph_rewrite_specs or graph_rewrite_specs[0].transforms:
raise ValueError('The first element of graph_rewrite_specs '
'must specify no transforms.')
untransformed_tags = graph_rewrite_specs[0].tags
# TODO(soergel): switch to main_op or otherwise update when dust settles
builder.add_meta_graph_and_variables(
session,
untransformed_tags,
signature_def_map=signature_def_map,
assets_collection=ops.get_collection(ops.GraphKeys.ASSET_FILEPATHS),
legacy_init_op=init_op,
strip_default_attrs=strip_default_attrs)
# pylint: disable=protected-access
base_meta_graph_def = builder._saved_model.meta_graphs[0]
# pylint: enable=protected-access
if graph_rewrite_specs[1:]:
# Prepare the input_names and output_names needed for the
# meta_graph_transform call below.
input_names = [
tensor.name
for input_dict in input_alternatives.values()
for tensor in input_dict.values()
]
output_names = [
tensor.name
for output_alternative in output_alternatives.values()
for tensor in output_alternative[1].values()
]
# Write the additional MetaGraphDefs
for graph_rewrite_spec in graph_rewrite_specs[1:]:
# TODO(soergel) consider moving most of this to saved_model.builder_impl
# as e.g. builder.add_rewritten_meta_graph(rewritten_graph_def, tags)
transformed_meta_graph_def = meta_graph_transform.meta_graph_transform(
base_meta_graph_def, input_names, output_names,
graph_rewrite_spec.transforms, graph_rewrite_spec.tags)
# pylint: disable=protected-access
meta_graph_def = builder._saved_model.meta_graphs.add()
# pylint: enable=protected-access
meta_graph_def.CopyFrom(transformed_meta_graph_def)
# Add the extra assets
if assets_extra:
assets_extra_path = os.path.join(
compat.as_bytes(temp_export_dir), compat.as_bytes('assets.extra'))
for dest_relative, source in assets_extra.items():
dest_absolute = os.path.join(
compat.as_bytes(assets_extra_path), compat.as_bytes(dest_relative))
dest_path = os.path.dirname(dest_absolute)
gfile.MakeDirs(dest_path)
gfile.Copy(source, dest_absolute)
builder.save(as_text)
gfile.Rename(temp_export_dir, export_dir)
return export_dir
# For time of deprecation x,y from Estimator allow direct access.
# pylint: disable=protected-access
class SKCompat(sklearn.BaseEstimator):
"""Scikit learn wrapper for TensorFlow Learn Estimator."""
def __init__(self, estimator):
self._estimator = estimator
def fit(self, x, y, batch_size=128, steps=None, max_steps=None,
monitors=None):
input_fn, feed_fn = _get_input_fn(
x,
y,
input_fn=None,
feed_fn=None,
batch_size=batch_size,
shuffle=True,
epochs=None)
all_monitors = []
if feed_fn:
all_monitors = [basic_session_run_hooks.FeedFnHook(feed_fn)]
if monitors:
all_monitors.extend(monitors)
self._estimator.fit(
input_fn=input_fn,
steps=steps,
max_steps=max_steps,
monitors=all_monitors)
return self
def score(self, x, y, batch_size=128, steps=None, metrics=None, name=None):
input_fn, feed_fn = _get_input_fn(
x,
y,
input_fn=None,
feed_fn=None,
batch_size=batch_size,
shuffle=False,
epochs=1)
if metrics is not None and not isinstance(metrics, dict):
raise ValueError('Metrics argument should be None or dict. '
'Got %s.' % metrics)
eval_results, global_step = self._estimator._evaluate_model(
input_fn=input_fn,
feed_fn=feed_fn,
steps=steps,
metrics=metrics,
name=name)
if eval_results is not None:
eval_results.update({'global_step': global_step})
return eval_results
def predict(self, x, batch_size=128, outputs=None):
input_fn, feed_fn = _get_input_fn(
x,
None,
input_fn=None,
feed_fn=None,
batch_size=batch_size,
shuffle=False,
epochs=1)
results = list(
self._estimator._infer_model(
input_fn=input_fn,
feed_fn=feed_fn,
outputs=outputs,
as_iterable=True,
iterate_batches=True))
if not isinstance(results[0], dict):
return np.concatenate([output for output in results], axis=0)
return {
key: np.concatenate([output[key] for output in results], axis=0)
for key in results[0]
}
|
apache-2.0
|
aetilley/scikit-learn
|
examples/linear_model/plot_multi_task_lasso_support.py
|
249
|
2211
|
#!/usr/bin/env python
"""
=============================================
Joint feature selection with multi-task Lasso
=============================================
The multi-task lasso allows to fit multiple regression problems
jointly enforcing the selected features to be the same across
tasks. This example simulates sequential measurements, each task
is a time instant, and the relevant features vary in amplitude
over time while being the same. The multi-task lasso imposes that
features that are selected at one time point are select for all time
point. This makes feature selection by the Lasso more stable.
"""
print(__doc__)
# Author: Alexandre Gramfort <[email protected]>
# License: BSD 3 clause
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import MultiTaskLasso, Lasso
rng = np.random.RandomState(42)
# Generate some 2D coefficients with sine waves with random frequency and phase
n_samples, n_features, n_tasks = 100, 30, 40
n_relevant_features = 5
coef = np.zeros((n_tasks, n_features))
times = np.linspace(0, 2 * np.pi, n_tasks)
for k in range(n_relevant_features):
coef[:, k] = np.sin((1. + rng.randn(1)) * times + 3 * rng.randn(1))
X = rng.randn(n_samples, n_features)
Y = np.dot(X, coef.T) + rng.randn(n_samples, n_tasks)
coef_lasso_ = np.array([Lasso(alpha=0.5).fit(X, y).coef_ for y in Y.T])
coef_multi_task_lasso_ = MultiTaskLasso(alpha=1.).fit(X, Y).coef_
###############################################################################
# Plot support and time series
fig = plt.figure(figsize=(8, 5))
plt.subplot(1, 2, 1)
plt.spy(coef_lasso_)
plt.xlabel('Feature')
plt.ylabel('Time (or Task)')
plt.text(10, 5, 'Lasso')
plt.subplot(1, 2, 2)
plt.spy(coef_multi_task_lasso_)
plt.xlabel('Feature')
plt.ylabel('Time (or Task)')
plt.text(10, 5, 'MultiTaskLasso')
fig.suptitle('Coefficient non-zero location')
feature_to_plot = 0
plt.figure()
plt.plot(coef[:, feature_to_plot], 'k', label='Ground truth')
plt.plot(coef_lasso_[:, feature_to_plot], 'g', label='Lasso')
plt.plot(coef_multi_task_lasso_[:, feature_to_plot],
'r', label='MultiTaskLasso')
plt.legend(loc='upper center')
plt.axis('tight')
plt.ylim([-1.1, 1.1])
plt.show()
|
bsd-3-clause
|
louisLouL/pair_trading
|
capstone_env/lib/python3.6/site-packages/pandas/tests/series/test_dtypes.py
|
3
|
9418
|
# coding=utf-8
# pylint: disable-msg=E1101,W0612
import pytest
from datetime import datetime
import sys
import string
import warnings
from numpy import nan
import numpy as np
from pandas import Series, Timestamp, Timedelta, DataFrame, date_range
from pandas.compat import lrange, range, u
from pandas import compat
import pandas.util.testing as tm
from .common import TestData
class TestSeriesDtypes(TestData):
@pytest.mark.parametrize("dtype", ["float32", "float64",
"int64", "int32"])
def test_astype(self, dtype):
s = Series(np.random.randn(5), name='foo')
as_typed = s.astype(dtype)
assert as_typed.dtype == dtype
assert as_typed.name == s.name
def test_dtype(self):
assert self.ts.dtype == np.dtype('float64')
assert self.ts.dtypes == np.dtype('float64')
assert self.ts.ftype == 'float64:dense'
assert self.ts.ftypes == 'float64:dense'
tm.assert_series_equal(self.ts.get_dtype_counts(),
Series(1, ['float64']))
tm.assert_series_equal(self.ts.get_ftype_counts(),
Series(1, ['float64:dense']))
@pytest.mark.parametrize("value", [np.nan, np.inf])
@pytest.mark.parametrize("dtype", [np.int32, np.int64])
def test_astype_cast_nan_inf_int(self, dtype, value):
# gh-14265: check NaN and inf raise error when converting to int
msg = 'Cannot convert non-finite values \\(NA or inf\\) to integer'
s = Series([value])
with tm.assert_raises_regex(ValueError, msg):
s.astype(dtype)
@pytest.mark.parametrize("dtype", [int, np.int8, np.int64])
def test_astype_cast_object_int_fail(self, dtype):
arr = Series(["car", "house", "tree", "1"])
with pytest.raises(ValueError):
arr.astype(dtype)
def test_astype_cast_object_int(self):
arr = Series(['1', '2', '3', '4'], dtype=object)
result = arr.astype(int)
tm.assert_series_equal(result, Series(np.arange(1, 5)))
def test_astype_datetimes(self):
import pandas._libs.tslib as tslib
s = Series(tslib.iNaT, dtype='M8[ns]', index=lrange(5))
s = s.astype('O')
assert s.dtype == np.object_
s = Series([datetime(2001, 1, 2, 0, 0)])
s = s.astype('O')
assert s.dtype == np.object_
s = Series([datetime(2001, 1, 2, 0, 0) for i in range(3)])
s[1] = np.nan
assert s.dtype == 'M8[ns]'
s = s.astype('O')
assert s.dtype == np.object_
@pytest.mark.parametrize("dtype", [compat.text_type, np.str_])
@pytest.mark.parametrize("series", [Series([string.digits * 10,
tm.rands(63),
tm.rands(64),
tm.rands(1000)]),
Series([string.digits * 10,
tm.rands(63),
tm.rands(64), nan, 1.0])])
def test_astype_str_map(self, dtype, series):
# see gh-4405
result = series.astype(dtype)
expected = series.map(compat.text_type)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("dtype", [str, compat.text_type])
def test_astype_str_cast(self, dtype):
# see gh-9757: test str and unicode on python 2.x
# and just str on python 3.x
ts = Series([Timestamp('2010-01-04 00:00:00')])
s = ts.astype(dtype)
expected = Series([dtype('2010-01-04')])
tm.assert_series_equal(s, expected)
ts = Series([Timestamp('2010-01-04 00:00:00', tz='US/Eastern')])
s = ts.astype(dtype)
expected = Series([dtype('2010-01-04 00:00:00-05:00')])
tm.assert_series_equal(s, expected)
td = Series([Timedelta(1, unit='d')])
s = td.astype(dtype)
expected = Series([dtype('1 days 00:00:00.000000000')])
tm.assert_series_equal(s, expected)
def test_astype_unicode(self):
# see gh-7758: A bit of magic is required to set
# default encoding to utf-8
digits = string.digits
test_series = [
Series([digits * 10, tm.rands(63), tm.rands(64), tm.rands(1000)]),
Series([u('データーサイエンス、お前はもう死んでいる')]),
]
former_encoding = None
if not compat.PY3:
# In Python, we can force the default encoding for this test
former_encoding = sys.getdefaultencoding()
reload(sys) # noqa
sys.setdefaultencoding("utf-8")
if sys.getdefaultencoding() == "utf-8":
test_series.append(Series([u('野菜食べないとやばい')
.encode("utf-8")]))
for s in test_series:
res = s.astype("unicode")
expec = s.map(compat.text_type)
tm.assert_series_equal(res, expec)
# Restore the former encoding
if former_encoding is not None and former_encoding != "utf-8":
reload(sys) # noqa
sys.setdefaultencoding(former_encoding)
@pytest.mark.parametrize("dtype_class", [dict, Series])
def test_astype_dict_like(self, dtype_class):
# see gh-7271
s = Series(range(0, 10, 2), name='abc')
dt1 = dtype_class({'abc': str})
result = s.astype(dt1)
expected = Series(['0', '2', '4', '6', '8'], name='abc')
tm.assert_series_equal(result, expected)
dt2 = dtype_class({'abc': 'float64'})
result = s.astype(dt2)
expected = Series([0.0, 2.0, 4.0, 6.0, 8.0], dtype='float64',
name='abc')
tm.assert_series_equal(result, expected)
dt3 = dtype_class({'abc': str, 'def': str})
with pytest.raises(KeyError):
s.astype(dt3)
dt4 = dtype_class({0: str})
with pytest.raises(KeyError):
s.astype(dt4)
# GH16717
# if dtypes provided is empty, it should error
dt5 = dtype_class({})
with pytest.raises(KeyError):
s.astype(dt5)
def test_astype_generic_timestamp_deprecated(self):
# see gh-15524
data = [1]
with tm.assert_produces_warning(FutureWarning,
check_stacklevel=False):
s = Series(data)
dtype = np.datetime64
result = s.astype(dtype)
expected = Series(data, dtype=dtype)
tm.assert_series_equal(result, expected)
with tm.assert_produces_warning(FutureWarning,
check_stacklevel=False):
s = Series(data)
dtype = np.timedelta64
result = s.astype(dtype)
expected = Series(data, dtype=dtype)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("dtype", np.typecodes['All'])
def test_astype_empty_constructor_equality(self, dtype):
# see gh-15524
if dtype not in ('S', 'V'): # poor support (if any) currently
with warnings.catch_warnings(record=True):
# Generic timestamp dtypes ('M' and 'm') are deprecated,
# but we test that already in series/test_constructors.py
init_empty = Series([], dtype=dtype)
as_type_empty = Series([]).astype(dtype)
tm.assert_series_equal(init_empty, as_type_empty)
def test_complex(self):
# see gh-4819: complex access for ndarray compat
a = np.arange(5, dtype=np.float64)
b = Series(a + 4j * a)
tm.assert_numpy_array_equal(a, b.real)
tm.assert_numpy_array_equal(4 * a, b.imag)
b.real = np.arange(5) + 5
tm.assert_numpy_array_equal(a + 5, b.real)
tm.assert_numpy_array_equal(4 * a, b.imag)
def test_arg_for_errors_in_astype(self):
# see gh-14878
s = Series([1, 2, 3])
with pytest.raises(ValueError):
s.astype(np.float64, errors=False)
with tm.assert_produces_warning(FutureWarning):
s.astype(np.int8, raise_on_error=True)
s.astype(np.int8, errors='raise')
def test_intercept_astype_object(self):
series = Series(date_range('1/1/2000', periods=10))
# This test no longer makes sense, as
# Series is by default already M8[ns].
expected = series.astype('object')
df = DataFrame({'a': series,
'b': np.random.randn(len(series))})
exp_dtypes = Series([np.dtype('datetime64[ns]'),
np.dtype('float64')], index=['a', 'b'])
tm.assert_series_equal(df.dtypes, exp_dtypes)
result = df.values.squeeze()
assert (result[:, 0] == expected.values).all()
df = DataFrame({'a': series, 'b': ['foo'] * len(series)})
result = df.values.squeeze()
assert (result[:, 0] == expected.values).all()
def test_series_to_categorical(self):
# see gh-16524: test conversion of Series to Categorical
series = Series(['a', 'b', 'c'])
result = Series(series, dtype='category')
expected = Series(['a', 'b', 'c'], dtype='category')
tm.assert_series_equal(result, expected)
|
mit
|
theoryno3/scikit-learn
|
sklearn/neighbors/nearest_centroid.py
|
25
|
7219
|
# -*- coding: utf-8 -*-
"""
Nearest Centroid Classification
"""
# Author: Robert Layton <[email protected]>
# Olivier Grisel <[email protected]>
#
# License: BSD 3 clause
import warnings
import numpy as np
from scipy import sparse as sp
from ..base import BaseEstimator, ClassifierMixin
from ..externals.six.moves import xrange
from ..metrics.pairwise import pairwise_distances
from ..preprocessing import LabelEncoder
from ..utils.validation import check_array, check_X_y, check_is_fitted
from ..utils.sparsefuncs import csc_median_axis_0
class NearestCentroid(BaseEstimator, ClassifierMixin):
"""Nearest centroid classifier.
Each class is represented by its centroid, with test samples classified to
the class with the nearest centroid.
Parameters
----------
metric: string, or callable
The metric to use when calculating distance between instances in a
feature array. If metric is a string or callable, it must be one of
the options allowed by metrics.pairwise.pairwise_distances for its
metric parameter.
The centroids for the samples corresponding to each class is the point
from which the sum of the distances (according to the metric) of all
samples that belong to that particular class are minimized.
If the "manhattan" metric is provided, this centroid is the median and
for all other metrics, the centroid is now set to be the mean.
shrink_threshold : float, optional (default = None)
Threshold for shrinking centroids to remove features.
Attributes
----------
centroids_ : array-like, shape = [n_classes, n_features]
Centroid of each class
Examples
--------
>>> from sklearn.neighbors.nearest_centroid import NearestCentroid
>>> import numpy as np
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> y = np.array([1, 1, 1, 2, 2, 2])
>>> clf = NearestCentroid()
>>> clf.fit(X, y)
NearestCentroid(metric='euclidean', shrink_threshold=None)
>>> print(clf.predict([[-0.8, -1]]))
[1]
See also
--------
sklearn.neighbors.KNeighborsClassifier: nearest neighbors classifier
Notes
-----
When used for text classification with tf-idf vectors, this classifier is
also known as the Rocchio classifier.
References
----------
Tibshirani, R., Hastie, T., Narasimhan, B., & Chu, G. (2002). Diagnosis of
multiple cancer types by shrunken centroids of gene expression. Proceedings
of the National Academy of Sciences of the United States of America,
99(10), 6567-6572. The National Academy of Sciences.
"""
def __init__(self, metric='euclidean', shrink_threshold=None):
self.metric = metric
self.shrink_threshold = shrink_threshold
def fit(self, X, y):
"""
Fit the NearestCentroid model according to the given training data.
Parameters
----------
X : {array-like, sparse matrix}, shape = [n_samples, n_features]
Training vector, where n_samples in the number of samples and
n_features is the number of features.
Note that centroid shrinking cannot be used with sparse matrices.
y : array, shape = [n_samples]
Target values (integers)
"""
# If X is sparse and the metric is "manhattan", store it in a csc
# format is easier to calculate the median.
if self.metric == 'manhattan':
X, y = check_X_y(X, y, ['csc'])
else:
X, y = check_X_y(X, y, ['csr', 'csc'])
is_X_sparse = sp.issparse(X)
if is_X_sparse and self.shrink_threshold:
raise ValueError("threshold shrinking not supported"
" for sparse input")
n_samples, n_features = X.shape
le = LabelEncoder()
y_ind = le.fit_transform(y)
self.classes_ = classes = le.classes_
n_classes = classes.size
if n_classes < 2:
raise ValueError('y has less than 2 classes')
# Mask mapping each class to it's members.
self.centroids_ = np.empty((n_classes, n_features), dtype=np.float64)
# Number of clusters in each class.
nk = np.zeros(n_classes)
for cur_class in range(n_classes):
center_mask = y_ind == cur_class
nk[cur_class] = np.sum(center_mask)
if is_X_sparse:
center_mask = np.where(center_mask)[0]
# XXX: Update other averaging methods according to the metrics.
if self.metric == "manhattan":
# NumPy does not calculate median of sparse matrices.
if not is_X_sparse:
self.centroids_[cur_class] = np.median(X[center_mask], axis=0)
else:
self.centroids_[cur_class] = csc_median_axis_0(X[center_mask])
else:
if self.metric != 'euclidean':
warnings.warn("Averaging for metrics other than "
"euclidean and manhattan not supported. "
"The average is set to be the mean."
)
self.centroids_[cur_class] = X[center_mask].mean(axis=0)
if self.shrink_threshold:
dataset_centroid_ = np.mean(X, axis=0)
# m parameter for determining deviation
m = np.sqrt((1. / nk) + (1. / n_samples))
# Calculate deviation using the standard deviation of centroids.
variance = (X - self.centroids_[y_ind]) ** 2
variance = variance.sum(axis=0)
s = np.sqrt(variance / (n_samples - n_classes))
s += np.median(s) # To deter outliers from affecting the results.
mm = m.reshape(len(m), 1) # Reshape to allow broadcasting.
ms = mm * s
deviation = ((self.centroids_ - dataset_centroid_) / ms)
# Soft thresholding: if the deviation crosses 0 during shrinking,
# it becomes zero.
signs = np.sign(deviation)
deviation = (np.abs(deviation) - self.shrink_threshold)
deviation[deviation < 0] = 0
deviation *= signs
# Now adjust the centroids using the deviation
msd = ms * deviation
self.centroids_ = dataset_centroid_[np.newaxis, :] + msd
return self
def predict(self, X):
"""Perform classification on an array of test vectors X.
The predicted class C for each sample in X is returned.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Returns
-------
C : array, shape = [n_samples]
Notes
-----
If the metric constructor parameter is "precomputed", X is assumed to
be the distance matrix between the data to be predicted and
``self.centroids_``.
"""
check_is_fitted(self, 'centroids_')
X = check_array(X, accept_sparse='csr')
return self.classes_[pairwise_distances(
X, self.centroids_, metric=self.metric).argmin(axis=1)]
|
bsd-3-clause
|
tosolveit/scikit-learn
|
sklearn/datasets/base.py
|
196
|
18554
|
"""
Base IO code for all datasets
"""
# Copyright (c) 2007 David Cournapeau <[email protected]>
# 2010 Fabian Pedregosa <[email protected]>
# 2010 Olivier Grisel <[email protected]>
# License: BSD 3 clause
import os
import csv
import shutil
from os import environ
from os.path import dirname
from os.path import join
from os.path import exists
from os.path import expanduser
from os.path import isdir
from os import listdir
from os import makedirs
import numpy as np
from ..utils import check_random_state
class Bunch(dict):
"""Container object for datasets
Dictionary-like object that exposes its keys as attributes.
>>> b = Bunch(a=1, b=2)
>>> b['b']
2
>>> b.b
2
>>> b.a = 3
>>> b['a']
3
>>> b.c = 6
>>> b['c']
6
"""
def __init__(self, **kwargs):
dict.__init__(self, kwargs)
def __setattr__(self, key, value):
self[key] = value
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(key)
def __getstate__(self):
return self.__dict__
def get_data_home(data_home=None):
"""Return the path of the scikit-learn data dir.
This folder is used by some large dataset loaders to avoid
downloading the data several times.
By default the data dir is set to a folder named 'scikit_learn_data'
in the user home folder.
Alternatively, it can be set by the 'SCIKIT_LEARN_DATA' environment
variable or programmatically by giving an explicit folder path. The
'~' symbol is expanded to the user home folder.
If the folder does not already exist, it is automatically created.
"""
if data_home is None:
data_home = environ.get('SCIKIT_LEARN_DATA',
join('~', 'scikit_learn_data'))
data_home = expanduser(data_home)
if not exists(data_home):
makedirs(data_home)
return data_home
def clear_data_home(data_home=None):
"""Delete all the content of the data home cache."""
data_home = get_data_home(data_home)
shutil.rmtree(data_home)
def load_files(container_path, description=None, categories=None,
load_content=True, shuffle=True, encoding=None,
decode_error='strict', random_state=0):
"""Load text files with categories as subfolder names.
Individual samples are assumed to be files stored a two levels folder
structure such as the following:
container_folder/
category_1_folder/
file_1.txt
file_2.txt
...
file_42.txt
category_2_folder/
file_43.txt
file_44.txt
...
The folder names are used as supervised signal label names. The
individual file names are not important.
This function does not try to extract features into a numpy array or
scipy sparse matrix. In addition, if load_content is false it
does not try to load the files in memory.
To use text files in a scikit-learn classification or clustering
algorithm, you will need to use the `sklearn.feature_extraction.text`
module to build a feature extraction transformer that suits your
problem.
If you set load_content=True, you should also specify the encoding of
the text using the 'encoding' parameter. For many modern text files,
'utf-8' will be the correct encoding. If you leave encoding equal to None,
then the content will be made of bytes instead of Unicode, and you will
not be able to use most functions in `sklearn.feature_extraction.text`.
Similar feature extractors should be built for other kind of unstructured
data input such as images, audio, video, ...
Read more in the :ref:`User Guide <datasets>`.
Parameters
----------
container_path : string or unicode
Path to the main folder holding one subfolder per category
description: string or unicode, optional (default=None)
A paragraph describing the characteristic of the dataset: its source,
reference, etc.
categories : A collection of strings or None, optional (default=None)
If None (default), load all the categories.
If not None, list of category names to load (other categories ignored).
load_content : boolean, optional (default=True)
Whether to load or not the content of the different files. If
true a 'data' attribute containing the text information is present
in the data structure returned. If not, a filenames attribute
gives the path to the files.
encoding : string or None (default is None)
If None, do not try to decode the content of the files (e.g. for
images or other non-text content).
If not None, encoding to use to decode text files to Unicode if
load_content is True.
decode_error: {'strict', 'ignore', 'replace'}, optional
Instruction on what to do if a byte sequence is given to analyze that
contains characters not of the given `encoding`. Passed as keyword
argument 'errors' to bytes.decode.
shuffle : bool, optional (default=True)
Whether or not to shuffle the data: might be important for models that
make the assumption that the samples are independent and identically
distributed (i.i.d.), such as stochastic gradient descent.
random_state : int, RandomState instance or None, optional (default=0)
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
-------
data : Bunch
Dictionary-like object, the interesting attributes are: either
data, the raw text data to learn, or 'filenames', the files
holding it, 'target', the classification labels (integer index),
'target_names', the meaning of the labels, and 'DESCR', the full
description of the dataset.
"""
target = []
target_names = []
filenames = []
folders = [f for f in sorted(listdir(container_path))
if isdir(join(container_path, f))]
if categories is not None:
folders = [f for f in folders if f in categories]
for label, folder in enumerate(folders):
target_names.append(folder)
folder_path = join(container_path, folder)
documents = [join(folder_path, d)
for d in sorted(listdir(folder_path))]
target.extend(len(documents) * [label])
filenames.extend(documents)
# convert to array for fancy indexing
filenames = np.array(filenames)
target = np.array(target)
if shuffle:
random_state = check_random_state(random_state)
indices = np.arange(filenames.shape[0])
random_state.shuffle(indices)
filenames = filenames[indices]
target = target[indices]
if load_content:
data = []
for filename in filenames:
with open(filename, 'rb') as f:
data.append(f.read())
if encoding is not None:
data = [d.decode(encoding, decode_error) for d in data]
return Bunch(data=data,
filenames=filenames,
target_names=target_names,
target=target,
DESCR=description)
return Bunch(filenames=filenames,
target_names=target_names,
target=target,
DESCR=description)
def load_iris():
"""Load and return the iris dataset (classification).
The iris dataset is a classic and very easy multi-class classification
dataset.
================= ==============
Classes 3
Samples per class 50
Samples total 150
Dimensionality 4
Features real, positive
================= ==============
Read more in the :ref:`User Guide <datasets>`.
Returns
-------
data : Bunch
Dictionary-like object, the interesting attributes are:
'data', the data to learn, 'target', the classification labels,
'target_names', the meaning of the labels, 'feature_names', the
meaning of the features, and 'DESCR', the
full description of the dataset.
Examples
--------
Let's say you are interested in the samples 10, 25, and 50, and want to
know their class name.
>>> from sklearn.datasets import load_iris
>>> data = load_iris()
>>> data.target[[10, 25, 50]]
array([0, 0, 1])
>>> list(data.target_names)
['setosa', 'versicolor', 'virginica']
"""
module_path = dirname(__file__)
with open(join(module_path, 'data', 'iris.csv')) as csv_file:
data_file = csv.reader(csv_file)
temp = next(data_file)
n_samples = int(temp[0])
n_features = int(temp[1])
target_names = np.array(temp[2:])
data = np.empty((n_samples, n_features))
target = np.empty((n_samples,), dtype=np.int)
for i, ir in enumerate(data_file):
data[i] = np.asarray(ir[:-1], dtype=np.float)
target[i] = np.asarray(ir[-1], dtype=np.int)
with open(join(module_path, 'descr', 'iris.rst')) as rst_file:
fdescr = rst_file.read()
return Bunch(data=data, target=target,
target_names=target_names,
DESCR=fdescr,
feature_names=['sepal length (cm)', 'sepal width (cm)',
'petal length (cm)', 'petal width (cm)'])
def load_digits(n_class=10):
"""Load and return the digits dataset (classification).
Each datapoint is a 8x8 image of a digit.
================= ==============
Classes 10
Samples per class ~180
Samples total 1797
Dimensionality 64
Features integers 0-16
================= ==============
Read more in the :ref:`User Guide <datasets>`.
Parameters
----------
n_class : integer, between 0 and 10, optional (default=10)
The number of classes to return.
Returns
-------
data : Bunch
Dictionary-like object, the interesting attributes are:
'data', the data to learn, 'images', the images corresponding
to each sample, 'target', the classification labels for each
sample, 'target_names', the meaning of the labels, and 'DESCR',
the full description of the dataset.
Examples
--------
To load the data and visualize the images::
>>> from sklearn.datasets import load_digits
>>> digits = load_digits()
>>> print(digits.data.shape)
(1797, 64)
>>> import pylab as pl #doctest: +SKIP
>>> pl.gray() #doctest: +SKIP
>>> pl.matshow(digits.images[0]) #doctest: +SKIP
>>> pl.show() #doctest: +SKIP
"""
module_path = dirname(__file__)
data = np.loadtxt(join(module_path, 'data', 'digits.csv.gz'),
delimiter=',')
with open(join(module_path, 'descr', 'digits.rst')) as f:
descr = f.read()
target = data[:, -1]
flat_data = data[:, :-1]
images = flat_data.view()
images.shape = (-1, 8, 8)
if n_class < 10:
idx = target < n_class
flat_data, target = flat_data[idx], target[idx]
images = images[idx]
return Bunch(data=flat_data,
target=target.astype(np.int),
target_names=np.arange(10),
images=images,
DESCR=descr)
def load_diabetes():
"""Load and return the diabetes dataset (regression).
============== ==================
Samples total 442
Dimensionality 10
Features real, -.2 < x < .2
Targets integer 25 - 346
============== ==================
Read more in the :ref:`User Guide <datasets>`.
Returns
-------
data : Bunch
Dictionary-like object, the interesting attributes are:
'data', the data to learn and 'target', the regression target for each
sample.
"""
base_dir = join(dirname(__file__), 'data')
data = np.loadtxt(join(base_dir, 'diabetes_data.csv.gz'))
target = np.loadtxt(join(base_dir, 'diabetes_target.csv.gz'))
return Bunch(data=data, target=target)
def load_linnerud():
"""Load and return the linnerud dataset (multivariate regression).
Samples total: 20
Dimensionality: 3 for both data and targets
Features: integer
Targets: integer
Returns
-------
data : Bunch
Dictionary-like object, the interesting attributes are: 'data' and
'targets', the two multivariate datasets, with 'data' corresponding to
the exercise and 'targets' corresponding to the physiological
measurements, as well as 'feature_names' and 'target_names'.
"""
base_dir = join(dirname(__file__), 'data/')
# Read data
data_exercise = np.loadtxt(base_dir + 'linnerud_exercise.csv', skiprows=1)
data_physiological = np.loadtxt(base_dir + 'linnerud_physiological.csv',
skiprows=1)
# Read header
with open(base_dir + 'linnerud_exercise.csv') as f:
header_exercise = f.readline().split()
with open(base_dir + 'linnerud_physiological.csv') as f:
header_physiological = f.readline().split()
with open(dirname(__file__) + '/descr/linnerud.rst') as f:
descr = f.read()
return Bunch(data=data_exercise, feature_names=header_exercise,
target=data_physiological,
target_names=header_physiological,
DESCR=descr)
def load_boston():
"""Load and return the boston house-prices dataset (regression).
============== ==============
Samples total 506
Dimensionality 13
Features real, positive
Targets real 5. - 50.
============== ==============
Returns
-------
data : Bunch
Dictionary-like object, the interesting attributes are:
'data', the data to learn, 'target', the regression targets,
and 'DESCR', the full description of the dataset.
Examples
--------
>>> from sklearn.datasets import load_boston
>>> boston = load_boston()
>>> print(boston.data.shape)
(506, 13)
"""
module_path = dirname(__file__)
fdescr_name = join(module_path, 'descr', 'boston_house_prices.rst')
with open(fdescr_name) as f:
descr_text = f.read()
data_file_name = join(module_path, 'data', 'boston_house_prices.csv')
with open(data_file_name) as f:
data_file = csv.reader(f)
temp = next(data_file)
n_samples = int(temp[0])
n_features = int(temp[1])
data = np.empty((n_samples, n_features))
target = np.empty((n_samples,))
temp = next(data_file) # names of features
feature_names = np.array(temp)
for i, d in enumerate(data_file):
data[i] = np.asarray(d[:-1], dtype=np.float)
target[i] = np.asarray(d[-1], dtype=np.float)
return Bunch(data=data,
target=target,
# last column is target value
feature_names=feature_names[:-1],
DESCR=descr_text)
def load_sample_images():
"""Load sample images for image manipulation.
Loads both, ``china`` and ``flower``.
Returns
-------
data : Bunch
Dictionary-like object with the following attributes :
'images', the two sample images, 'filenames', the file
names for the images, and 'DESCR'
the full description of the dataset.
Examples
--------
To load the data and visualize the images:
>>> from sklearn.datasets import load_sample_images
>>> dataset = load_sample_images() #doctest: +SKIP
>>> len(dataset.images) #doctest: +SKIP
2
>>> first_img_data = dataset.images[0] #doctest: +SKIP
>>> first_img_data.shape #doctest: +SKIP
(427, 640, 3)
>>> first_img_data.dtype #doctest: +SKIP
dtype('uint8')
"""
# Try to import imread from scipy. We do this lazily here to prevent
# this module from depending on PIL.
try:
try:
from scipy.misc import imread
except ImportError:
from scipy.misc.pilutil import imread
except ImportError:
raise ImportError("The Python Imaging Library (PIL) "
"is required to load data from jpeg files")
module_path = join(dirname(__file__), "images")
with open(join(module_path, 'README.txt')) as f:
descr = f.read()
filenames = [join(module_path, filename)
for filename in os.listdir(module_path)
if filename.endswith(".jpg")]
# Load image data for each image in the source folder.
images = [imread(filename) for filename in filenames]
return Bunch(images=images,
filenames=filenames,
DESCR=descr)
def load_sample_image(image_name):
"""Load the numpy array of a single sample image
Parameters
-----------
image_name: {`china.jpg`, `flower.jpg`}
The name of the sample image loaded
Returns
-------
img: 3D array
The image as a numpy array: height x width x color
Examples
---------
>>> from sklearn.datasets import load_sample_image
>>> china = load_sample_image('china.jpg') # doctest: +SKIP
>>> china.dtype # doctest: +SKIP
dtype('uint8')
>>> china.shape # doctest: +SKIP
(427, 640, 3)
>>> flower = load_sample_image('flower.jpg') # doctest: +SKIP
>>> flower.dtype # doctest: +SKIP
dtype('uint8')
>>> flower.shape # doctest: +SKIP
(427, 640, 3)
"""
images = load_sample_images()
index = None
for i, filename in enumerate(images.filenames):
if filename.endswith(image_name):
index = i
break
if index is None:
raise AttributeError("Cannot find sample image: %s" % image_name)
return images.images[index]
|
bsd-3-clause
|
ycaihua/scikit-learn
|
examples/exercises/plot_cv_diabetes.py
|
231
|
2527
|
"""
===============================================
Cross-validation on diabetes Dataset Exercise
===============================================
A tutorial exercise which uses cross-validation with linear models.
This exercise is used in the :ref:`cv_estimators_tut` part of the
:ref:`model_selection_tut` section of the :ref:`stat_learn_tut_index`.
"""
from __future__ import print_function
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from sklearn import cross_validation, datasets, linear_model
diabetes = datasets.load_diabetes()
X = diabetes.data[:150]
y = diabetes.target[:150]
lasso = linear_model.Lasso()
alphas = np.logspace(-4, -.5, 30)
scores = list()
scores_std = list()
for alpha in alphas:
lasso.alpha = alpha
this_scores = cross_validation.cross_val_score(lasso, X, y, n_jobs=1)
scores.append(np.mean(this_scores))
scores_std.append(np.std(this_scores))
plt.figure(figsize=(4, 3))
plt.semilogx(alphas, scores)
# plot error lines showing +/- std. errors of the scores
plt.semilogx(alphas, np.array(scores) + np.array(scores_std) / np.sqrt(len(X)),
'b--')
plt.semilogx(alphas, np.array(scores) - np.array(scores_std) / np.sqrt(len(X)),
'b--')
plt.ylabel('CV score')
plt.xlabel('alpha')
plt.axhline(np.max(scores), linestyle='--', color='.5')
##############################################################################
# Bonus: how much can you trust the selection of alpha?
# To answer this question we use the LassoCV object that sets its alpha
# parameter automatically from the data by internal cross-validation (i.e. it
# performs cross-validation on the training data it receives).
# We use external cross-validation to see how much the automatically obtained
# alphas differ across different cross-validation folds.
lasso_cv = linear_model.LassoCV(alphas=alphas)
k_fold = cross_validation.KFold(len(X), 3)
print("Answer to the bonus question:",
"how much can you trust the selection of alpha?")
print()
print("Alpha parameters maximising the generalization score on different")
print("subsets of the data:")
for k, (train, test) in enumerate(k_fold):
lasso_cv.fit(X[train], y[train])
print("[fold {0}] alpha: {1:.5f}, score: {2:.5f}".
format(k, lasso_cv.alpha_, lasso_cv.score(X[test], y[test])))
print()
print("Answer: Not very much since we obtained different alphas for different")
print("subsets of the data and moreover, the scores for these alphas differ")
print("quite substantially.")
plt.show()
|
bsd-3-clause
|
ndingwall/scikit-learn
|
examples/neighbors/plot_nca_classification.py
|
31
|
3112
|
"""
=============================================================================
Comparing Nearest Neighbors with and without Neighborhood Components Analysis
=============================================================================
An example comparing nearest neighbors classification with and without
Neighborhood Components Analysis.
It will plot the class decision boundaries given by a Nearest Neighbors
classifier when using the Euclidean distance on the original features, versus
using the Euclidean distance after the transformation learned by Neighborhood
Components Analysis. The latter aims to find a linear transformation that
maximises the (stochastic) nearest neighbor classification accuracy on the
training set.
"""
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import (KNeighborsClassifier,
NeighborhoodComponentsAnalysis)
from sklearn.pipeline import Pipeline
print(__doc__)
n_neighbors = 1
dataset = datasets.load_iris()
X, y = dataset.data, dataset.target
# we only take two features. We could avoid this ugly
# slicing by using a two-dim dataset
X = X[:, [0, 2]]
X_train, X_test, y_train, y_test = \
train_test_split(X, y, stratify=y, test_size=0.7, random_state=42)
h = .01 # step size in the mesh
# Create color maps
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])
names = ['KNN', 'NCA, KNN']
classifiers = [Pipeline([('scaler', StandardScaler()),
('knn', KNeighborsClassifier(n_neighbors=n_neighbors))
]),
Pipeline([('scaler', StandardScaler()),
('nca', NeighborhoodComponentsAnalysis()),
('knn', KNeighborsClassifier(n_neighbors=n_neighbors))
])
]
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
for name, clf in zip(names, classifiers):
clf.fit(X_train, y_train)
score = clf.score(X_test, y_test)
# Plot the decision boundary. For that, we will assign a color to each
# point in the mesh [x_min, x_max]x[y_min, y_max].
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx, yy, Z, cmap=cmap_light, alpha=.8)
# Plot also the training and testing points
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold, edgecolor='k', s=20)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.title("{} (k = {})".format(name, n_neighbors))
plt.text(0.9, 0.1, '{:.2f}'.format(score), size=15,
ha='center', va='center', transform=plt.gca().transAxes)
plt.show()
|
bsd-3-clause
|
UNR-AERIAL/scikit-learn
|
examples/neighbors/plot_regression.py
|
349
|
1402
|
"""
============================
Nearest Neighbors regression
============================
Demonstrate the resolution of a regression problem
using a k-Nearest Neighbor and the interpolation of the
target using both barycenter and constant weights.
"""
print(__doc__)
# Author: Alexandre Gramfort <[email protected]>
# Fabian Pedregosa <[email protected]>
#
# License: BSD 3 clause (C) INRIA
###############################################################################
# Generate sample data
import numpy as np
import matplotlib.pyplot as plt
from sklearn import neighbors
np.random.seed(0)
X = np.sort(5 * np.random.rand(40, 1), axis=0)
T = np.linspace(0, 5, 500)[:, np.newaxis]
y = np.sin(X).ravel()
# Add noise to targets
y[::5] += 1 * (0.5 - np.random.rand(8))
###############################################################################
# Fit regression model
n_neighbors = 5
for i, weights in enumerate(['uniform', 'distance']):
knn = neighbors.KNeighborsRegressor(n_neighbors, weights=weights)
y_ = knn.fit(X, y).predict(T)
plt.subplot(2, 1, i + 1)
plt.scatter(X, y, c='k', label='data')
plt.plot(T, y_, c='g', label='prediction')
plt.axis('tight')
plt.legend()
plt.title("KNeighborsRegressor (k = %i, weights = '%s')" % (n_neighbors,
weights))
plt.show()
|
bsd-3-clause
|
kagayakidan/scikit-learn
|
sklearn/cluster/setup.py
|
263
|
1449
|
# Author: Alexandre Gramfort <[email protected]>
# License: BSD 3 clause
import os
from os.path import join
import numpy
from sklearn._build_utils import get_blas_info
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration
cblas_libs, blas_info = get_blas_info()
libraries = []
if os.name == 'posix':
cblas_libs.append('m')
libraries.append('m')
config = Configuration('cluster', parent_package, top_path)
config.add_extension('_dbscan_inner',
sources=['_dbscan_inner.cpp'],
include_dirs=[numpy.get_include()],
language="c++")
config.add_extension('_hierarchical',
sources=['_hierarchical.cpp'],
language="c++",
include_dirs=[numpy.get_include()],
libraries=libraries)
config.add_extension(
'_k_means',
libraries=cblas_libs,
sources=['_k_means.c'],
include_dirs=[join('..', 'src', 'cblas'),
numpy.get_include(),
blas_info.pop('include_dirs', [])],
extra_compile_args=blas_info.pop('extra_compile_args', []),
**blas_info
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
|
bsd-3-clause
|
BiaDarkia/scikit-learn
|
examples/calibration/plot_calibration_multiclass.py
|
95
|
6971
|
"""
==================================================
Probability Calibration for 3-class classification
==================================================
This example illustrates how sigmoid calibration changes predicted
probabilities for a 3-class classification problem. Illustrated is the
standard 2-simplex, where the three corners correspond to the three classes.
Arrows point from the probability vectors predicted by an uncalibrated
classifier to the probability vectors predicted by the same classifier after
sigmoid calibration on a hold-out validation set. Colors indicate the true
class of an instance (red: class 1, green: class 2, blue: class 3).
The base classifier is a random forest classifier with 25 base estimators
(trees). If this classifier is trained on all 800 training datapoints, it is
overly confident in its predictions and thus incurs a large log-loss.
Calibrating an identical classifier, which was trained on 600 datapoints, with
method='sigmoid' on the remaining 200 datapoints reduces the confidence of the
predictions, i.e., moves the probability vectors from the edges of the simplex
towards the center. This calibration results in a lower log-loss. Note that an
alternative would have been to increase the number of base estimators which
would have resulted in a similar decrease in log-loss.
"""
print(__doc__)
# Author: Jan Hendrik Metzen <[email protected]>
# License: BSD Style.
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.ensemble import RandomForestClassifier
from sklearn.calibration import CalibratedClassifierCV
from sklearn.metrics import log_loss
np.random.seed(0)
# Generate data
X, y = make_blobs(n_samples=1000, n_features=2, random_state=42,
cluster_std=5.0)
X_train, y_train = X[:600], y[:600]
X_valid, y_valid = X[600:800], y[600:800]
X_train_valid, y_train_valid = X[:800], y[:800]
X_test, y_test = X[800:], y[800:]
# Train uncalibrated random forest classifier on whole train and validation
# data and evaluate on test data
clf = RandomForestClassifier(n_estimators=25)
clf.fit(X_train_valid, y_train_valid)
clf_probs = clf.predict_proba(X_test)
score = log_loss(y_test, clf_probs)
# Train random forest classifier, calibrate on validation data and evaluate
# on test data
clf = RandomForestClassifier(n_estimators=25)
clf.fit(X_train, y_train)
clf_probs = clf.predict_proba(X_test)
sig_clf = CalibratedClassifierCV(clf, method="sigmoid", cv="prefit")
sig_clf.fit(X_valid, y_valid)
sig_clf_probs = sig_clf.predict_proba(X_test)
sig_score = log_loss(y_test, sig_clf_probs)
# Plot changes in predicted probabilities via arrows
plt.figure(0)
colors = ["r", "g", "b"]
for i in range(clf_probs.shape[0]):
plt.arrow(clf_probs[i, 0], clf_probs[i, 1],
sig_clf_probs[i, 0] - clf_probs[i, 0],
sig_clf_probs[i, 1] - clf_probs[i, 1],
color=colors[y_test[i]], head_width=1e-2)
# Plot perfect predictions
plt.plot([1.0], [0.0], 'ro', ms=20, label="Class 1")
plt.plot([0.0], [1.0], 'go', ms=20, label="Class 2")
plt.plot([0.0], [0.0], 'bo', ms=20, label="Class 3")
# Plot boundaries of unit simplex
plt.plot([0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], 'k', label="Simplex")
# Annotate points on the simplex
plt.annotate(r'($\frac{1}{3}$, $\frac{1}{3}$, $\frac{1}{3}$)',
xy=(1.0/3, 1.0/3), xytext=(1.0/3, .23), xycoords='data',
arrowprops=dict(facecolor='black', shrink=0.05),
horizontalalignment='center', verticalalignment='center')
plt.plot([1.0/3], [1.0/3], 'ko', ms=5)
plt.annotate(r'($\frac{1}{2}$, $0$, $\frac{1}{2}$)',
xy=(.5, .0), xytext=(.5, .1), xycoords='data',
arrowprops=dict(facecolor='black', shrink=0.05),
horizontalalignment='center', verticalalignment='center')
plt.annotate(r'($0$, $\frac{1}{2}$, $\frac{1}{2}$)',
xy=(.0, .5), xytext=(.1, .5), xycoords='data',
arrowprops=dict(facecolor='black', shrink=0.05),
horizontalalignment='center', verticalalignment='center')
plt.annotate(r'($\frac{1}{2}$, $\frac{1}{2}$, $0$)',
xy=(.5, .5), xytext=(.6, .6), xycoords='data',
arrowprops=dict(facecolor='black', shrink=0.05),
horizontalalignment='center', verticalalignment='center')
plt.annotate(r'($0$, $0$, $1$)',
xy=(0, 0), xytext=(.1, .1), xycoords='data',
arrowprops=dict(facecolor='black', shrink=0.05),
horizontalalignment='center', verticalalignment='center')
plt.annotate(r'($1$, $0$, $0$)',
xy=(1, 0), xytext=(1, .1), xycoords='data',
arrowprops=dict(facecolor='black', shrink=0.05),
horizontalalignment='center', verticalalignment='center')
plt.annotate(r'($0$, $1$, $0$)',
xy=(0, 1), xytext=(.1, 1), xycoords='data',
arrowprops=dict(facecolor='black', shrink=0.05),
horizontalalignment='center', verticalalignment='center')
# Add grid
plt.grid("off")
for x in [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]:
plt.plot([0, x], [x, 0], 'k', alpha=0.2)
plt.plot([0, 0 + (1-x)/2], [x, x + (1-x)/2], 'k', alpha=0.2)
plt.plot([x, x + (1-x)/2], [0, 0 + (1-x)/2], 'k', alpha=0.2)
plt.title("Change of predicted probabilities after sigmoid calibration")
plt.xlabel("Probability class 1")
plt.ylabel("Probability class 2")
plt.xlim(-0.05, 1.05)
plt.ylim(-0.05, 1.05)
plt.legend(loc="best")
print("Log-loss of")
print(" * uncalibrated classifier trained on 800 datapoints: %.3f "
% score)
print(" * classifier trained on 600 datapoints and calibrated on "
"200 datapoint: %.3f" % sig_score)
# Illustrate calibrator
plt.figure(1)
# generate grid over 2-simplex
p1d = np.linspace(0, 1, 20)
p0, p1 = np.meshgrid(p1d, p1d)
p2 = 1 - p0 - p1
p = np.c_[p0.ravel(), p1.ravel(), p2.ravel()]
p = p[p[:, 2] >= 0]
calibrated_classifier = sig_clf.calibrated_classifiers_[0]
prediction = np.vstack([calibrator.predict(this_p)
for calibrator, this_p in
zip(calibrated_classifier.calibrators_, p.T)]).T
prediction /= prediction.sum(axis=1)[:, None]
# Plot modifications of calibrator
for i in range(prediction.shape[0]):
plt.arrow(p[i, 0], p[i, 1],
prediction[i, 0] - p[i, 0], prediction[i, 1] - p[i, 1],
head_width=1e-2, color=colors[np.argmax(p[i])])
# Plot boundaries of unit simplex
plt.plot([0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], 'k', label="Simplex")
plt.grid("off")
for x in [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]:
plt.plot([0, x], [x, 0], 'k', alpha=0.2)
plt.plot([0, 0 + (1-x)/2], [x, x + (1-x)/2], 'k', alpha=0.2)
plt.plot([x, x + (1-x)/2], [0, 0 + (1-x)/2], 'k', alpha=0.2)
plt.title("Illustration of sigmoid calibrator")
plt.xlabel("Probability class 1")
plt.ylabel("Probability class 2")
plt.xlim(-0.05, 1.05)
plt.ylim(-0.05, 1.05)
plt.show()
|
bsd-3-clause
|
selective-inference/selective-inference
|
doc/learning_examples/HIV/HIV_scale_CV.py
|
3
|
4262
|
import functools
import numpy as np
from scipy.stats import norm as ndist
import regreg.api as rr
# load in the X matrix
from selection.tests.instance import HIV_NRTI
X_full = HIV_NRTI(datafile="NRTI_DATA.txt", standardize=False)[0]
from selection.learning.utils import full_model_inference, liu_inference, pivot_plot
from selection.learning.core import split_sampler, keras_fit
from selection.learning.Rutils import lasso_glmnet, cv_glmnet_lam
from selection.learning.learners import mixture_learner
mixture_learner.scales = [1]*10 + [1.5,2,3,4,5,10]
boot_design = False
def simulate(s=10, signal=(0.5, 1), sigma=2, alpha=0.1, B=15000, seed=0):
# description of statistical problem
n, p = X_full.shape
if boot_design:
idx = np.random.choice(np.arange(n), n, replace=True)
X = X_full[idx] # bootstrap X to make it really an IID sample, i.e. don't condition on X throughout
X += 0.1 * np.std(X) * np.random.standard_normal(X.shape) # to make non-degenerate
else:
X = X_full.copy()
X = X - np.mean(X, 0)[None, :]
X = X / np.std(X, 0)[None, :]
n, p = X.shape
truth = np.zeros(p)
truth[:s] = np.linspace(signal[0], signal[1], s)
np.random.shuffle(truth)
truth /= np.sqrt(n)
truth *= sigma
y = X.dot(truth) + sigma * np.random.standard_normal(n)
XTX = X.T.dot(X)
XTXi = np.linalg.inv(XTX)
resid = y - X.dot(XTXi.dot(X.T.dot(y)))
dispersion = np.linalg.norm(resid)**2 / (n-p)
S = X.T.dot(y)
covS = dispersion * X.T.dot(X)
print(dispersion, sigma**2)
splitting_sampler = split_sampler(X * y[:, None], covS)
def meta_algorithm(X, XTXi, resid, sampler):
S = sampler(scale=0.) # deterministic with scale=0
ynew = X.dot(XTXi).dot(S) + resid # will be ok for n>p and non-degen X
G = lasso_glmnet(X, ynew, *[None]*4)
select = G.select(seed=seed)
return set(list(select[0]))
selection_algorithm = functools.partial(meta_algorithm, X, XTXi, resid)
# run selection algorithm
df = full_model_inference(X,
y,
truth,
selection_algorithm,
splitting_sampler,
success_params=(1, 1),
B=B,
fit_probability=keras_fit,
fit_args={'epochs':10,
'sizes':[100]*5,
'dropout':0.,
'activation':'relu'},
learner_klass=mixture_learner)
if df is not None:
lam_min, lam_1se = cv_glmnet_lam(X.copy(), y.copy(), seed=seed)
lam_min, lam_1se = n * lam_min, n * lam_1se
liu_df = liu_inference(X,
y,
1.00001 * lam_min,
dispersion,
truth,
alpha=alpha)
return pd.merge(df, liu_df, on='variable')
else:
return df
if __name__ == "__main__":
import statsmodels.api as sm
import matplotlib.pyplot as plt
import pandas as pd
U = np.linspace(0, 1, 101)
plt.clf()
init_seed = np.fabs(np.random.standard_normal() * 500)
for i in range(500):
df = simulate(seed=init_seed+i)
csvfile = 'HIV_CV_scale.csv'
outbase = csvfile[:-4]
if df is not None or i > 0:
try:
df = pd.concat([df, pd.read_csv(csvfile)])
except FileNotFoundError:
pass
if df is not None:
df.to_csv(csvfile, index=False)
if len(df['pivot']) > 0:
pivot_ax, lengths_ax = pivot_plot(df, outbase)
liu_pivot = df['liu_pivot']
liu_pivot = liu_pivot[~np.isnan(liu_pivot)]
pivot_ax.plot(U, sm.distributions.ECDF(liu_pivot)(U), 'gray', label='Liu CV',
linewidth=3)
pivot_ax.legend()
fig = pivot_ax.figure
fig.savefig(csvfile[:-4] + '.pdf')
|
bsd-3-clause
|
ltiao/scikit-learn
|
sklearn/covariance/tests/test_covariance.py
|
34
|
11120
|
# Author: Alexandre Gramfort <[email protected]>
# Gael Varoquaux <[email protected]>
# Virgile Fritsch <[email protected]>
#
# License: BSD 3 clause
import numpy as np
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_raises
from sklearn.utils.testing import assert_warns
from sklearn.utils.testing import assert_greater
from sklearn import datasets
from sklearn.covariance import empirical_covariance, EmpiricalCovariance, \
ShrunkCovariance, shrunk_covariance, \
LedoitWolf, ledoit_wolf, ledoit_wolf_shrinkage, OAS, oas
X = datasets.load_diabetes().data
X_1d = X[:, 0]
n_samples, n_features = X.shape
def test_covariance():
# Tests Covariance module on a simple dataset.
# test covariance fit from data
cov = EmpiricalCovariance()
cov.fit(X)
emp_cov = empirical_covariance(X)
assert_array_almost_equal(emp_cov, cov.covariance_, 4)
assert_almost_equal(cov.error_norm(emp_cov), 0)
assert_almost_equal(
cov.error_norm(emp_cov, norm='spectral'), 0)
assert_almost_equal(
cov.error_norm(emp_cov, norm='frobenius'), 0)
assert_almost_equal(
cov.error_norm(emp_cov, scaling=False), 0)
assert_almost_equal(
cov.error_norm(emp_cov, squared=False), 0)
assert_raises(NotImplementedError,
cov.error_norm, emp_cov, norm='foo')
# Mahalanobis distances computation test
mahal_dist = cov.mahalanobis(X)
assert_greater(np.amin(mahal_dist), 0)
# test with n_features = 1
X_1d = X[:, 0].reshape((-1, 1))
cov = EmpiricalCovariance()
cov.fit(X_1d)
assert_array_almost_equal(empirical_covariance(X_1d), cov.covariance_, 4)
assert_almost_equal(cov.error_norm(empirical_covariance(X_1d)), 0)
assert_almost_equal(
cov.error_norm(empirical_covariance(X_1d), norm='spectral'), 0)
# test with one sample
# Create X with 1 sample and 5 features
X_1sample = np.arange(5).reshape(1, 5)
cov = EmpiricalCovariance()
assert_warns(UserWarning, cov.fit, X_1sample)
assert_array_almost_equal(cov.covariance_,
np.zeros(shape=(5, 5), dtype=np.float64))
# test integer type
X_integer = np.asarray([[0, 1], [1, 0]])
result = np.asarray([[0.25, -0.25], [-0.25, 0.25]])
assert_array_almost_equal(empirical_covariance(X_integer), result)
# test centered case
cov = EmpiricalCovariance(assume_centered=True)
cov.fit(X)
assert_array_equal(cov.location_, np.zeros(X.shape[1]))
def test_shrunk_covariance():
# Tests ShrunkCovariance module on a simple dataset.
# compare shrunk covariance obtained from data and from MLE estimate
cov = ShrunkCovariance(shrinkage=0.5)
cov.fit(X)
assert_array_almost_equal(
shrunk_covariance(empirical_covariance(X), shrinkage=0.5),
cov.covariance_, 4)
# same test with shrinkage not provided
cov = ShrunkCovariance()
cov.fit(X)
assert_array_almost_equal(
shrunk_covariance(empirical_covariance(X)), cov.covariance_, 4)
# same test with shrinkage = 0 (<==> empirical_covariance)
cov = ShrunkCovariance(shrinkage=0.)
cov.fit(X)
assert_array_almost_equal(empirical_covariance(X), cov.covariance_, 4)
# test with n_features = 1
X_1d = X[:, 0].reshape((-1, 1))
cov = ShrunkCovariance(shrinkage=0.3)
cov.fit(X_1d)
assert_array_almost_equal(empirical_covariance(X_1d), cov.covariance_, 4)
# test shrinkage coeff on a simple data set (without saving precision)
cov = ShrunkCovariance(shrinkage=0.5, store_precision=False)
cov.fit(X)
assert(cov.precision_ is None)
def test_ledoit_wolf():
# Tests LedoitWolf module on a simple dataset.
# test shrinkage coeff on a simple data set
X_centered = X - X.mean(axis=0)
lw = LedoitWolf(assume_centered=True)
lw.fit(X_centered)
shrinkage_ = lw.shrinkage_
score_ = lw.score(X_centered)
assert_almost_equal(ledoit_wolf_shrinkage(X_centered,
assume_centered=True),
shrinkage_)
assert_almost_equal(ledoit_wolf_shrinkage(X_centered, assume_centered=True,
block_size=6),
shrinkage_)
# compare shrunk covariance obtained from data and from MLE estimate
lw_cov_from_mle, lw_shinkrage_from_mle = ledoit_wolf(X_centered,
assume_centered=True)
assert_array_almost_equal(lw_cov_from_mle, lw.covariance_, 4)
assert_almost_equal(lw_shinkrage_from_mle, lw.shrinkage_)
# compare estimates given by LW and ShrunkCovariance
scov = ShrunkCovariance(shrinkage=lw.shrinkage_, assume_centered=True)
scov.fit(X_centered)
assert_array_almost_equal(scov.covariance_, lw.covariance_, 4)
# test with n_features = 1
X_1d = X[:, 0].reshape((-1, 1))
lw = LedoitWolf(assume_centered=True)
lw.fit(X_1d)
lw_cov_from_mle, lw_shinkrage_from_mle = ledoit_wolf(X_1d,
assume_centered=True)
assert_array_almost_equal(lw_cov_from_mle, lw.covariance_, 4)
assert_almost_equal(lw_shinkrage_from_mle, lw.shrinkage_)
assert_array_almost_equal((X_1d ** 2).sum() / n_samples, lw.covariance_, 4)
# test shrinkage coeff on a simple data set (without saving precision)
lw = LedoitWolf(store_precision=False, assume_centered=True)
lw.fit(X_centered)
assert_almost_equal(lw.score(X_centered), score_, 4)
assert(lw.precision_ is None)
# Same tests without assuming centered data
# test shrinkage coeff on a simple data set
lw = LedoitWolf()
lw.fit(X)
assert_almost_equal(lw.shrinkage_, shrinkage_, 4)
assert_almost_equal(lw.shrinkage_, ledoit_wolf_shrinkage(X))
assert_almost_equal(lw.shrinkage_, ledoit_wolf(X)[1])
assert_almost_equal(lw.score(X), score_, 4)
# compare shrunk covariance obtained from data and from MLE estimate
lw_cov_from_mle, lw_shinkrage_from_mle = ledoit_wolf(X)
assert_array_almost_equal(lw_cov_from_mle, lw.covariance_, 4)
assert_almost_equal(lw_shinkrage_from_mle, lw.shrinkage_)
# compare estimates given by LW and ShrunkCovariance
scov = ShrunkCovariance(shrinkage=lw.shrinkage_)
scov.fit(X)
assert_array_almost_equal(scov.covariance_, lw.covariance_, 4)
# test with n_features = 1
X_1d = X[:, 0].reshape((-1, 1))
lw = LedoitWolf()
lw.fit(X_1d)
lw_cov_from_mle, lw_shinkrage_from_mle = ledoit_wolf(X_1d)
assert_array_almost_equal(lw_cov_from_mle, lw.covariance_, 4)
assert_almost_equal(lw_shinkrage_from_mle, lw.shrinkage_)
assert_array_almost_equal(empirical_covariance(X_1d), lw.covariance_, 4)
# test with one sample
# warning should be raised when using only 1 sample
X_1sample = np.arange(5).reshape(1, 5)
lw = LedoitWolf()
assert_warns(UserWarning, lw.fit, X_1sample)
assert_array_almost_equal(lw.covariance_,
np.zeros(shape=(5, 5), dtype=np.float64))
# test shrinkage coeff on a simple data set (without saving precision)
lw = LedoitWolf(store_precision=False)
lw.fit(X)
assert_almost_equal(lw.score(X), score_, 4)
assert(lw.precision_ is None)
def test_ledoit_wolf_large():
# test that ledoit_wolf doesn't error on data that is wider than block_size
rng = np.random.RandomState(0)
# use a number of features that is larger than the block-size
X = rng.normal(size=(10, 20))
lw = LedoitWolf(block_size=10).fit(X)
# check that covariance is about diagonal (random normal noise)
assert_almost_equal(lw.covariance_, np.eye(20), 0)
cov = lw.covariance_
# check that the result is consistent with not splitting data into blocks.
lw = LedoitWolf(block_size=25).fit(X)
assert_almost_equal(lw.covariance_, cov)
def test_oas():
# Tests OAS module on a simple dataset.
# test shrinkage coeff on a simple data set
X_centered = X - X.mean(axis=0)
oa = OAS(assume_centered=True)
oa.fit(X_centered)
shrinkage_ = oa.shrinkage_
score_ = oa.score(X_centered)
# compare shrunk covariance obtained from data and from MLE estimate
oa_cov_from_mle, oa_shinkrage_from_mle = oas(X_centered,
assume_centered=True)
assert_array_almost_equal(oa_cov_from_mle, oa.covariance_, 4)
assert_almost_equal(oa_shinkrage_from_mle, oa.shrinkage_)
# compare estimates given by OAS and ShrunkCovariance
scov = ShrunkCovariance(shrinkage=oa.shrinkage_, assume_centered=True)
scov.fit(X_centered)
assert_array_almost_equal(scov.covariance_, oa.covariance_, 4)
# test with n_features = 1
X_1d = X[:, 0:1]
oa = OAS(assume_centered=True)
oa.fit(X_1d)
oa_cov_from_mle, oa_shinkrage_from_mle = oas(X_1d, assume_centered=True)
assert_array_almost_equal(oa_cov_from_mle, oa.covariance_, 4)
assert_almost_equal(oa_shinkrage_from_mle, oa.shrinkage_)
assert_array_almost_equal((X_1d ** 2).sum() / n_samples, oa.covariance_, 4)
# test shrinkage coeff on a simple data set (without saving precision)
oa = OAS(store_precision=False, assume_centered=True)
oa.fit(X_centered)
assert_almost_equal(oa.score(X_centered), score_, 4)
assert(oa.precision_ is None)
# Same tests without assuming centered data--------------------------------
# test shrinkage coeff on a simple data set
oa = OAS()
oa.fit(X)
assert_almost_equal(oa.shrinkage_, shrinkage_, 4)
assert_almost_equal(oa.score(X), score_, 4)
# compare shrunk covariance obtained from data and from MLE estimate
oa_cov_from_mle, oa_shinkrage_from_mle = oas(X)
assert_array_almost_equal(oa_cov_from_mle, oa.covariance_, 4)
assert_almost_equal(oa_shinkrage_from_mle, oa.shrinkage_)
# compare estimates given by OAS and ShrunkCovariance
scov = ShrunkCovariance(shrinkage=oa.shrinkage_)
scov.fit(X)
assert_array_almost_equal(scov.covariance_, oa.covariance_, 4)
# test with n_features = 1
X_1d = X[:, 0].reshape((-1, 1))
oa = OAS()
oa.fit(X_1d)
oa_cov_from_mle, oa_shinkrage_from_mle = oas(X_1d)
assert_array_almost_equal(oa_cov_from_mle, oa.covariance_, 4)
assert_almost_equal(oa_shinkrage_from_mle, oa.shrinkage_)
assert_array_almost_equal(empirical_covariance(X_1d), oa.covariance_, 4)
# test with one sample
# warning should be raised when using only 1 sample
X_1sample = np.arange(5).reshape(1, 5)
oa = OAS()
assert_warns(UserWarning, oa.fit, X_1sample)
assert_array_almost_equal(oa.covariance_,
np.zeros(shape=(5, 5), dtype=np.float64))
# test shrinkage coeff on a simple data set (without saving precision)
oa = OAS(store_precision=False)
oa.fit(X)
assert_almost_equal(oa.score(X), score_, 4)
assert(oa.precision_ is None)
|
bsd-3-clause
|
ycool/apollo
|
modules/tools/mapshow/libs/plot_planning.py
|
3
|
3641
|
#!/usr/bin/env python
###############################################################################
# Copyright 2017 The Apollo 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.
###############################################################################
import argparse
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from cyber_py import cyber
from modules.planning.proto import planning_pb2
from subplot_st_main import StMainSubplot
from subplot_path import PathSubplot
from subplot_sl_main import SlMainSubplot
from subplot_st_speed import StSpeedSubplot
from subplot_speed import SpeedSubplot
from localization import Localization
from planning import Planning
planning = Planning()
localization = Localization()
def update(frame_number):
# st_main_subplot.show(planning)
# st_speed_subplot.show(planning)
map_path_subplot.show(planning, localization)
dp_st_main_subplot.show(planning)
qp_st_main_subplot.show(planning)
speed_subplot.show(planning)
sl_main_subplot.show(planning)
st_speed_subplot.show(planning)
def planning_callback(planning_pb):
planning.update_planning_pb(planning_pb)
localization.update_localization_pb(
planning_pb.debug.planning_data.adc_position)
planning.compute_st_data()
planning.compute_sl_data()
planning.compute_path_data()
planning.compute_speed_data()
planning.compute_init_point()
def add_listener():
planning_sub = cyber.Node("st_plot")
planning_sub.create_reader('/apollo/planning', planning_pb2.ADCTrajectory,
planning_callback)
def press_key(event):
if event.key == '+' or event.key == '=':
map_path_subplot.zoom_in()
if event.key == '-' or event.key == '_':
map_path_subplot.zoom_out()
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="plot_planning is a tool to display "
"planning trajs on a map.",
prog="plot_planning_old.py")
parser.add_argument(
"-m",
"--map",
action="store",
type=str,
required=False,
default=None,
help="Specify the map file in txt or binary format")
args = parser.parse_args()
cyber.init()
add_listener()
fig = plt.figure()
fig.canvas.mpl_connect('key_press_event', press_key)
ax = plt.subplot2grid((3, 3), (0, 0), rowspan=2, colspan=2)
map_path_subplot = PathSubplot(ax, args.map)
ax1 = plt.subplot2grid((3, 3), (0, 2))
speed_subplot = SpeedSubplot(ax1)
ax2 = plt.subplot2grid((3, 3), (2, 2))
dp_st_main_subplot = StMainSubplot(ax2, 'QpSplineStSpeedOptimizer')
ax3 = plt.subplot2grid((3, 3), (1, 2))
qp_st_main_subplot = StMainSubplot(ax3, 'DpStSpeedOptimizer')
ax4 = plt.subplot2grid((3, 3), (2, 0), colspan=1)
sl_main_subplot = SlMainSubplot(ax4)
ax5 = plt.subplot2grid((3, 3), (2, 1), colspan=1)
st_speed_subplot = StSpeedSubplot(ax5, 'QpSplineStSpeedOptimizer')
ani = animation.FuncAnimation(fig, update, interval=100)
ax.axis('equal')
plt.show()
cyber.shutdown()
|
apache-2.0
|
uber-common/deck.gl
|
bindings/pydeck/examples/contour_layer.py
|
1
|
2239
|
"""
ContourLayer
===========
Location of livestock raised in New Mexico in the United States in 2006,
via the United Nations and FAOSTAT, with the source data viewable here: http://www.fao.org/faostat/en/
Locations for poultry are viewable in blue and cattle are in orange.
Overlaid with the satellite imagery from Mapbox to highlight the how terrain affects agriculture.
"""
import pandas as pd
import pydeck as pdk
CATTLE_DATA = "https://raw.githubusercontent.com/ajduberstein/geo_datasets/master/nm_cattle.csv"
POULTRY_DATA = "https://raw.githubusercontent.com/ajduberstein/geo_datasets/master/nm_chickens.csv"
HEADER = ["lng", "lat", "weight"]
cattle_df = pd.read_csv(CATTLE_DATA, header=None)
poultry_df = pd.read_csv(POULTRY_DATA, header=None)
cattle_df.columns = HEADER
poultry_df.columns = HEADER
view = pdk.data_utils.compute_view(cattle_df[["lng", "lat"]])
p75, p90, p99 = cattle_df["weight"].quantile([0.75, 0.9, 0.99])
STROKE_WIDTH = 5
CONTOURS_0 = [
{"threshold": p75, "color": [0, 238, 224], "strokeWidth": STROKE_WIDTH},
{"threshold": p90, "color": [0, 180, 240], "strokeWidth": STROKE_WIDTH},
{"threshold": p99, "color": [0, 0, 240], "strokeWidth": STROKE_WIDTH},
]
p75, p90, p99 = poultry_df["weight"].quantile([0.75, 0.9, 0.99])
CONTOURS_1 = [
{"threshold": p75, "color": [245, 245, 0], "strokeWidth": STROKE_WIDTH, "zIndex": 1},
{"threshold": p99, "color": [247, 150, 0], "strokeWidth": STROKE_WIDTH, "zIndex": 10},
]
# in meters
CELL_SIZE = 3000
cattle = pdk.Layer(
"ContourLayer",
data=cattle_df,
get_position=["lng", "lat"],
contours=CONTOURS_0,
cell_size=CELL_SIZE,
aggregation=pdk.types.String("MEAN"),
get_weight="weight",
pickable=True,
)
poultry = pdk.Layer(
"ContourLayer",
data=poultry_df,
get_position=["lng", "lat"],
contours=CONTOURS_1,
cell_size=CELL_SIZE,
aggregation=pdk.types.String("MEAN"),
get_weight="weight",
pickable=True,
)
r = pdk.Deck(
layers=[cattle, poultry],
initial_view_state=view,
map_provider="mapbox",
map_style=pdk.map_styles.SATELLITE,
tooltip={"text": "Concentration of cattle in blue, concentration of poultry in orange"},
)
r.to_html("contour_layer.html")
|
mit
|
FEniCS/dolfin
|
demo/undocumented/coordinates/python/demo_coordinates.py
|
1
|
1715
|
"""This demo program demonstrates how to manipulate (higher-order) mesh
coordinates."""
# Copyright (C) 2016 Jan Blechta
#
# This file is part of DOLFIN.
#
# DOLFIN is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DOLFIN 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with DOLFIN. If not, see <http://www.gnu.org/licenses/>.
from dolfin import *
import matplotlib.pyplot as plt
# Create mesh
comm = mpi_comm_world()
mesh = UnitDiscMesh.create(comm, 20, 2, 2)
plt.figure()
plot(mesh)
# Fetch coordinate function
C = FunctionSpace(mesh, mesh.ufl_coordinate_element())
c = Function(C)
get_coordinates(c, mesh.geometry())
# Deform coordinates harmonically subject to BC
u, v = TrialFunction(C), TestFunction(C)
a = inner(grad(u), grad(v))*dx
L = dot(Constant((0, 0)), v)*dx
bc1 = DirichletBC(C, (-1, -1), "x[0] < -0.5")
bc2 = DirichletBC(C, c, "x[0] >= -0.5")
displacement = Function(C)
solve(a == L, displacement, [bc1, bc2])
c_vec = c.vector()
c_vec += displacement.vector()
# Set coordinates
set_coordinates(mesh.geometry(), c)
plt.figure()
plot(mesh)
# We can create (cubic) mesh from function
C3 = VectorFunctionSpace(mesh, "Lagrange", 4)
c3 = interpolate(c, C3)
mesh3 = create_mesh(c3)
plt.figure()
plot(mesh3)
# Display plots
plt.show()
|
lgpl-3.0
|
DSLituiev/scikit-learn
|
sklearn/neighbors/regression.py
|
7
|
10997
|
"""Nearest Neighbor Regression"""
# Authors: Jake Vanderplas <[email protected]>
# Fabian Pedregosa <[email protected]>
# Alexandre Gramfort <[email protected]>
# Sparseness support by Lars Buitinck
# Multi-output support by Arnaud Joly <[email protected]>
#
# License: BSD 3 clause (C) INRIA, University of Amsterdam
import numpy as np
from .base import _get_weights, _check_weights, NeighborsBase, KNeighborsMixin
from .base import RadiusNeighborsMixin, SupervisedFloatMixin
from ..base import RegressorMixin
from ..utils import check_array
class KNeighborsRegressor(NeighborsBase, KNeighborsMixin,
SupervisedFloatMixin,
RegressorMixin):
"""Regression based on k-nearest neighbors.
The target is predicted by local interpolation of the targets
associated of the nearest neighbors in the training set.
Read more in the :ref:`User Guide <regression>`.
Parameters
----------
n_neighbors : int, optional (default = 5)
Number of neighbors to use by default for :meth:`k_neighbors` queries.
weights : str or callable
weight function used in prediction. Possible values:
- 'uniform' : uniform weights. All points in each neighborhood
are weighted equally.
- 'distance' : weight points by the inverse of their distance.
in this case, closer neighbors of a query point will have a
greater influence than neighbors which are further away.
- [callable] : a user-defined function which accepts an
array of distances, and returns an array of the same shape
containing the weights.
Uniform weights are used by default.
algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, optional
Algorithm used to compute the nearest neighbors:
- 'ball_tree' will use :class:`BallTree`
- 'kd_tree' will use :class:`KDtree`
- 'brute' will use a brute-force search.
- 'auto' will attempt to decide the most appropriate algorithm
based on the values passed to :meth:`fit` method.
Note: fitting on sparse input will override the setting of
this parameter, using brute force.
leaf_size : int, optional (default = 30)
Leaf size passed to BallTree or KDTree. This can affect the
speed of the construction and query, as well as the memory
required to store the tree. The optimal value depends on the
nature of the problem.
metric : string or DistanceMetric object (default='minkowski')
the distance metric to use for the tree. The default metric is
minkowski, and with p=2 is equivalent to the standard Euclidean
metric. See the documentation of the DistanceMetric class for a
list of available metrics.
p : integer, optional (default = 2)
Power parameter for the Minkowski metric. When p = 1, this is
equivalent to using manhattan_distance (l1), and euclidean_distance
(l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.
metric_params : dict, optional (default = None)
Additional keyword arguments for the metric function.
n_jobs : int, optional (default = 1)
The number of parallel jobs to run for neighbors search.
If ``-1``, then the number of jobs is set to the number of CPU cores.
Doesn't affect :meth:`fit` method.
Examples
--------
>>> X = [[0], [1], [2], [3]]
>>> y = [0, 0, 1, 1]
>>> from sklearn.neighbors import KNeighborsRegressor
>>> neigh = KNeighborsRegressor(n_neighbors=2)
>>> neigh.fit(X, y) # doctest: +ELLIPSIS
KNeighborsRegressor(...)
>>> print(neigh.predict([[1.5]]))
[ 0.5]
See also
--------
NearestNeighbors
RadiusNeighborsRegressor
KNeighborsClassifier
RadiusNeighborsClassifier
Notes
-----
See :ref:`Nearest Neighbors <neighbors>` in the online documentation
for a discussion of the choice of ``algorithm`` and ``leaf_size``.
.. warning::
Regarding the Nearest Neighbors algorithms, if it is found that two
neighbors, neighbor `k+1` and `k`, have identical distances but
but different labels, the results will depend on the ordering of the
training data.
http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm
"""
def __init__(self, n_neighbors=5, weights='uniform',
algorithm='auto', leaf_size=30,
p=2, metric='minkowski', metric_params=None, n_jobs=1,
**kwargs):
self._init_params(n_neighbors=n_neighbors,
algorithm=algorithm,
leaf_size=leaf_size, metric=metric, p=p,
metric_params=metric_params, n_jobs=n_jobs, **kwargs)
self.weights = _check_weights(weights)
def predict(self, X):
"""Predict the target for the provided data
Parameters
----------
X : array-like, shape (n_query, n_features), \
or (n_query, n_indexed) if metric == 'precomputed'
Test samples.
Returns
-------
y : array of int, shape = [n_samples] or [n_samples, n_outputs]
Target values
"""
X = check_array(X, accept_sparse='csr')
neigh_dist, neigh_ind = self.kneighbors(X)
weights = _get_weights(neigh_dist, self.weights)
_y = self._y
if _y.ndim == 1:
_y = _y.reshape((-1, 1))
if weights is None:
y_pred = np.mean(_y[neigh_ind], axis=1)
else:
y_pred = np.empty((X.shape[0], _y.shape[1]), dtype=np.float64)
denom = np.sum(weights, axis=1)
for j in range(_y.shape[1]):
num = np.sum(_y[neigh_ind, j] * weights, axis=1)
y_pred[:, j] = num / denom
if self._y.ndim == 1:
y_pred = y_pred.ravel()
return y_pred
class RadiusNeighborsRegressor(NeighborsBase, RadiusNeighborsMixin,
SupervisedFloatMixin,
RegressorMixin):
"""Regression based on neighbors within a fixed radius.
The target is predicted by local interpolation of the targets
associated of the nearest neighbors in the training set.
Read more in the :ref:`User Guide <regression>`.
Parameters
----------
radius : float, optional (default = 1.0)
Range of parameter space to use by default for :meth`radius_neighbors`
queries.
weights : str or callable
weight function used in prediction. Possible values:
- 'uniform' : uniform weights. All points in each neighborhood
are weighted equally.
- 'distance' : weight points by the inverse of their distance.
in this case, closer neighbors of a query point will have a
greater influence than neighbors which are further away.
- [callable] : a user-defined function which accepts an
array of distances, and returns an array of the same shape
containing the weights.
Uniform weights are used by default.
algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, optional
Algorithm used to compute the nearest neighbors:
- 'ball_tree' will use :class:`BallTree`
- 'kd_tree' will use :class:`KDtree`
- 'brute' will use a brute-force search.
- 'auto' will attempt to decide the most appropriate algorithm
based on the values passed to :meth:`fit` method.
Note: fitting on sparse input will override the setting of
this parameter, using brute force.
leaf_size : int, optional (default = 30)
Leaf size passed to BallTree or KDTree. This can affect the
speed of the construction and query, as well as the memory
required to store the tree. The optimal value depends on the
nature of the problem.
metric : string or DistanceMetric object (default='minkowski')
the distance metric to use for the tree. The default metric is
minkowski, and with p=2 is equivalent to the standard Euclidean
metric. See the documentation of the DistanceMetric class for a
list of available metrics.
p : integer, optional (default = 2)
Power parameter for the Minkowski metric. When p = 1, this is
equivalent to using manhattan_distance (l1), and euclidean_distance
(l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.
metric_params : dict, optional (default = None)
Additional keyword arguments for the metric function.
Examples
--------
>>> X = [[0], [1], [2], [3]]
>>> y = [0, 0, 1, 1]
>>> from sklearn.neighbors import RadiusNeighborsRegressor
>>> neigh = RadiusNeighborsRegressor(radius=1.0)
>>> neigh.fit(X, y) # doctest: +ELLIPSIS
RadiusNeighborsRegressor(...)
>>> print(neigh.predict([[1.5]]))
[ 0.5]
See also
--------
NearestNeighbors
KNeighborsRegressor
KNeighborsClassifier
RadiusNeighborsClassifier
Notes
-----
See :ref:`Nearest Neighbors <neighbors>` in the online documentation
for a discussion of the choice of ``algorithm`` and ``leaf_size``.
http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm
"""
def __init__(self, radius=1.0, weights='uniform',
algorithm='auto', leaf_size=30,
p=2, metric='minkowski', metric_params=None, **kwargs):
self._init_params(radius=radius,
algorithm=algorithm,
leaf_size=leaf_size,
p=p, metric=metric, metric_params=metric_params,
**kwargs)
self.weights = _check_weights(weights)
def predict(self, X):
"""Predict the target for the provided data
Parameters
----------
X : array-like, shape (n_query, n_features), \
or (n_query, n_indexed) if metric == 'precomputed'
Test samples.
Returns
-------
y : array of int, shape = [n_samples] or [n_samples, n_outputs]
Target values
"""
X = check_array(X, accept_sparse='csr')
neigh_dist, neigh_ind = self.radius_neighbors(X)
weights = _get_weights(neigh_dist, self.weights)
_y = self._y
if _y.ndim == 1:
_y = _y.reshape((-1, 1))
if weights is None:
y_pred = np.array([np.mean(_y[ind, :], axis=0)
for ind in neigh_ind])
else:
y_pred = np.array([(np.average(_y[ind, :], axis=0,
weights=weights[i]))
for (i, ind) in enumerate(neigh_ind)])
if self._y.ndim == 1:
y_pred = y_pred.ravel()
return y_pred
|
bsd-3-clause
|
SiLab-Bonn/Scarce
|
scarce/examples/transient_3D.py
|
1
|
4824
|
''' Example that moves e-h pairs in a 3D sensor.
Calculates the induced charge from e-h pairs drifting
through the silicon.
.. WARNING::
The 3D field is low between pixels. Thus diffusion
should be activated to leave this field minima quickly
to give reasonable results.
'''
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from scipy import integrate
from scarce import plot, solver, sensor
def transient_3D():
n_pixel_x, n_pixel_y = 3, 3
width_x = 250.
width_y = 50.
radius = 6.
nD = 2 # Number of columns per pixel
n_eff = 1e12
T = 300
V_bias = -20.
V_readout = 0.
pot_w_descr, pot_descr, geom_descr = sensor.sensor_3D(n_eff=n_eff,
V_bias=V_bias,
V_readout=V_readout,
temperature=T,
n_pixel_x=n_pixel_x,
n_pixel_y=n_pixel_y,
width_x=width_x,
width_y=width_y,
radius=radius,
nD=nD,
resolution=80,
smoothing=0.1)
# Start parameters of e-h pairs
# 10 pairs per position
xx, yy = np.meshgrid(np.linspace(-width_x / 2., width_x / 2., 25), # x
np.repeat(np.linspace(-width_y / 2.,
width_y / 2., 5), 10), # y
sparse=False) # All combinations of x / y
p0 = np.array([xx.ravel(), yy.ravel()])
# Initial charge
q0 = np.ones(p0.shape[1])
# Time steps
dt = 0.001 # [ns]
n_steps = 10000
t = np.arange(n_steps) * dt
dd = solver.DriftDiffusionSolver(pot_descr, pot_w_descr,
geom_descr=geom_descr,
T=T,
diffusion=True)
traj_e, traj_h, I_ind_e, I_ind_h, T, I_ind_tot, Q_ind_e_tot, Q_ind_h_tot = dd.solve(p0, q0, dt, n_steps)
I_ind_e[np.isnan(I_ind_e)] = 0.
I_ind_h[np.isnan(I_ind_h)] = 0.
Q_ind_e = integrate.cumtrapz(I_ind_e, T, axis=0, initial=0)
Q_ind_h = integrate.cumtrapz(I_ind_h, T, axis=0, initial=0)
for i in (5, 13):
plt.plot(T[:, i], Q_ind_e[:, i], color='blue',
label='Electrons')
plt.plot(T[:, i], Q_ind_h[:, i], color='red',
label='Holes')
plt.plot(T[:, i], (Q_ind_e + Q_ind_h)[:, i],
color='magenta', label='Sum')
plt.plot(plt.xlim(), [(Q_ind_e_tot + Q_ind_h_tot)[i]] * 2, '-', color='magenta')
plt.legend(loc=0)
plt.xlabel('Time [ns]')
plt.ylabel('Charge normalized to 1')
plt.grid()
plt.title('Induced charge of drifting e-h pairs, start pos. %d/%d um' %
(p0[0, i], p0[1, i]))
plt.show()
# Plot numerical result in 2D with particle animation
fig = plt.figure()
plot.get_3D_sensor_plot(fig, width_x, width_y,
radius, nD,
n_pixel_x, n_pixel_y,
V_bias=V_bias, V_readout=V_readout,
pot_func=pot_descr.get_potential_smooth,
field_func=pot_descr.get_field,
# Comment in if you want to see the mesh
mesh=None, # potential.mesh,
title='Potential and field of a 3D sensor, '\
'%dx%d pixel matrix, numerical solution' % \
(n_pixel_x, n_pixel_y))
# Create animation
frames = 50
init, animate = plot.animate_drift_diffusion(fig, T=T, pe=traj_e,
ph=traj_h, dt=t.max() /
frames,
n_steps=frames)
ani = animation.FuncAnimation(fig=fig, func=animate,
blit=True, init_func=init, frames=frames,
interval=5000 / frames)
# ani.save('Example_3D_drift.gif', dpi=80, writer='imagemagick')
plt.show()
if __name__ == '__main__':
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S")
transient_3D()
|
mit
|
eastmallingresearch/crosslink
|
scripts/compare_multimaps2.py
|
1
|
1525
|
#!/usr/bin/python
#Crosslink Copyright (C) 2016 NIAB EMR see included NOTICE file for details
'''
plot marker position in multiple maps versus average position across all maps
assumes markers always map to same lg in everymap
csvs must have first three columns as:
marker name,linkage group,centimorgan position
'''
import sys
import numpy as np
import matplotlib.pyplot as plt
from mapping_funcs2 import *
order = []
for x in xrange(1,8):
for y in 'ABCD':
order.append(str(x)+y)
map_list = sys.argv[1:]
maps = [loadmap(x,order=order) for x in map_list]
pos = {}
for mp in maps:
for uid in mp.loci:
if not uid in pos: pos[uid] = []
pos[uid].append(mp.loci[uid].relpos)
mean = {}
for uid in pos:
mean[uid] = sum(pos[uid]) / len(pos[uid])
xposn = []
yposn = []
col = []
for i,mp in enumerate(maps):
for uid in mp.loci:
marker = mp.loci[uid]
lg = mp.groups[marker.lg]
xposn.append(mean[uid] + lg.order)
yposn.append(marker.relpos + lg.order)
col.append(i)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(xposn,yposn,c=col,s=10,lw=0)
lines = range(len(order)+1)
ax.vlines(lines, 0.0, lines[-1])
ax.hlines(lines, 0.0, lines[-1])
ax.set_xlim([0.0,lines[-1]])
ax.set_ylim([0.0,lines[-1]])
#ax.set_xlabel(refmap)
#ax.set_ylabel(conf.map2)
fs=10.0
for i,lg in enumerate(order):
ax.text(i+0.5,-1.0,lg,fontsize=fs,rotation='vertical')
ax.text(-1.0,i+0.5,lg,fontsize=fs)
ax.text(i,i+0.9,lg,fontsize=fs)
plt.show()
|
gpl-2.0
|
tcstewar/2015-Embodied_Benchmarks
|
code/benchmark.py
|
1
|
5094
|
import argparse
import importlib
import inspect
import logging
import os
import shelve
import time
import matplotlib.pyplot
import numpy as np
import nengo
def find_offset(a, b):
assert len(a) == len(b)
corr = np.correlate(a, b, 'full')
index = np.argmax(corr[len(a):])
return index
class Benchmark(object):
def __init__(self):
self.parser = argparse.ArgumentParser(
description='Nengo benchmark: %s' %
self.__class__.__name__)
self.param_names = []
self.hidden_params = []
self.params()
self.fixed_params()
def default(self, description, **kwarg):
if len(kwarg) != 1:
raise ValueException('Must specify exactly one parameter')
k, v = kwarg.items()[0]
if k in self.param_names:
raise ValueException('Cannot redefine parameter "%s"' % k)
if v is False:
self.parser.add_argument('--%s' % k, action='store_true',
help=description)
else:
self.parser.add_argument('--%s' % k, type=type(v), default=v,
help=description)
self.param_names.append(k)
def fixed_params(self):
self.default('backend to use', backend='nengo')
self.default('time step', dt=0.001)
self.default('random number seed', seed=1)
self.default('data directory', data_dir='data')
self.default('display figures', show_figs=False)
self.default('do not generate figures', no_figs=False)
self.default('enable debug messages', debug=False)
self.hidden_params.extend(['data_dir', 'show_figs',
'no_figs', 'debug'])
def process_args(self, allow_cmdline=True, **kwargs):
if len(kwargs) == 0 and allow_cmdline:
args = self.parser.parse_args()
else:
args = argparse.Namespace()
for k in self.param_names:
v = kwargs.get(k, self.parser.get_default(k))
setattr(args, k, v)
name = self.__class__.__name__
text = []
self.args_text = []
for k in self.param_names:
if k not in self.hidden_params:
text.append('%s=%s' % (k, getattr(args, k)))
self.args_text.append('_%s = %r' % (k, getattr(args, k)))
filename = name + '#' + ','.join(text)
uid = np.random.randint(0x7FFFFFFF)
filename = name + '#' + time.strftime('%Y%m%d-%H%M%S')+('-%08x' % uid)
return args, filename
def make_model(self, **kwargs):
p, fn = self.process_args(allow_cmdline=False, **kwargs)
np.random.seed(p.seed)
model = self.model(p)
return model
def record_speed(self, t):
now = time.time()
self.sim_speed = t / (now - self.start_time)
def run(self, **kwargs):
p, fn = self.process_args(**kwargs)
if p.debug:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.ERROR)
print('running %s' % fn)
np.random.seed(p.seed)
model = self.model(p)
module = importlib.import_module(p.backend)
Simulator = module.Simulator
if p.backend == 'nengo_spinnaker':
import nengo_spinnaker
nengo_spinnaker.add_spinnaker_params(model.config)
for node in model.all_nodes:
if (node.size_in == 0 and
node.size_out > 0 and
callable(node.output)):
model.config[node].function_of_time = True
if not p.no_figs or p.show_figs:
plt = matplotlib.pyplot
else:
plt = None
sim = Simulator(model, dt=p.dt)
self.start_time = time.time()
self.sim_speed = None
result = self.evaluate(p, sim, plt)
if p.backend == 'nengo_spinnaker':
sim.close()
if self.sim_speed is not None and 'sim_speed' not in result:
result['sim_speed'] = self.sim_speed
text = []
for k, v in sorted(result.items()):
text.append('%s = %s' % (k, repr(v)))
if plt is not None:
plt.suptitle(fn.replace('#', '\n') +'\n' + '\n'.join(text),
fontsize=8)
plt.figtext(0.12,0.12,'\n'.join(self.args_text))
text = self.args_text + text
text = '\n'.join(text)
if not os.path.exists(p.data_dir):
os.mkdir(p.data_dir)
fn = os.path.join(p.data_dir, fn)
if not p.no_figs:
plt.savefig(fn + '.png', dpi=300)
with open(fn + '.txt', 'w') as f:
f.write(text)
print(text)
db = shelve.open(fn + '.db')
db['trange'] = sim.trange()
for k, v in inspect.getmembers(self):
if isinstance(v, nengo.Probe):
db[k] = sim.data[v]
db.close()
if p.show_figs:
plt.show()
return result
|
gpl-2.0
|
JWDebelius/scikit-bio
|
skbio/stats/distance/tests/test_anosim.py
|
1
|
4403
|
#! /usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ----------------------------------------------------------------------------
from __future__ import absolute_import, division, print_function
from future.utils.six import StringIO
from unittest import TestCase, main
import numpy as np
import numpy.testing as npt
import pandas as pd
from skbio import DistanceMatrix
from skbio.stats.distance import ANOSIM
class ANOSIMTests(TestCase):
"""All results were verified with R (vegan::anosim)."""
def setUp(self):
# Distance matrices with and without ties in the ranks, with 2 groups
# of equal size.
dm_ids = ['s1', 's2', 's3', 's4']
grouping_equal = ['Control', 'Control', 'Fast', 'Fast']
df = pd.read_csv(
StringIO('ID,Group\ns2,Control\ns3,Fast\ns4,Fast\ns5,Control\n'
's1,Control'), index_col=0)
self.dm_ties = DistanceMatrix([[0, 1, 1, 4],
[1, 0, 3, 2],
[1, 3, 0, 3],
[4, 2, 3, 0]], dm_ids)
self.dm_no_ties = DistanceMatrix([[0, 1, 5, 4],
[1, 0, 3, 2],
[5, 3, 0, 3],
[4, 2, 3, 0]], dm_ids)
# Test with 3 groups of unequal size. This data also generates a
# negative R statistic.
grouping_unequal = ['Control', 'Treatment1', 'Treatment2',
'Treatment1', 'Control', 'Control']
self.dm_unequal = DistanceMatrix(
[[0.0, 1.0, 0.1, 0.5678, 1.0, 1.0],
[1.0, 0.0, 0.002, 0.42, 0.998, 0.0],
[0.1, 0.002, 0.0, 1.0, 0.123, 1.0],
[0.5678, 0.42, 1.0, 0.0, 0.123, 0.43],
[1.0, 0.998, 0.123, 0.123, 0.0, 0.5],
[1.0, 0.0, 1.0, 0.43, 0.5, 0.0]],
['s1', 's2', 's3', 's4', 's5', 's6'])
self.anosim_ties = ANOSIM(self.dm_ties, grouping_equal)
self.anosim_no_ties = ANOSIM(self.dm_no_ties, grouping_equal)
self.anosim_ties_df = ANOSIM(self.dm_ties, df, column='Group')
self.anosim_unequal = ANOSIM(self.dm_unequal, grouping_unequal)
def test_call_ties(self):
# Ensure we get the same results if we rerun the method on the same
# object. Also ensure we get the same results if we run the method
# using a grouping vector or a data frame with equivalent groupings.
for inst in self.anosim_ties, self.anosim_ties_df:
for trial in range(2):
np.random.seed(0)
obs = inst()
self.assertEqual(obs.sample_size, 4)
npt.assert_array_equal(obs.groups,
['Control', 'Fast'])
self.assertAlmostEqual(obs.statistic, 0.25)
self.assertAlmostEqual(obs.p_value, 0.671)
self.assertEqual(obs.permutations, 999)
def test_call_no_ties(self):
np.random.seed(0)
obs = self.anosim_no_ties()
self.assertEqual(obs.sample_size, 4)
npt.assert_array_equal(obs.groups, ['Control', 'Fast'])
self.assertAlmostEqual(obs.statistic, 0.625)
self.assertAlmostEqual(obs.p_value, 0.332)
self.assertEqual(obs.permutations, 999)
def test_call_no_permutations(self):
obs = self.anosim_no_ties(0)
self.assertEqual(obs.sample_size, 4)
npt.assert_array_equal(obs.groups, ['Control', 'Fast'])
self.assertAlmostEqual(obs.statistic, 0.625)
self.assertEqual(obs.p_value, None)
self.assertEqual(obs.permutations, 0)
def test_call_unequal_group_sizes(self):
np.random.seed(0)
obs = self.anosim_unequal()
self.assertEqual(obs.sample_size, 6)
npt.assert_array_equal(obs.groups,
['Control', 'Treatment1', 'Treatment2'])
self.assertAlmostEqual(obs.statistic, -0.363636, 6)
self.assertAlmostEqual(obs.p_value, 0.878)
self.assertEqual(obs.permutations, 999)
if __name__ == '__main__':
main()
|
bsd-3-clause
|
kenshay/ImageScripter
|
ProgramData/SystemFiles/Python/Lib/site-packages/pandas/indexes/category.py
|
7
|
22750
|
import numpy as np
import pandas.index as _index
from pandas import compat
from pandas.compat.numpy import function as nv
from pandas.types.generic import ABCCategorical, ABCSeries
from pandas.types.common import (is_categorical_dtype,
_ensure_platform_int,
is_list_like,
is_scalar)
from pandas.types.missing import array_equivalent
from pandas.util.decorators import (Appender, cache_readonly,
deprecate_kwarg)
from pandas.core.config import get_option
from pandas.indexes.base import Index, _index_shared_docs
import pandas.core.base as base
import pandas.core.missing as missing
import pandas.indexes.base as ibase
class CategoricalIndex(Index, base.PandasDelegate):
"""
Immutable Index implementing an ordered, sliceable set. CategoricalIndex
represents a sparsely populated Index with an underlying Categorical.
.. versionadded:: 0.16.1
Parameters
----------
data : array-like or Categorical, (1-dimensional)
categories : optional, array-like
categories for the CategoricalIndex
ordered : boolean,
designating if the categories are ordered
copy : bool
Make a copy of input ndarray
name : object
Name to be stored in the index
"""
_typ = 'categoricalindex'
_engine_type = _index.Int64Engine
_attributes = ['name']
def __new__(cls, data=None, categories=None, ordered=None, dtype=None,
copy=False, name=None, fastpath=False, **kwargs):
if fastpath:
return cls._simple_new(data, name=name)
if name is None and hasattr(data, 'name'):
name = data.name
if isinstance(data, ABCCategorical):
data = cls._create_categorical(cls, data, categories, ordered)
elif isinstance(data, CategoricalIndex):
data = data._data
data = cls._create_categorical(cls, data, categories, ordered)
else:
# don't allow scalars
# if data is None, then categories must be provided
if is_scalar(data):
if data is not None or categories is None:
cls._scalar_data_error(data)
data = []
data = cls._create_categorical(cls, data, categories, ordered)
if copy:
data = data.copy()
return cls._simple_new(data, name=name)
def _create_from_codes(self, codes, categories=None, ordered=None,
name=None):
"""
*this is an internal non-public method*
create the correct categorical from codes
Parameters
----------
codes : new codes
categories : optional categories, defaults to existing
ordered : optional ordered attribute, defaults to existing
name : optional name attribute, defaults to existing
Returns
-------
CategoricalIndex
"""
from pandas.core.categorical import Categorical
if categories is None:
categories = self.categories
if ordered is None:
ordered = self.ordered
if name is None:
name = self.name
cat = Categorical.from_codes(codes, categories=categories,
ordered=self.ordered)
return CategoricalIndex(cat, name=name)
@staticmethod
def _create_categorical(self, data, categories=None, ordered=None):
"""
*this is an internal non-public method*
create the correct categorical from data and the properties
Parameters
----------
data : data for new Categorical
categories : optional categories, defaults to existing
ordered : optional ordered attribute, defaults to existing
Returns
-------
Categorical
"""
if not isinstance(data, ABCCategorical):
ordered = False if ordered is None else ordered
from pandas.core.categorical import Categorical
data = Categorical(data, categories=categories, ordered=ordered)
else:
if categories is not None:
data = data.set_categories(categories)
if ordered is not None:
data = data.set_ordered(ordered)
return data
@classmethod
def _simple_new(cls, values, name=None, categories=None, ordered=None,
**kwargs):
result = object.__new__(cls)
values = cls._create_categorical(cls, values, categories, ordered)
result._data = values
result.name = name
for k, v in compat.iteritems(kwargs):
setattr(result, k, v)
result._reset_identity()
return result
@Appender(_index_shared_docs['_shallow_copy'])
def _shallow_copy(self, values=None, categories=None, ordered=None,
**kwargs):
# categories and ordered can't be part of attributes,
# as these are properties
if categories is None:
categories = self.categories
if ordered is None:
ordered = self.ordered
return super(CategoricalIndex,
self)._shallow_copy(values=values, categories=categories,
ordered=ordered, **kwargs)
def _is_dtype_compat(self, other):
"""
*this is an internal non-public method*
provide a comparison between the dtype of self and other (coercing if
needed)
Raises
------
TypeError if the dtypes are not compatible
"""
if is_categorical_dtype(other):
if isinstance(other, CategoricalIndex):
other = other._values
if not other.is_dtype_equal(self):
raise TypeError("categories must match existing categories "
"when appending")
else:
values = other
if not is_list_like(values):
values = [values]
other = CategoricalIndex(self._create_categorical(
self, other, categories=self.categories, ordered=self.ordered))
if not other.isin(values).all():
raise TypeError("cannot append a non-category item to a "
"CategoricalIndex")
return other
def equals(self, other):
"""
Determines if two CategorialIndex objects contain the same elements.
"""
if self.is_(other):
return True
if not isinstance(other, Index):
return False
try:
other = self._is_dtype_compat(other)
return array_equivalent(self._data, other)
except (TypeError, ValueError):
pass
return False
@property
def _formatter_func(self):
return self.categories._formatter_func
def _format_attrs(self):
"""
Return a list of tuples of the (attr,formatted_value)
"""
max_categories = (10 if get_option("display.max_categories") == 0 else
get_option("display.max_categories"))
attrs = [
('categories',
ibase.default_pprint(self.categories,
max_seq_items=max_categories)),
('ordered', self.ordered)]
if self.name is not None:
attrs.append(('name', ibase.default_pprint(self.name)))
attrs.append(('dtype', "'%s'" % self.dtype))
max_seq_items = get_option('display.max_seq_items') or len(self)
if len(self) > max_seq_items:
attrs.append(('length', len(self)))
return attrs
@property
def inferred_type(self):
return 'categorical'
@property
def values(self):
""" return the underlying data, which is a Categorical """
return self._data
def get_values(self):
""" return the underlying data as an ndarray """
return self._data.get_values()
@property
def codes(self):
return self._data.codes
@property
def categories(self):
return self._data.categories
@property
def ordered(self):
return self._data.ordered
def __contains__(self, key):
hash(key)
return key in self.values
def __array__(self, dtype=None):
""" the array interface, return my values """
return np.array(self._data, dtype=dtype)
@cache_readonly
def _isnan(self):
""" return if each value is nan"""
return self._data.codes == -1
@Appender(ibase._index_shared_docs['fillna'])
def fillna(self, value, downcast=None):
self._assert_can_do_op(value)
return CategoricalIndex(self._data.fillna(value), name=self.name)
def argsort(self, *args, **kwargs):
return self.values.argsort(*args, **kwargs)
@cache_readonly
def _engine(self):
# we are going to look things up with the codes themselves
return self._engine_type(lambda: self.codes.astype('i8'), len(self))
@cache_readonly
def is_unique(self):
return not self.duplicated().any()
@Appender(base._shared_docs['unique'] % ibase._index_doc_kwargs)
def unique(self):
result = base.IndexOpsMixin.unique(self)
# CategoricalIndex._shallow_copy uses keeps original categories
# and ordered if not otherwise specified
return self._shallow_copy(result, categories=result.categories,
ordered=result.ordered)
@deprecate_kwarg('take_last', 'keep', mapping={True: 'last',
False: 'first'})
@Appender(base._shared_docs['duplicated'] % ibase._index_doc_kwargs)
def duplicated(self, keep='first'):
from pandas.hashtable import duplicated_int64
codes = self.codes.astype('i8')
return duplicated_int64(codes, keep)
def _to_safe_for_reshape(self):
""" convert to object if we are a categorical """
return self.astype('object')
def get_loc(self, key, method=None):
"""
Get integer location for requested label
Parameters
----------
key : label
method : {None}
* default: exact matches only.
Returns
-------
loc : int if unique index, possibly slice or mask if not
"""
codes = self.categories.get_loc(key)
if (codes == -1):
raise KeyError(key)
return self._engine.get_loc(codes)
def _can_reindex(self, indexer):
""" always allow reindexing """
pass
def where(self, cond, other=None):
"""
.. versionadded:: 0.19.0
Return an Index of same shape as self and whose corresponding
entries are from self where cond is True and otherwise are from
other.
Parameters
----------
cond : boolean same length as self
other : scalar, or array-like
"""
if other is None:
other = self._na_value
values = np.where(cond, self.values, other)
from pandas.core.categorical import Categorical
cat = Categorical(values,
categories=self.categories,
ordered=self.ordered)
return self._shallow_copy(cat, **self._get_attributes_dict())
def reindex(self, target, method=None, level=None, limit=None,
tolerance=None):
"""
Create index with target's values (move/add/delete values as necessary)
Returns
-------
new_index : pd.Index
Resulting index
indexer : np.ndarray or None
Indices of output values in original index
"""
if method is not None:
raise NotImplementedError("argument method is not implemented for "
"CategoricalIndex.reindex")
if level is not None:
raise NotImplementedError("argument level is not implemented for "
"CategoricalIndex.reindex")
if limit is not None:
raise NotImplementedError("argument limit is not implemented for "
"CategoricalIndex.reindex")
target = ibase._ensure_index(target)
if not is_categorical_dtype(target) and not target.is_unique:
raise ValueError("cannot reindex with a non-unique indexer")
indexer, missing = self.get_indexer_non_unique(np.array(target))
new_target = self.take(indexer)
# filling in missing if needed
if len(missing):
cats = self.categories.get_indexer(target)
if (cats == -1).any():
# coerce to a regular index here!
result = Index(np.array(self), name=self.name)
new_target, indexer, _ = result._reindex_non_unique(
np.array(target))
else:
codes = new_target.codes.copy()
codes[indexer == -1] = cats[missing]
new_target = self._create_from_codes(codes)
# we always want to return an Index type here
# to be consistent with .reindex for other index types (e.g. they don't
# coerce based on the actual values, only on the dtype)
# unless we had an inital Categorical to begin with
# in which case we are going to conform to the passed Categorical
new_target = np.asarray(new_target)
if is_categorical_dtype(target):
new_target = target._shallow_copy(new_target, name=self.name)
else:
new_target = Index(new_target, name=self.name)
return new_target, indexer
def _reindex_non_unique(self, target):
""" reindex from a non-unique; which CategoricalIndex's are almost
always
"""
new_target, indexer = self.reindex(target)
new_indexer = None
check = indexer == -1
if check.any():
new_indexer = np.arange(len(self.take(indexer)))
new_indexer[check] = -1
cats = self.categories.get_indexer(target)
if not (cats == -1).any():
# .reindex returns normal Index. Revert to CategoricalIndex if
# all targets are included in my categories
new_target = self._shallow_copy(new_target)
return new_target, indexer, new_indexer
def get_indexer(self, target, method=None, limit=None, tolerance=None):
"""
Compute indexer and mask for new index given the current index. The
indexer should be then used as an input to ndarray.take to align the
current data to the new index. The mask determines whether labels are
found or not in the current index
Parameters
----------
target : MultiIndex or Index (of tuples)
method : {'pad', 'ffill', 'backfill', 'bfill'}
pad / ffill: propagate LAST valid observation forward to next valid
backfill / bfill: use NEXT valid observation to fill gap
Notes
-----
This is a low-level method and probably should be used at your own risk
Examples
--------
>>> indexer, mask = index.get_indexer(new_index)
>>> new_values = cur_values.take(indexer)
>>> new_values[-mask] = np.nan
Returns
-------
(indexer, mask) : (ndarray, ndarray)
"""
method = missing.clean_reindex_fill_method(method)
target = ibase._ensure_index(target)
if isinstance(target, CategoricalIndex):
target = target.categories
if method == 'pad' or method == 'backfill':
raise NotImplementedError("method='pad' and method='backfill' not "
"implemented yet for CategoricalIndex")
elif method == 'nearest':
raise NotImplementedError("method='nearest' not implemented yet "
'for CategoricalIndex')
else:
codes = self.categories.get_indexer(target)
indexer, _ = self._engine.get_indexer_non_unique(codes)
return _ensure_platform_int(indexer)
def get_indexer_non_unique(self, target):
""" this is the same for a CategoricalIndex for get_indexer; the API
returns the missing values as well
"""
target = ibase._ensure_index(target)
if isinstance(target, CategoricalIndex):
target = target.categories
codes = self.categories.get_indexer(target)
return self._engine.get_indexer_non_unique(codes)
def _convert_list_indexer(self, keyarr, kind=None):
"""
we are passed a list indexer.
Return our indexer or raise if all of the values are not included in
the categories
"""
codes = self.categories.get_indexer(keyarr)
if (codes == -1).any():
raise KeyError("a list-indexer must only include values that are "
"in the categories")
return None
@Appender(_index_shared_docs['take'])
def take(self, indices, axis=0, allow_fill=True,
fill_value=None, **kwargs):
nv.validate_take(tuple(), kwargs)
indices = _ensure_platform_int(indices)
taken = self._assert_take_fillable(self.codes, indices,
allow_fill=allow_fill,
fill_value=fill_value,
na_value=-1)
return self._create_from_codes(taken)
def map(self, mapper):
"""
Apply mapper function to its categories (not codes).
Parameters
----------
mapper : callable
Function to be applied. When all categories are mapped
to different categories, the result will be Categorical which has
the same order property as the original. Otherwise, the result will
be np.ndarray.
Returns
-------
applied : Categorical or np.ndarray.
"""
return self.values.map(mapper)
def delete(self, loc):
"""
Make new Index with passed location(-s) deleted
Returns
-------
new_index : Index
"""
return self._create_from_codes(np.delete(self.codes, loc))
def insert(self, loc, item):
"""
Make new Index inserting new item at location. Follows
Python list.append semantics for negative values
Parameters
----------
loc : int
item : object
Returns
-------
new_index : Index
Raises
------
ValueError if the item is not in the categories
"""
code = self.categories.get_indexer([item])
if (code == -1):
raise TypeError("cannot insert an item into a CategoricalIndex "
"that is not already an existing category")
codes = self.codes
codes = np.concatenate((codes[:loc], code, codes[loc:]))
return self._create_from_codes(codes)
def _append_same_dtype(self, to_concat, name):
"""
Concatenate to_concat which has the same class
ValueError if other is not in the categories
"""
to_concat = [self._is_dtype_compat(c) for c in to_concat]
codes = np.concatenate([c.codes for c in to_concat])
result = self._create_from_codes(codes, name=name)
# if name is None, _create_from_codes sets self.name
result.name = name
return result
@classmethod
def _add_comparison_methods(cls):
""" add in comparison methods """
def _make_compare(op):
def _evaluate_compare(self, other):
# if we have a Categorical type, then must have the same
# categories
if isinstance(other, CategoricalIndex):
other = other._values
elif isinstance(other, Index):
other = self._create_categorical(
self, other._values, categories=self.categories,
ordered=self.ordered)
if isinstance(other, (ABCCategorical, np.ndarray,
ABCSeries)):
if len(self.values) != len(other):
raise ValueError("Lengths must match to compare")
if isinstance(other, ABCCategorical):
if not self.values.is_dtype_equal(other):
raise TypeError("categorical index comparisions must "
"have the same categories and ordered "
"attributes")
return getattr(self.values, op)(other)
return _evaluate_compare
cls.__eq__ = _make_compare('__eq__')
cls.__ne__ = _make_compare('__ne__')
cls.__lt__ = _make_compare('__lt__')
cls.__gt__ = _make_compare('__gt__')
cls.__le__ = _make_compare('__le__')
cls.__ge__ = _make_compare('__ge__')
def _delegate_method(self, name, *args, **kwargs):
""" method delegation to the ._values """
method = getattr(self._values, name)
if 'inplace' in kwargs:
raise ValueError("cannot use inplace with CategoricalIndex")
res = method(*args, **kwargs)
if is_scalar(res):
return res
return CategoricalIndex(res, name=self.name)
@classmethod
def _add_accessors(cls):
""" add in Categorical accessor methods """
from pandas.core.categorical import Categorical
CategoricalIndex._add_delegate_accessors(
delegate=Categorical, accessors=["rename_categories",
"reorder_categories",
"add_categories",
"remove_categories",
"remove_unused_categories",
"set_categories",
"as_ordered", "as_unordered",
"min", "max"],
typ='method', overwrite=True)
CategoricalIndex._add_numeric_methods_add_sub_disabled()
CategoricalIndex._add_numeric_methods_disabled()
CategoricalIndex._add_logical_methods_disabled()
CategoricalIndex._add_comparison_methods()
CategoricalIndex._add_accessors()
|
gpl-3.0
|
lbdreyer/iris
|
lib/iris/tests/integration/plot/test_netcdftime.py
|
5
|
1624
|
# Copyright Iris contributors
#
# This file is part of Iris and is released under the LGPL license.
# See COPYING and COPYING.LESSER in the root of the repository for full
# licensing details.
"""
Test plot of time coord with non-gregorian calendar.
"""
# import iris tests first so that some things can be initialised before
# importing anything else
import iris.tests as tests
import cftime
import numpy as np
from iris.coords import AuxCoord
from cf_units import Unit
if tests.NC_TIME_AXIS_AVAILABLE:
from nc_time_axis import CalendarDateTime
# Run tests in no graphics mode if matplotlib is not available.
if tests.MPL_AVAILABLE:
import iris.plot as iplt
@tests.skip_nc_time_axis
@tests.skip_plot
class Test(tests.GraphicsTest):
def test_360_day_calendar(self):
n = 360
calendar = "360_day"
time_unit = Unit("days since 1970-01-01 00:00", calendar=calendar)
time_coord = AuxCoord(np.arange(n), "time", units=time_unit)
times = [time_unit.num2date(point) for point in time_coord.points]
times = [
cftime.datetime(
atime.year,
atime.month,
atime.day,
atime.hour,
atime.minute,
atime.second,
)
for atime in times
]
expected_ydata = np.array(
[CalendarDateTime(time, calendar) for time in times]
)
(line1,) = iplt.plot(time_coord)
result_ydata = line1.get_ydata()
self.assertArrayEqual(expected_ydata, result_ydata)
if __name__ == "__main__":
tests.main()
|
lgpl-3.0
|
rebeccabilbro/rebeccabilbro.github.io
|
_drafts/mushroom_tutorial_reboot.py
|
1
|
9739
|
#!/usr/bin/env python
# coding: utf-8
# # Model Selection Tutorial with Yellowbrick
#
# In this tutorial, we are going to look at scores for a variety of [scikit-learn](http://scikit-learn.org) models and compare them using visual diagnostic tools from [Yellowbrick](http://www.scikit-yb.org) in order to select the best model for our data.
#
#
# ## The Model Selection Triple
#
# Discussions of machine learning are frequently characterized by a singular focus on model selection. Be it logistic regression, random forests, Bayesian methods, or artificial neural networks, machine learning practitioners are often quick to express their preference. The reason for this is mostly historical. Though modern third-party machine learning libraries have made the deployment of multiple models appear nearly trivial, traditionally the application and tuning of even one of these algorithms required many years of study. As a result, machine learning practitioners tended to have strong preferences for particular (and likely more familiar) models over others.
#
# However, model selection is a bit more nuanced than simply picking the "right" or "wrong" algorithm. In practice, the workflow includes:
#
# 1. selecting and/or engineering the smallest and most predictive feature set
# 2. choosing a set of algorithms from a model family, and
# 3. tuning the algorithm hyperparameters to optimize performance.
#
# The **model selection triple** was first described in a 2015 [SIGMOD](http://cseweb.ucsd.edu/~arunkk/vision/SIGMODRecord15.pdf) paper by Kumar et al. In their paper, which concerns the development of next-generation database systems built to anticipate predictive modeling, the authors cogently express that such systems are badly needed due to the highly experimental nature of machine learning in practice. "Model selection," they explain, "is iterative and exploratory because the space of [model selection triples] is usually infinite, and it is generally impossible for analysts to know a priori which [combination] will yield satisfactory accuracy and/or insights."
#
# Recently, much of this workflow has been automated through grid search methods, standardized APIs, and GUI-based applications. In practice, however, human intuition and guidance can more effectively hone in on quality models than exhaustive search. By visualizing the model selection process, data scientists can steer towards final, explainable models and avoid pitfalls and traps.
#
# The Yellowbrick library is a diagnostic visualization platform for machine learning that allows data scientists to steer the model selection process. Yellowbrick extends the scikit-learn API with a new core object: the Visualizer. Visualizers allow visual models to be fit and transformed as part of the scikit-learn `Pipeline` process, providing visual diagnostics throughout the transformation of high dimensional data.
#
#
# ## About the Data
#
# This tutorial uses the mushrooms data from the Yellowbrick :doc:`api/datasets` module. Our objective is to predict if a mushroom is poisonous or edible based on its characteristics.
#
# _NOTE: The YB version of the mushrooms data differs from the mushroom dataset from the [UCI Machine Learning Repository](http://archive.ics.uci.edu/ml/). The Yellowbrick version has been deliberately modified to make modeling a bit more of a challenge._
#
# The data include descriptions of hypothetical samples corresponding to 23 species of gilled mushrooms in the Agaricus and Lepiota Family. Each species was identified as definitely edible, definitely poisonous, or of unknown edibility and not recommended (this latter class was combined with the poisonous one).
#
# Our file, "agaricus-lepiota.txt," contains information for 3 nominally valued attributes and a target value from 8124 instances of mushrooms (4208 edible, 3916 poisonous).
#
# Let's load the data:
# In[1]:
from yellowbrick.datasets import load_mushroom
X, y = load_mushroom()
print(X[:5]) # inspect the first five rows
# ## Feature Extraction
#
# Our data, including the target, is categorical. We will need to change these values to numeric ones for machine learning. In order to extract this from the dataset, we'll have to use scikit-learn transformers to transform our input dataset into something that can be fit to a model. Luckily, scikit-learn does provide transformers for converting categorical labels into numeric integers: [`sklearn.preprocessing.LabelEncoder`](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html) and [`sklearn.preprocessing.OneHotEncoder`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html).
#
# We'll use a combination of scikit-learn's `Pipeline` object ([here's great post on using pipelines](http://zacstewart.com/2014/08/05/pipelines-of-featureunions-of-pipelines.html) by [Zac Stewart](https://twitter.com/zacstewart)), `OneHotEncoder`, and `LabelEncoder`:
#
# ```python
# from sklearn.pipeline import Pipeline
# from sklearn.preprocessing import OneHotEncoder, LabelEncoder
#
#
# y = LabelEncoder().fit_transform(y) # Label-encode targets before modeling
# model = Pipeline([
# ('one_hot_encoder', OneHotEncoder()), # One-hot encode columns before modeling
# ('estimator', estimator)
# ])
# ```
# ## Modeling and Evaluation
#
# ### Common metrics for evaluating classifiers
#
# **Precision** is the number of correct positive results divided by the number of all positive results (e.g. _How many of the mushrooms we predicted would be edible actually were?_).
#
# **Recall** is the number of correct positive results divided by the number of positive results that should have been returned (e.g. _How many of the mushrooms that were poisonous did we accurately predict were poisonous?_).
#
# The **F1 score** is a measure of a test's accuracy. It considers both the precision and the recall of the test to compute the score. The F1 score can be interpreted as a weighted average of the precision and recall, where an F1 score reaches its best value at 1 and worst at 0.
#
# precision = true positives / (true positives + false positives)
#
# recall = true positives / (false negatives + true positives)
#
# F1 score = 2 * ((precision * recall) / (precision + recall))
#
#
# Now we're ready to make some predictions!
#
# Let's build a way to evaluate multiple estimators — first using traditional numeric scores (which we'll later compare to some visual diagnostics from the Yellowbrick library).
# In[2]:
from sklearn.metrics import f1_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, LabelEncoder
def score_model(X, y, estimator, **kwargs):
"""
Test various estimators.
"""
y = LabelEncoder().fit_transform(y)
model = Pipeline([
('one_hot_encoder', OneHotEncoder()),
('estimator', estimator)
])
# Instantiate the classification model and visualizer
model.fit(X, y, **kwargs)
expected = y
predicted = model.predict(X)
# Compute and return F1 (harmonic mean of precision and recall)
print("{}: {}".format(estimator.__class__.__name__, f1_score(expected, predicted)))
# In[3]:
# Try them all!
from sklearn.svm import LinearSVC, NuSVC, SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegressionCV, LogisticRegression, SGDClassifier
from sklearn.ensemble import BaggingClassifier, ExtraTreesClassifier, RandomForestClassifier
models = [
SVC(gamma='auto'), NuSVC(gamma='auto'), LinearSVC(),
SGDClassifier(max_iter=100, tol=1e-3), KNeighborsClassifier(),
LogisticRegression(solver='lbfgs'), LogisticRegressionCV(cv=3),
BaggingClassifier(), ExtraTreesClassifier(n_estimators=100),
RandomForestClassifier(n_estimators=100)
]
for model in models:
score_model(X, y, model)
# ### Preliminary Model Evaluation
#
# Based on the results from the F1 scores above, which model is performing the best?
# ## Visual Model Evaluation
#
# Now let's refactor our model evaluation function to use Yellowbrick's `ClassificationReport` class, a model visualizer that displays the precision, recall, and F1 scores. This visual model analysis tool integrates numerical scores as well color-coded heatmap in order to support easy interpretation and detection, particularly the nuances of Type I and Type II error, which are very relevant (lifesaving, even) to our use case!
#
#
# **Type I error** (or a **"false positive"**) is detecting an effect that is not present (e.g. determining a mushroom is poisonous when it is in fact edible).
#
# **Type II error** (or a **"false negative"**) is failing to detect an effect that is present (e.g. believing a mushroom is edible when it is in fact poisonous).
# In[7]:
from sklearn.pipeline import Pipeline
from yellowbrick.classifier import ClassificationReport
def visualize_model(X, y, estimator):
"""
Test various estimators.
"""
y = LabelEncoder().fit_transform(y)
model = Pipeline([
('one_hot_encoder', OneHotEncoder()),
('estimator', estimator)
])
# Instantiate the classification model and visualizer
visualizer = ClassificationReport(
model, classes=['edible', 'poisonous'],
cmap="YlGn", size=(600, 360)
)
visualizer.fit(X, y)
visualizer.score(X, y)
visualizer.poof()
for model in models:
visualize_model(X, y, model)
# ## Reflection
#
# 1. Which model seems best now? Why?
# 2. Which is most likely to save your life?
# 3. How is the visual model evaluation experience different from numeric model evaluation?
|
mit
|
scls19fr/pandas_degreedays
|
tests/test_degreedays.py
|
1
|
2046
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import datetime
import pandas_degreedays
from pandas_degreedays import *
import six
def test_version():
"""Test version"""
version = pandas_degreedays.__version__
isinstance(version, six.string_types)
def test_degreedays_date_Tmin_before_6PM():
"""Tmin: BEFORE 6PM"""
dt = datetime.datetime(year=2014, month=11, day=1, hour=12, minute=0)
d = degreedays_date_Tn(dt)
d2 = dt.date()
assert(d == d2)
def test_degreedays_date_Tmin_after_6PM():
"""Tmin: AFTER 6PM"""
dt = datetime.datetime(year=2014, month=11, day=1, hour=18, minute=0)
d = degreedays_date_Tn(dt)
dt2 = dt + datetime.timedelta(days=1)
d2 = dt2.date()
assert(d == d2)
def test_degreedays_date_Tmax_before_6AM():
"""Tmin: BEFORE 6AM"""
dt = datetime.datetime(year=2014, month=11, day=1, hour=5, minute=0)
d = degreedays_date_Tx(dt)
dt2 = dt - datetime.timedelta(days=1)
d2 = dt2.date()
assert(d == d2)
def test_degreedays_date_Tmin_after_6AM():
"""Tmin: AFTER 6AM"""
dt = datetime.datetime(year=2014, month=11, day=1, hour=7, minute=0)
d = degreedays_date_Tx(dt)
d2 = dt.date()
assert(d == d2)
def test_degreedays():
"""Calculating degree days"""
assert(hdd_meteo(10, 20, 18)==3)
assert(hdd_meteo(10, 30, 18)==0)
assert(cdd_meteo(10, 20, 18)==0)
assert(cdd_meteo(10, 30, 18)==2)
assert(hdd(5, 15, 18)==8)
assert(hdd(20, 30, 18)==0)
assert(hdd(10, 20, 18)==3.328)
assert(cdd(5, 15, 18)==0)
assert(cdd(20, 30, 18)==7)
assert(cdd(10, 20, 18)==0.32799999999999996)
def test_sample():
"""Reading XLS file with temperature as time serie
and calculate degree days"""
filename = os.path.join('sample', 'temperature_sample.xls')
df_temp = pd.read_excel(filename)
df_temp = df_temp.set_index('datetime')
ts_temp = df_temp['temp']
df_degreedays = calculate_dd(ts_temp=ts_temp, method='pro', typ='heating', Tref=18.0)
isinstance(df_degreedays, pd.DataFrame)
|
bsd-3-clause
|
stpsomad/DynamicPCDMS
|
pointcloud/duplicates/duplicate.py
|
2
|
2699
|
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 03 20:20 2016
@author: Stella Psomadaki
Command line executable to remove duplicates. Only one folder per run.
This module takes a laz, las file and removes duplicate points in the
(x,y) dimensions. This is an important preprocessing step because the IOT
does not allow duplicates in the index.
"""
import numpy as np
from pandas import DataFrame
import time
from laspy.file import File
import os
from pointcloud.reader import readFileLaspy
from pointcloud.utils import getFiles
import sys, getopt
def removeDuplicate(file):
"""Removes duplicate points based on X, Y coordinates
Returns a numpy array"""
df = DataFrame(np.vstack((file.x, file.y, file.z)).transpose(), columns=['X', 'Y', 'Z'])
df.drop_duplicates(subset=['X','Y'], inplace=True)
return df.values
def writeFile(directory,name,header,coords):
"""Write a laz file using laspy and numpy arrays"""
output = File(directory + name, mode = "w", header=header)
output.x = coords[0]
output.y = coords[1]
output.z = coords[2]
output.close()
def checkDirectory(directory):
""" Checks if the specified directory exists, and otherwise it creates it"""
try:
os.makedirs(directory)
except OSError:
if not os.path.isdir(directory):
raise
def lasDuplicateFree(directory, output):
""" Takes a directory with las [laz] files and an output directory
Returns las, [laz] files free from duplicates"""
files = getFiles(directory,['laz'],True)
checkDirectory(output)
for file in files:
print file
fh = readFileLaspy(file)
writeFile(output,file[file.rfind('\\')+1:],fh.header,removeDuplicate(fh).transpose())
def main(argv):
inputdir = ''
outputdir = ''
try:
opts, args = getopt.getopt(argv, "hi:o:", ["help", "input=", "output="])
except getopt.GetoptError:
print 'lasduplicate.py -i <inputDirectory> -o <outputDirectory>'
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--help"):
print argv[0] +' -i <inputDirectory> -o <outputDirectory>'
sys.exit()
elif opt in ("-i", "--input"):
inputdir = arg
elif opt in ("-o", "--output"):
outputdir = arg
lasDuplicateFree(inputdir, outputdir)
if __name__ =="__main__":
start = time.time()
main(sys.argv[1:])
end = time.time()
print "Finished in ", end - start
#Example run: python duplicate.py -i D:\ -o D:\output\
|
isc
|
vortex-ape/scikit-learn
|
sklearn/ensemble/tests/test_gradient_boosting.py
|
5
|
50475
|
"""
Testing for the gradient boosting module (sklearn.ensemble.gradient_boosting).
"""
import warnings
import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse import csc_matrix
from scipy.sparse import coo_matrix
import pytest
from sklearn import datasets
from sklearn.base import clone
from sklearn.datasets import make_classification, fetch_california_housing
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.ensemble.gradient_boosting import ZeroEstimator
from sklearn.ensemble._gradient_boosting import predict_stages
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.utils import check_random_state, tosequence
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_less
from sklearn.utils.testing import assert_raises
from sklearn.utils.testing import assert_raise_message
from sklearn.utils.testing import assert_true
from sklearn.utils.testing import assert_warns
from sklearn.utils.testing import assert_warns_message
from sklearn.utils.testing import skip_if_32bit
from sklearn.exceptions import DataConversionWarning
from sklearn.exceptions import NotFittedError
GRADIENT_BOOSTING_ESTIMATORS = [GradientBoostingClassifier,
GradientBoostingRegressor]
# 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]
rng = np.random.RandomState(0)
# 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]
# also load the iris dataset
# and randomly permute it
iris = datasets.load_iris()
perm = rng.permutation(iris.target.size)
iris.data = iris.data[perm]
iris.target = iris.target[perm]
def check_classification_toy(presort, loss):
# Check classification on a toy dataset.
clf = GradientBoostingClassifier(loss=loss, n_estimators=10,
random_state=1, presort=presort)
assert_raises(ValueError, clf.predict, T)
clf.fit(X, y)
assert_array_equal(clf.predict(T), true_result)
assert_equal(10, len(clf.estimators_))
deviance_decrease = (clf.train_score_[:-1] - clf.train_score_[1:])
assert_true(np.any(deviance_decrease >= 0.0))
leaves = clf.apply(X)
assert_equal(leaves.shape, (6, 10, 1))
@pytest.mark.parametrize('presort', ('auto', True, False))
@pytest.mark.parametrize('loss', ('deviance', 'exponential'))
def test_classification_toy(presort, loss):
check_classification_toy(presort, loss)
def test_classifier_parameter_checks():
# Check input parameter validation for GradientBoostingClassifier.
assert_raises(ValueError,
GradientBoostingClassifier(n_estimators=0).fit, X, y)
assert_raises(ValueError,
GradientBoostingClassifier(n_estimators=-1).fit, X, y)
assert_raises(ValueError,
GradientBoostingClassifier(learning_rate=0.0).fit, X, y)
assert_raises(ValueError,
GradientBoostingClassifier(learning_rate=-1.0).fit, X, y)
assert_raises(ValueError,
GradientBoostingClassifier(loss='foobar').fit, X, y)
assert_raises(ValueError,
GradientBoostingClassifier(min_samples_split=0.0).fit, X, y)
assert_raises(ValueError,
GradientBoostingClassifier(min_samples_split=-1.0).fit, X, y)
assert_raises(ValueError,
GradientBoostingClassifier(min_samples_split=1.1).fit, X, y)
assert_raises(ValueError,
GradientBoostingClassifier(min_samples_leaf=0).fit, X, y)
assert_raises(ValueError,
GradientBoostingClassifier(min_samples_leaf=-1.0).fit, X, y)
assert_raises(ValueError,
GradientBoostingClassifier(min_weight_fraction_leaf=-1.).fit,
X, y)
assert_raises(ValueError,
GradientBoostingClassifier(min_weight_fraction_leaf=0.6).fit,
X, y)
assert_raises(ValueError,
GradientBoostingClassifier(subsample=0.0).fit, X, y)
assert_raises(ValueError,
GradientBoostingClassifier(subsample=1.1).fit, X, y)
assert_raises(ValueError,
GradientBoostingClassifier(subsample=-0.1).fit, X, y)
assert_raises(ValueError,
GradientBoostingClassifier(max_depth=-0.1).fit, X, y)
assert_raises(ValueError,
GradientBoostingClassifier(max_depth=0).fit, X, y)
assert_raises(ValueError,
GradientBoostingClassifier(init={}).fit, X, y)
# test fit before feature importance
assert_raises(ValueError,
lambda: GradientBoostingClassifier().feature_importances_)
# deviance requires ``n_classes >= 2``.
assert_raises(ValueError,
lambda X, y: GradientBoostingClassifier(
loss='deviance').fit(X, y),
X, [0, 0, 0, 0])
allowed_presort = ('auto', True, False)
assert_raise_message(ValueError,
"'presort' should be in {}. "
"Got 'invalid' instead.".format(allowed_presort),
GradientBoostingClassifier(presort='invalid')
.fit, X, y)
def test_regressor_parameter_checks():
# Check input parameter validation for GradientBoostingRegressor
assert_raise_message(ValueError, "alpha must be in (0.0, 1.0) but was 1.2",
GradientBoostingRegressor(loss='huber', alpha=1.2)
.fit, X, y)
assert_raise_message(ValueError, "alpha must be in (0.0, 1.0) but was 1.2",
GradientBoostingRegressor(loss='quantile', alpha=1.2)
.fit, X, y)
assert_raise_message(ValueError, "Invalid value for max_features: "
"'invalid'. Allowed string values are 'auto', 'sqrt'"
" or 'log2'.",
GradientBoostingRegressor(max_features='invalid').fit,
X, y)
assert_raise_message(ValueError, "n_iter_no_change should either be None"
" or an integer. 'invalid' was passed",
GradientBoostingRegressor(n_iter_no_change='invalid')
.fit, X, y)
allowed_presort = ('auto', True, False)
assert_raise_message(ValueError,
"'presort' should be in {}. "
"Got 'invalid' instead.".format(allowed_presort),
GradientBoostingRegressor(presort='invalid')
.fit, X, y)
def test_loss_function():
assert_raises(ValueError,
GradientBoostingClassifier(loss='ls').fit, X, y)
assert_raises(ValueError,
GradientBoostingClassifier(loss='lad').fit, X, y)
assert_raises(ValueError,
GradientBoostingClassifier(loss='quantile').fit, X, y)
assert_raises(ValueError,
GradientBoostingClassifier(loss='huber').fit, X, y)
assert_raises(ValueError,
GradientBoostingRegressor(loss='deviance').fit, X, y)
assert_raises(ValueError,
GradientBoostingRegressor(loss='exponential').fit, X, y)
def check_classification_synthetic(presort, loss):
# Test GradientBoostingClassifier on synthetic dataset used by
# Hastie et al. in ESLII Example 12.7.
X, y = datasets.make_hastie_10_2(n_samples=12000, random_state=1)
X_train, X_test = X[:2000], X[2000:]
y_train, y_test = y[:2000], y[2000:]
gbrt = GradientBoostingClassifier(n_estimators=100, min_samples_split=2,
max_depth=1, loss=loss,
learning_rate=1.0, random_state=0)
gbrt.fit(X_train, y_train)
error_rate = (1.0 - gbrt.score(X_test, y_test))
assert_less(error_rate, 0.09)
gbrt = GradientBoostingClassifier(n_estimators=200, min_samples_split=2,
max_depth=1, loss=loss,
learning_rate=1.0, subsample=0.5,
random_state=0,
presort=presort)
gbrt.fit(X_train, y_train)
error_rate = (1.0 - gbrt.score(X_test, y_test))
assert_less(error_rate, 0.08)
@pytest.mark.parametrize('presort', ('auto', True, False))
@pytest.mark.parametrize('loss', ('deviance', 'exponential'))
def test_classification_synthetic(presort, loss):
check_classification_synthetic(presort, loss)
def check_boston(presort, loss, subsample):
# Check consistency on dataset boston house prices with least squares
# and least absolute deviation.
ones = np.ones(len(boston.target))
last_y_pred = None
for sample_weight in None, ones, 2 * ones:
clf = GradientBoostingRegressor(n_estimators=100,
loss=loss,
max_depth=4,
subsample=subsample,
min_samples_split=2,
random_state=1,
presort=presort)
assert_raises(ValueError, clf.predict, boston.data)
clf.fit(boston.data, boston.target,
sample_weight=sample_weight)
leaves = clf.apply(boston.data)
assert_equal(leaves.shape, (506, 100))
y_pred = clf.predict(boston.data)
mse = mean_squared_error(boston.target, y_pred)
assert_less(mse, 6.0)
if last_y_pred is not None:
assert_array_almost_equal(last_y_pred, y_pred)
last_y_pred = y_pred
@pytest.mark.parametrize('presort', ('auto', True, False))
@pytest.mark.parametrize('loss', ('ls', 'lad', 'huber'))
@pytest.mark.parametrize('subsample', (1.0, 0.5))
def test_boston(presort, loss, subsample):
check_boston(presort, loss, subsample)
def check_iris(presort, subsample, sample_weight):
# Check consistency on dataset iris.
clf = GradientBoostingClassifier(n_estimators=100,
loss='deviance',
random_state=1,
subsample=subsample,
presort=presort)
clf.fit(iris.data, iris.target, sample_weight=sample_weight)
score = clf.score(iris.data, iris.target)
assert_greater(score, 0.9)
leaves = clf.apply(iris.data)
assert_equal(leaves.shape, (150, 100, 3))
@pytest.mark.parametrize('presort', ('auto', True, False))
@pytest.mark.parametrize('subsample', (1.0, 0.5))
@pytest.mark.parametrize('sample_weight', (None, 1))
def test_iris(presort, subsample, sample_weight):
if sample_weight == 1:
sample_weight = np.ones(len(iris.target))
check_iris(presort, subsample, sample_weight)
def test_regression_synthetic():
# Test on synthetic regression datasets used in Leo Breiman,
# `Bagging Predictors?. Machine Learning 24(2): 123-140 (1996).
random_state = check_random_state(1)
regression_params = {'n_estimators': 100, 'max_depth': 4,
'min_samples_split': 2, 'learning_rate': 0.1,
'loss': 'ls'}
# Friedman1
X, y = datasets.make_friedman1(n_samples=1200,
random_state=random_state,
noise=1.0)
X_train, y_train = X[:200], y[:200]
X_test, y_test = X[200:], y[200:]
for presort in True, False:
clf = GradientBoostingRegressor(presort=presort)
clf.fit(X_train, y_train)
mse = mean_squared_error(y_test, clf.predict(X_test))
assert_less(mse, 5.0)
# Friedman2
X, y = datasets.make_friedman2(n_samples=1200, random_state=random_state)
X_train, y_train = X[:200], y[:200]
X_test, y_test = X[200:], y[200:]
for presort in True, False:
regression_params['presort'] = presort
clf = GradientBoostingRegressor(**regression_params)
clf.fit(X_train, y_train)
mse = mean_squared_error(y_test, clf.predict(X_test))
assert_less(mse, 1700.0)
# Friedman3
X, y = datasets.make_friedman3(n_samples=1200, random_state=random_state)
X_train, y_train = X[:200], y[:200]
X_test, y_test = X[200:], y[200:]
for presort in True, False:
regression_params['presort'] = presort
clf = GradientBoostingRegressor(**regression_params)
clf.fit(X_train, y_train)
mse = mean_squared_error(y_test, clf.predict(X_test))
assert_less(mse, 0.015)
def test_feature_importances():
X = np.array(boston.data, dtype=np.float32)
y = np.array(boston.target, dtype=np.float32)
for presort in True, False:
clf = GradientBoostingRegressor(n_estimators=100, max_depth=5,
min_samples_split=2, random_state=1,
presort=presort)
clf.fit(X, y)
assert_true(hasattr(clf, 'feature_importances_'))
def test_probability_log():
# Predict probabilities.
clf = GradientBoostingClassifier(n_estimators=100, random_state=1)
assert_raises(ValueError, clf.predict_proba, T)
clf.fit(X, y)
assert_array_equal(clf.predict(T), true_result)
# check if probabilities are in [0, 1].
y_proba = clf.predict_proba(T)
assert_true(np.all(y_proba >= 0.0))
assert_true(np.all(y_proba <= 1.0))
# derive predictions from probabilities
y_pred = clf.classes_.take(y_proba.argmax(axis=1), axis=0)
assert_array_equal(y_pred, true_result)
def test_check_inputs():
# Test input checks (shape and type of X and y).
clf = GradientBoostingClassifier(n_estimators=100, random_state=1)
assert_raises(ValueError, clf.fit, X, y + [0, 1])
clf = GradientBoostingClassifier(n_estimators=100, random_state=1)
assert_raises(ValueError, clf.fit, X, y,
sample_weight=([1] * len(y)) + [0, 1])
weight = [0, 0, 0, 1, 1, 1]
clf = GradientBoostingClassifier(n_estimators=100, random_state=1)
msg = ("y contains 1 class after sample_weight trimmed classes with "
"zero weights, while a minimum of 2 classes are required.")
assert_raise_message(ValueError, msg, clf.fit, X, y, sample_weight=weight)
def test_check_inputs_predict():
# X has wrong shape
clf = GradientBoostingClassifier(n_estimators=100, random_state=1)
clf.fit(X, y)
x = np.array([1.0, 2.0])[:, np.newaxis]
assert_raises(ValueError, clf.predict, x)
x = np.array([[]])
assert_raises(ValueError, clf.predict, x)
x = np.array([1.0, 2.0, 3.0])[:, np.newaxis]
assert_raises(ValueError, clf.predict, x)
clf = GradientBoostingRegressor(n_estimators=100, random_state=1)
clf.fit(X, rng.rand(len(X)))
x = np.array([1.0, 2.0])[:, np.newaxis]
assert_raises(ValueError, clf.predict, x)
x = np.array([[]])
assert_raises(ValueError, clf.predict, x)
x = np.array([1.0, 2.0, 3.0])[:, np.newaxis]
assert_raises(ValueError, clf.predict, x)
def test_check_inputs_predict_stages():
# check that predict_stages through an error if the type of X is not
# supported
x, y = datasets.make_hastie_10_2(n_samples=100, random_state=1)
x_sparse_csc = csc_matrix(x)
clf = GradientBoostingClassifier(n_estimators=100, random_state=1)
clf.fit(x, y)
score = np.zeros((y.shape)).reshape(-1, 1)
assert_raise_message(ValueError,
"When X is a sparse matrix, a CSR format is expected",
predict_stages, clf.estimators_, x_sparse_csc,
clf.learning_rate, score)
x_fortran = np.asfortranarray(x)
assert_raise_message(ValueError,
"X should be C-ordered np.ndarray",
predict_stages, clf.estimators_, x_fortran,
clf.learning_rate, score)
def test_check_max_features():
# test if max_features is valid.
clf = GradientBoostingRegressor(n_estimators=100, random_state=1,
max_features=0)
assert_raises(ValueError, clf.fit, X, y)
clf = GradientBoostingRegressor(n_estimators=100, random_state=1,
max_features=(len(X[0]) + 1))
assert_raises(ValueError, clf.fit, X, y)
clf = GradientBoostingRegressor(n_estimators=100, random_state=1,
max_features=-0.1)
assert_raises(ValueError, clf.fit, X, y)
def test_max_feature_regression():
# Test to make sure random state is set properly.
X, y = datasets.make_hastie_10_2(n_samples=12000, random_state=1)
X_train, X_test = X[:2000], X[2000:]
y_train, y_test = y[:2000], y[2000:]
gbrt = GradientBoostingClassifier(n_estimators=100, min_samples_split=5,
max_depth=2, learning_rate=.1,
max_features=2, random_state=1)
gbrt.fit(X_train, y_train)
deviance = gbrt.loss_(y_test, gbrt.decision_function(X_test))
assert_true(deviance < 0.5, "GB failed with deviance %.4f" % deviance)
@pytest.mark.network
def test_feature_importance_regression():
"""Test that Gini importance is calculated correctly.
This test follows the example from [1]_ (pg. 373).
.. [1] Friedman, J., Hastie, T., & Tibshirani, R. (2001). The elements
of statistical learning. New York: Springer series in statistics.
"""
california = fetch_california_housing()
X, y = california.data, california.target
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
reg = GradientBoostingRegressor(loss='huber', learning_rate=0.1,
max_leaf_nodes=6, n_estimators=100,
random_state=0)
reg.fit(X_train, y_train)
sorted_idx = np.argsort(reg.feature_importances_)[::-1]
sorted_features = [california.feature_names[s] for s in sorted_idx]
# The most important feature is the median income by far.
assert sorted_features[0] == 'MedInc'
# The three subsequent features are the following. Their relative ordering
# might change a bit depending on the randomness of the trees and the
# train / test split.
assert set(sorted_features[1:4]) == {'Longitude', 'AveOccup', 'Latitude'}
def test_max_feature_auto():
# Test if max features is set properly for floats and str.
X, y = datasets.make_hastie_10_2(n_samples=12000, random_state=1)
_, n_features = X.shape
X_train = X[:2000]
y_train = y[:2000]
gbrt = GradientBoostingClassifier(n_estimators=1, max_features='auto')
gbrt.fit(X_train, y_train)
assert_equal(gbrt.max_features_, int(np.sqrt(n_features)))
gbrt = GradientBoostingRegressor(n_estimators=1, max_features='auto')
gbrt.fit(X_train, y_train)
assert_equal(gbrt.max_features_, n_features)
gbrt = GradientBoostingRegressor(n_estimators=1, max_features=0.3)
gbrt.fit(X_train, y_train)
assert_equal(gbrt.max_features_, int(n_features * 0.3))
gbrt = GradientBoostingRegressor(n_estimators=1, max_features='sqrt')
gbrt.fit(X_train, y_train)
assert_equal(gbrt.max_features_, int(np.sqrt(n_features)))
gbrt = GradientBoostingRegressor(n_estimators=1, max_features='log2')
gbrt.fit(X_train, y_train)
assert_equal(gbrt.max_features_, int(np.log2(n_features)))
gbrt = GradientBoostingRegressor(n_estimators=1,
max_features=0.01 / X.shape[1])
gbrt.fit(X_train, y_train)
assert_equal(gbrt.max_features_, 1)
def test_staged_predict():
# Test whether staged decision function eventually gives
# the same prediction.
X, y = datasets.make_friedman1(n_samples=1200,
random_state=1, noise=1.0)
X_train, y_train = X[:200], y[:200]
X_test = X[200:]
clf = GradientBoostingRegressor()
# test raise ValueError if not fitted
assert_raises(ValueError, lambda X: np.fromiter(
clf.staged_predict(X), dtype=np.float64), X_test)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
# test if prediction for last stage equals ``predict``
for y in clf.staged_predict(X_test):
assert_equal(y.shape, y_pred.shape)
assert_array_almost_equal(y_pred, y)
def test_staged_predict_proba():
# Test whether staged predict proba eventually gives
# the same prediction.
X, y = datasets.make_hastie_10_2(n_samples=1200,
random_state=1)
X_train, y_train = X[:200], y[:200]
X_test, y_test = X[200:], y[200:]
clf = GradientBoostingClassifier(n_estimators=20)
# test raise NotFittedError if not fitted
assert_raises(NotFittedError, lambda X: np.fromiter(
clf.staged_predict_proba(X), dtype=np.float64), X_test)
clf.fit(X_train, y_train)
# test if prediction for last stage equals ``predict``
for y_pred in clf.staged_predict(X_test):
assert_equal(y_test.shape, y_pred.shape)
assert_array_equal(clf.predict(X_test), y_pred)
# test if prediction for last stage equals ``predict_proba``
for staged_proba in clf.staged_predict_proba(X_test):
assert_equal(y_test.shape[0], staged_proba.shape[0])
assert_equal(2, staged_proba.shape[1])
assert_array_almost_equal(clf.predict_proba(X_test), staged_proba)
@pytest.mark.parametrize('Estimator', GRADIENT_BOOSTING_ESTIMATORS)
def test_staged_functions_defensive(Estimator):
# test that staged_functions make defensive copies
rng = np.random.RandomState(0)
X = rng.uniform(size=(10, 3))
y = (4 * X[:, 0]).astype(np.int) + 1 # don't predict zeros
estimator = Estimator()
estimator.fit(X, y)
for func in ['predict', 'decision_function', 'predict_proba']:
staged_func = getattr(estimator, "staged_" + func, None)
if staged_func is None:
# regressor has no staged_predict_proba
continue
with warnings.catch_warnings(record=True):
staged_result = list(staged_func(X))
staged_result[1][:] = 0
assert_true(np.all(staged_result[0] != 0))
def test_serialization():
# Check model serialization.
clf = GradientBoostingClassifier(n_estimators=100, random_state=1)
clf.fit(X, y)
assert_array_equal(clf.predict(T), true_result)
assert_equal(100, len(clf.estimators_))
try:
import cPickle as pickle
except ImportError:
import pickle
serialized_clf = pickle.dumps(clf, protocol=pickle.HIGHEST_PROTOCOL)
clf = None
clf = pickle.loads(serialized_clf)
assert_array_equal(clf.predict(T), true_result)
assert_equal(100, len(clf.estimators_))
def test_degenerate_targets():
# Check if we can fit even though all targets are equal.
clf = GradientBoostingClassifier(n_estimators=100, random_state=1)
# classifier should raise exception
assert_raises(ValueError, clf.fit, X, np.ones(len(X)))
clf = GradientBoostingRegressor(n_estimators=100, random_state=1)
clf.fit(X, np.ones(len(X)))
clf.predict([rng.rand(2)])
assert_array_equal(np.ones((1,), dtype=np.float64),
clf.predict([rng.rand(2)]))
def test_quantile_loss():
# Check if quantile loss with alpha=0.5 equals lad.
clf_quantile = GradientBoostingRegressor(n_estimators=100, loss='quantile',
max_depth=4, alpha=0.5,
random_state=7)
clf_quantile.fit(boston.data, boston.target)
y_quantile = clf_quantile.predict(boston.data)
clf_lad = GradientBoostingRegressor(n_estimators=100, loss='lad',
max_depth=4, random_state=7)
clf_lad.fit(boston.data, boston.target)
y_lad = clf_lad.predict(boston.data)
assert_array_almost_equal(y_quantile, y_lad, decimal=4)
def test_symbol_labels():
# Test with non-integer class labels.
clf = GradientBoostingClassifier(n_estimators=100, random_state=1)
symbol_y = tosequence(map(str, y))
clf.fit(X, symbol_y)
assert_array_equal(clf.predict(T), tosequence(map(str, true_result)))
assert_equal(100, len(clf.estimators_))
def test_float_class_labels():
# Test with float class labels.
clf = GradientBoostingClassifier(n_estimators=100, random_state=1)
float_y = np.asarray(y, dtype=np.float32)
clf.fit(X, float_y)
assert_array_equal(clf.predict(T),
np.asarray(true_result, dtype=np.float32))
assert_equal(100, len(clf.estimators_))
def test_shape_y():
# Test with float class labels.
clf = GradientBoostingClassifier(n_estimators=100, random_state=1)
y_ = np.asarray(y, dtype=np.int32)
y_ = y_[:, np.newaxis]
# This will raise a DataConversionWarning that we want to
# "always" raise, elsewhere the warnings gets ignored in the
# later tests, and the tests that check for this warning fail
assert_warns(DataConversionWarning, clf.fit, X, y_)
assert_array_equal(clf.predict(T), true_result)
assert_equal(100, len(clf.estimators_))
def test_mem_layout():
# Test with different memory layouts of X and y
X_ = np.asfortranarray(X)
clf = GradientBoostingClassifier(n_estimators=100, random_state=1)
clf.fit(X_, y)
assert_array_equal(clf.predict(T), true_result)
assert_equal(100, len(clf.estimators_))
X_ = np.ascontiguousarray(X)
clf = GradientBoostingClassifier(n_estimators=100, random_state=1)
clf.fit(X_, y)
assert_array_equal(clf.predict(T), true_result)
assert_equal(100, len(clf.estimators_))
y_ = np.asarray(y, dtype=np.int32)
y_ = np.ascontiguousarray(y_)
clf = GradientBoostingClassifier(n_estimators=100, random_state=1)
clf.fit(X, y_)
assert_array_equal(clf.predict(T), true_result)
assert_equal(100, len(clf.estimators_))
y_ = np.asarray(y, dtype=np.int32)
y_ = np.asfortranarray(y_)
clf = GradientBoostingClassifier(n_estimators=100, random_state=1)
clf.fit(X, y_)
assert_array_equal(clf.predict(T), true_result)
assert_equal(100, len(clf.estimators_))
def test_oob_improvement():
# Test if oob improvement has correct shape and regression test.
clf = GradientBoostingClassifier(n_estimators=100, random_state=1,
subsample=0.5)
clf.fit(X, y)
assert_equal(clf.oob_improvement_.shape[0], 100)
# hard-coded regression test - change if modification in OOB computation
assert_array_almost_equal(clf.oob_improvement_[:5],
np.array([0.19, 0.15, 0.12, -0.12, -0.11]),
decimal=2)
def test_oob_improvement_raise():
# Test if oob improvement has correct shape.
clf = GradientBoostingClassifier(n_estimators=100, random_state=1,
subsample=1.0)
clf.fit(X, y)
assert_raises(AttributeError, lambda: clf.oob_improvement_)
def test_oob_multilcass_iris():
# Check OOB improvement on multi-class dataset.
clf = GradientBoostingClassifier(n_estimators=100, loss='deviance',
random_state=1, subsample=0.5)
clf.fit(iris.data, iris.target)
score = clf.score(iris.data, iris.target)
assert_greater(score, 0.9)
assert_equal(clf.oob_improvement_.shape[0], clf.n_estimators)
# hard-coded regression test - change if modification in OOB computation
# FIXME: the following snippet does not yield the same results on 32 bits
# assert_array_almost_equal(clf.oob_improvement_[:5],
# np.array([12.68, 10.45, 8.18, 6.43, 5.13]),
# decimal=2)
def test_verbose_output():
# Check verbose=1 does not cause error.
from sklearn.externals.six.moves import cStringIO as StringIO
import sys
old_stdout = sys.stdout
sys.stdout = StringIO()
clf = GradientBoostingClassifier(n_estimators=100, random_state=1,
verbose=1, subsample=0.8)
clf.fit(X, y)
verbose_output = sys.stdout
sys.stdout = old_stdout
# check output
verbose_output.seek(0)
header = verbose_output.readline().rstrip()
# with OOB
true_header = ' '.join(['%10s'] + ['%16s'] * 3) % (
'Iter', 'Train Loss', 'OOB Improve', 'Remaining Time')
assert_equal(true_header, header)
n_lines = sum(1 for l in verbose_output.readlines())
# one for 1-10 and then 9 for 20-100
assert_equal(10 + 9, n_lines)
def test_more_verbose_output():
# Check verbose=2 does not cause error.
from sklearn.externals.six.moves import cStringIO as StringIO
import sys
old_stdout = sys.stdout
sys.stdout = StringIO()
clf = GradientBoostingClassifier(n_estimators=100, random_state=1,
verbose=2)
clf.fit(X, y)
verbose_output = sys.stdout
sys.stdout = old_stdout
# check output
verbose_output.seek(0)
header = verbose_output.readline().rstrip()
# no OOB
true_header = ' '.join(['%10s'] + ['%16s'] * 2) % (
'Iter', 'Train Loss', 'Remaining Time')
assert_equal(true_header, header)
n_lines = sum(1 for l in verbose_output.readlines())
# 100 lines for n_estimators==100
assert_equal(100, n_lines)
@pytest.mark.parametrize('Cls', GRADIENT_BOOSTING_ESTIMATORS)
def test_warm_start(Cls):
# Test if warm start equals fit.
X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1)
est = Cls(n_estimators=200, max_depth=1)
est.fit(X, y)
est_ws = Cls(n_estimators=100, max_depth=1, warm_start=True)
est_ws.fit(X, y)
est_ws.set_params(n_estimators=200)
est_ws.fit(X, y)
if Cls is GradientBoostingRegressor:
assert_array_almost_equal(est_ws.predict(X), est.predict(X))
else:
# Random state is preserved and hence predict_proba must also be
# same
assert_array_equal(est_ws.predict(X), est.predict(X))
assert_array_almost_equal(est_ws.predict_proba(X),
est.predict_proba(X))
@pytest.mark.parametrize('Cls', GRADIENT_BOOSTING_ESTIMATORS)
def test_warm_start_n_estimators(Cls):
# Test if warm start equals fit - set n_estimators.
X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1)
est = Cls(n_estimators=300, max_depth=1)
est.fit(X, y)
est_ws = Cls(n_estimators=100, max_depth=1, warm_start=True)
est_ws.fit(X, y)
est_ws.set_params(n_estimators=300)
est_ws.fit(X, y)
assert_array_almost_equal(est_ws.predict(X), est.predict(X))
@pytest.mark.parametrize('Cls', GRADIENT_BOOSTING_ESTIMATORS)
def test_warm_start_max_depth(Cls):
# Test if possible to fit trees of different depth in ensemble.
X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1)
est = Cls(n_estimators=100, max_depth=1, warm_start=True)
est.fit(X, y)
est.set_params(n_estimators=110, max_depth=2)
est.fit(X, y)
# last 10 trees have different depth
assert_equal(est.estimators_[0, 0].max_depth, 1)
for i in range(1, 11):
assert_equal(est.estimators_[-i, 0].max_depth, 2)
@pytest.mark.parametrize('Cls', GRADIENT_BOOSTING_ESTIMATORS)
def test_warm_start_clear(Cls):
# Test if fit clears state.
X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1)
est = Cls(n_estimators=100, max_depth=1)
est.fit(X, y)
est_2 = Cls(n_estimators=100, max_depth=1, warm_start=True)
est_2.fit(X, y) # inits state
est_2.set_params(warm_start=False)
est_2.fit(X, y) # clears old state and equals est
assert_array_almost_equal(est_2.predict(X), est.predict(X))
@pytest.mark.parametrize('Cls', GRADIENT_BOOSTING_ESTIMATORS)
def test_warm_start_zero_n_estimators(Cls):
# Test if warm start with zero n_estimators raises error
X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1)
est = Cls(n_estimators=100, max_depth=1, warm_start=True)
est.fit(X, y)
est.set_params(n_estimators=0)
assert_raises(ValueError, est.fit, X, y)
@pytest.mark.parametrize('Cls', GRADIENT_BOOSTING_ESTIMATORS)
def test_warm_start_smaller_n_estimators(Cls):
# Test if warm start with smaller n_estimators raises error
X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1)
est = Cls(n_estimators=100, max_depth=1, warm_start=True)
est.fit(X, y)
est.set_params(n_estimators=99)
assert_raises(ValueError, est.fit, X, y)
@pytest.mark.parametrize('Cls', GRADIENT_BOOSTING_ESTIMATORS)
def test_warm_start_equal_n_estimators(Cls):
# Test if warm start with equal n_estimators does nothing
X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1)
est = Cls(n_estimators=100, max_depth=1)
est.fit(X, y)
est2 = clone(est)
est2.set_params(n_estimators=est.n_estimators, warm_start=True)
est2.fit(X, y)
assert_array_almost_equal(est2.predict(X), est.predict(X))
@pytest.mark.parametrize('Cls', GRADIENT_BOOSTING_ESTIMATORS)
def test_warm_start_oob_switch(Cls):
# Test if oob can be turned on during warm start.
X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1)
est = Cls(n_estimators=100, max_depth=1, warm_start=True)
est.fit(X, y)
est.set_params(n_estimators=110, subsample=0.5)
est.fit(X, y)
assert_array_equal(est.oob_improvement_[:100], np.zeros(100))
# the last 10 are not zeros
assert_array_equal(est.oob_improvement_[-10:] == 0.0,
np.zeros(10, dtype=np.bool))
@pytest.mark.parametrize('Cls', GRADIENT_BOOSTING_ESTIMATORS)
def test_warm_start_oob(Cls):
# Test if warm start OOB equals fit.
X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1)
est = Cls(n_estimators=200, max_depth=1, subsample=0.5,
random_state=1)
est.fit(X, y)
est_ws = Cls(n_estimators=100, max_depth=1, subsample=0.5,
random_state=1, warm_start=True)
est_ws.fit(X, y)
est_ws.set_params(n_estimators=200)
est_ws.fit(X, y)
assert_array_almost_equal(est_ws.oob_improvement_[:100],
est.oob_improvement_[:100])
@pytest.mark.parametrize('Cls', GRADIENT_BOOSTING_ESTIMATORS)
def test_warm_start_sparse(Cls):
# Test that all sparse matrix types are supported
X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1)
sparse_matrix_type = [csr_matrix, csc_matrix, coo_matrix]
est_dense = Cls(n_estimators=100, max_depth=1, subsample=0.5,
random_state=1, warm_start=True)
est_dense.fit(X, y)
est_dense.predict(X)
est_dense.set_params(n_estimators=200)
est_dense.fit(X, y)
y_pred_dense = est_dense.predict(X)
for sparse_constructor in sparse_matrix_type:
X_sparse = sparse_constructor(X)
est_sparse = Cls(n_estimators=100, max_depth=1, subsample=0.5,
random_state=1, warm_start=True)
est_sparse.fit(X_sparse, y)
est_sparse.predict(X)
est_sparse.set_params(n_estimators=200)
est_sparse.fit(X_sparse, y)
y_pred_sparse = est_sparse.predict(X)
assert_array_almost_equal(est_dense.oob_improvement_[:100],
est_sparse.oob_improvement_[:100])
assert_array_almost_equal(y_pred_dense, y_pred_sparse)
@pytest.mark.parametrize('Cls', GRADIENT_BOOSTING_ESTIMATORS)
def test_warm_start_fortran(Cls):
# Test that feeding a X in Fortran-ordered is giving the same results as
# in C-ordered
X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1)
est_c = Cls(n_estimators=1, random_state=1, warm_start=True)
est_fortran = Cls(n_estimators=1, random_state=1, warm_start=True)
est_c.fit(X, y)
est_c.set_params(n_estimators=11)
est_c.fit(X, y)
X_fortran = np.asfortranarray(X)
est_fortran.fit(X_fortran, y)
est_fortran.set_params(n_estimators=11)
est_fortran.fit(X_fortran, y)
assert_array_almost_equal(est_c.predict(X), est_fortran.predict(X))
def early_stopping_monitor(i, est, locals):
"""Returns True on the 10th iteration. """
if i == 9:
return True
else:
return False
@pytest.mark.parametrize('Cls', GRADIENT_BOOSTING_ESTIMATORS)
def test_monitor_early_stopping(Cls):
# Test if monitor return value works.
X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1)
est = Cls(n_estimators=20, max_depth=1, random_state=1, subsample=0.5)
est.fit(X, y, monitor=early_stopping_monitor)
assert_equal(est.n_estimators, 20) # this is not altered
assert_equal(est.estimators_.shape[0], 10)
assert_equal(est.train_score_.shape[0], 10)
assert_equal(est.oob_improvement_.shape[0], 10)
# try refit
est.set_params(n_estimators=30)
est.fit(X, y)
assert_equal(est.n_estimators, 30)
assert_equal(est.estimators_.shape[0], 30)
assert_equal(est.train_score_.shape[0], 30)
est = Cls(n_estimators=20, max_depth=1, random_state=1, subsample=0.5,
warm_start=True)
est.fit(X, y, monitor=early_stopping_monitor)
assert_equal(est.n_estimators, 20)
assert_equal(est.estimators_.shape[0], 10)
assert_equal(est.train_score_.shape[0], 10)
assert_equal(est.oob_improvement_.shape[0], 10)
# try refit
est.set_params(n_estimators=30, warm_start=False)
est.fit(X, y)
assert_equal(est.n_estimators, 30)
assert_equal(est.train_score_.shape[0], 30)
assert_equal(est.estimators_.shape[0], 30)
assert_equal(est.oob_improvement_.shape[0], 30)
def test_complete_classification():
# 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
est = GradientBoostingClassifier(n_estimators=20, max_depth=None,
random_state=1, max_leaf_nodes=k + 1)
est.fit(X, y)
tree = est.estimators_[0, 0].tree_
assert_equal(tree.max_depth, k)
assert_equal(tree.children_left[tree.children_left == TREE_LEAF].shape[0],
k + 1)
def test_complete_regression():
# Test greedy trees with max_depth + 1 leafs.
from sklearn.tree._tree import TREE_LEAF
k = 4
est = GradientBoostingRegressor(n_estimators=20, max_depth=None,
random_state=1, max_leaf_nodes=k + 1)
est.fit(boston.data, boston.target)
tree = est.estimators_[-1, 0].tree_
assert_equal(tree.children_left[tree.children_left == TREE_LEAF].shape[0],
k + 1)
def test_zero_estimator_reg():
# Test if ZeroEstimator works for regression.
est = GradientBoostingRegressor(n_estimators=20, max_depth=1,
random_state=1, init=ZeroEstimator())
est.fit(boston.data, boston.target)
y_pred = est.predict(boston.data)
mse = mean_squared_error(boston.target, y_pred)
assert_almost_equal(mse, 33.0, decimal=0)
est = GradientBoostingRegressor(n_estimators=20, max_depth=1,
random_state=1, init='zero')
est.fit(boston.data, boston.target)
y_pred = est.predict(boston.data)
mse = mean_squared_error(boston.target, y_pred)
assert_almost_equal(mse, 33.0, decimal=0)
est = GradientBoostingRegressor(n_estimators=20, max_depth=1,
random_state=1, init='foobar')
assert_raises(ValueError, est.fit, boston.data, boston.target)
def test_zero_estimator_clf():
# Test if ZeroEstimator works for classification.
X = iris.data
y = np.array(iris.target)
est = GradientBoostingClassifier(n_estimators=20, max_depth=1,
random_state=1, init=ZeroEstimator())
est.fit(X, y)
assert_greater(est.score(X, y), 0.96)
est = GradientBoostingClassifier(n_estimators=20, max_depth=1,
random_state=1, init='zero')
est.fit(X, y)
assert_greater(est.score(X, y), 0.96)
# binary clf
mask = y != 0
y[mask] = 1
y[~mask] = 0
est = GradientBoostingClassifier(n_estimators=20, max_depth=1,
random_state=1, init='zero')
est.fit(X, y)
assert_greater(est.score(X, y), 0.96)
est = GradientBoostingClassifier(n_estimators=20, max_depth=1,
random_state=1, init='foobar')
assert_raises(ValueError, est.fit, X, y)
@pytest.mark.parametrize('GBEstimator', GRADIENT_BOOSTING_ESTIMATORS)
def test_max_leaf_nodes_max_depth(GBEstimator):
# Test precedence of max_leaf_nodes over max_depth.
X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1)
k = 4
est = GBEstimator(max_depth=1, max_leaf_nodes=k).fit(X, y)
tree = est.estimators_[0, 0].tree_
assert_greater(tree.max_depth, 1)
est = GBEstimator(max_depth=1).fit(X, y)
tree = est.estimators_[0, 0].tree_
assert_equal(tree.max_depth, 1)
@pytest.mark.parametrize('GBEstimator', GRADIENT_BOOSTING_ESTIMATORS)
def test_min_impurity_split(GBEstimator):
# Test if min_impurity_split of base estimators is set
# Regression test for #8006
X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1)
est = GBEstimator(min_impurity_split=0.1)
est = assert_warns_message(DeprecationWarning, "min_impurity_decrease",
est.fit, X, y)
for tree in est.estimators_.flat:
assert_equal(tree.min_impurity_split, 0.1)
@pytest.mark.parametrize('GBEstimator', GRADIENT_BOOSTING_ESTIMATORS)
def test_min_impurity_decrease(GBEstimator):
X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1)
est = GBEstimator(min_impurity_decrease=0.1)
est.fit(X, y)
for tree in est.estimators_.flat:
# Simply check if the parameter is passed on correctly. Tree tests
# will suffice for the actual working of this param
assert_equal(tree.min_impurity_decrease, 0.1)
def test_warm_start_wo_nestimators_change():
# Test if warm_start does nothing if n_estimators is not changed.
# Regression test for #3513.
clf = GradientBoostingClassifier(n_estimators=10, warm_start=True)
clf.fit([[0, 1], [2, 3]], [0, 1])
assert_equal(clf.estimators_.shape[0], 10)
clf.fit([[0, 1], [2, 3]], [0, 1])
assert_equal(clf.estimators_.shape[0], 10)
def test_probability_exponential():
# Predict probabilities.
clf = GradientBoostingClassifier(loss='exponential',
n_estimators=100, random_state=1)
assert_raises(ValueError, clf.predict_proba, T)
clf.fit(X, y)
assert_array_equal(clf.predict(T), true_result)
# check if probabilities are in [0, 1].
y_proba = clf.predict_proba(T)
assert_true(np.all(y_proba >= 0.0))
assert_true(np.all(y_proba <= 1.0))
score = clf.decision_function(T).ravel()
assert_array_almost_equal(y_proba[:, 1],
1.0 / (1.0 + np.exp(-2 * score)))
# derive predictions from probabilities
y_pred = clf.classes_.take(y_proba.argmax(axis=1), axis=0)
assert_array_equal(y_pred, true_result)
def test_non_uniform_weights_toy_edge_case_reg():
X = [[1, 0],
[1, 0],
[1, 0],
[0, 1]]
y = [0, 0, 1, 0]
# ignore the first 2 training samples by setting their weight to 0
sample_weight = [0, 0, 1, 1]
for loss in ('huber', 'ls', 'lad', 'quantile'):
gb = GradientBoostingRegressor(learning_rate=1.0, n_estimators=2,
loss=loss)
gb.fit(X, y, sample_weight=sample_weight)
assert_greater(gb.predict([[1, 0]])[0], 0.5)
def test_non_uniform_weights_toy_edge_case_clf():
X = [[1, 0],
[1, 0],
[1, 0],
[0, 1]]
y = [0, 0, 1, 0]
# ignore the first 2 training samples by setting their weight to 0
sample_weight = [0, 0, 1, 1]
for loss in ('deviance', 'exponential'):
gb = GradientBoostingClassifier(n_estimators=5, loss=loss)
gb.fit(X, y, sample_weight=sample_weight)
assert_array_equal(gb.predict([[1, 0]]), [1])
def check_sparse_input(EstimatorClass, X, X_sparse, y):
dense = EstimatorClass(n_estimators=10, random_state=0,
max_depth=2).fit(X, y)
sparse = EstimatorClass(n_estimators=10, random_state=0, max_depth=2,
presort=False).fit(X_sparse, y)
auto = EstimatorClass(n_estimators=10, random_state=0, max_depth=2,
presort='auto').fit(X_sparse, y)
assert_array_almost_equal(sparse.apply(X), dense.apply(X))
assert_array_almost_equal(sparse.predict(X), dense.predict(X))
assert_array_almost_equal(sparse.feature_importances_,
dense.feature_importances_)
assert_array_almost_equal(sparse.apply(X), auto.apply(X))
assert_array_almost_equal(sparse.predict(X), auto.predict(X))
assert_array_almost_equal(sparse.feature_importances_,
auto.feature_importances_)
assert_array_almost_equal(sparse.predict(X_sparse), dense.predict(X))
assert_array_almost_equal(dense.predict(X_sparse), sparse.predict(X))
if isinstance(EstimatorClass, GradientBoostingClassifier):
assert_array_almost_equal(sparse.predict_proba(X),
dense.predict_proba(X))
assert_array_almost_equal(sparse.predict_log_proba(X),
dense.predict_log_proba(X))
assert_array_almost_equal(sparse.predict_proba(X),
auto.predict_proba(X))
assert_array_almost_equal(sparse.predict_log_proba(X),
auto.predict_log_proba(X))
assert_array_almost_equal(sparse.decision_function(X_sparse),
sparse.decision_function(X))
assert_array_almost_equal(dense.decision_function(X_sparse),
sparse.decision_function(X))
assert_array_almost_equal(
np.array(sparse.staged_decision_function(X_sparse)),
np.array(sparse.staged_decision_function(X)))
@skip_if_32bit
@pytest.mark.parametrize(
'EstimatorClass',
(GradientBoostingClassifier, GradientBoostingRegressor))
@pytest.mark.parametrize('sparse_matrix', (csr_matrix, csc_matrix, coo_matrix))
def test_sparse_input(EstimatorClass, sparse_matrix):
y, X = datasets.make_multilabel_classification(random_state=0,
n_samples=50,
n_features=1,
n_classes=20)
y = y[:, 0]
check_sparse_input(EstimatorClass, X, sparse_matrix(X), y)
def test_gradient_boosting_early_stopping():
X, y = make_classification(n_samples=1000, random_state=0)
gbc = GradientBoostingClassifier(n_estimators=1000,
n_iter_no_change=10,
learning_rate=0.1, max_depth=3,
random_state=42)
gbr = GradientBoostingRegressor(n_estimators=1000, n_iter_no_change=10,
learning_rate=0.1, max_depth=3,
random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y,
random_state=42)
# Check if early_stopping works as expected
for est, tol, early_stop_n_estimators in ((gbc, 1e-1, 24), (gbr, 1e-1, 13),
(gbc, 1e-3, 36),
(gbr, 1e-3, 28)):
est.set_params(tol=tol)
est.fit(X_train, y_train)
assert_equal(est.n_estimators_, early_stop_n_estimators)
assert est.score(X_test, y_test) > 0.7
# Without early stopping
gbc = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1,
max_depth=3, random_state=42)
gbc.fit(X, y)
gbr = GradientBoostingRegressor(n_estimators=200, learning_rate=0.1,
max_depth=3, random_state=42)
gbr.fit(X, y)
assert gbc.n_estimators_ == 100
assert gbr.n_estimators_ == 200
def test_gradient_boosting_validation_fraction():
X, y = make_classification(n_samples=1000, random_state=0)
gbc = GradientBoostingClassifier(n_estimators=100,
n_iter_no_change=10,
validation_fraction=0.1,
learning_rate=0.1, max_depth=3,
random_state=42)
gbc2 = clone(gbc).set_params(validation_fraction=0.3)
gbc3 = clone(gbc).set_params(n_iter_no_change=20)
gbr = GradientBoostingRegressor(n_estimators=100, n_iter_no_change=10,
learning_rate=0.1, max_depth=3,
validation_fraction=0.1,
random_state=42)
gbr2 = clone(gbr).set_params(validation_fraction=0.3)
gbr3 = clone(gbr).set_params(n_iter_no_change=20)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
# Check if validation_fraction has an effect
gbc.fit(X_train, y_train)
gbc2.fit(X_train, y_train)
assert gbc.n_estimators_ != gbc2.n_estimators_
gbr.fit(X_train, y_train)
gbr2.fit(X_train, y_train)
assert gbr.n_estimators_ != gbr2.n_estimators_
# Check if n_estimators_ increase monotonically with n_iter_no_change
# Set validation
gbc3.fit(X_train, y_train)
gbr3.fit(X_train, y_train)
assert gbr.n_estimators_ < gbr3.n_estimators_
assert gbc.n_estimators_ < gbc3.n_estimators_
|
bsd-3-clause
|
florentchandelier/zipline
|
zipline/data/benchmarks.py
|
1
|
2211
|
#
# Copyright 2013 Quantopian, Inc.
#
# 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.
import json
import pandas as pd
import numpy as np
import requests
import os
def get_benchmark_returns(symbol):
"""
Get a Series of benchmark returns from IEX associated with `symbol`.
Default is `SPY`.
Parameters
----------
symbol : str
Benchmark symbol for which we're getting the returns.
The data is provided by IEX (https://iextrading.com/), and we can
get up to 5 years worth of data.
"""
r = requests.get(
'https://api.iextrading.com/1.0/stock/{}/chart/5y'.format(symbol)
)
data = json.loads(r.text)
df = pd.DataFrame(data)
df.index = pd.DatetimeIndex(df['date'])
df = df['close']
return df.sort_index().tz_localize('UTC').pct_change(1).iloc[1:]
def get_localcsv_benchmark_returns(symbol, local_benchmark):
"""
Get a Series of benchmark returns with `symbol`.
Default is `SPY`.
Parameters
----------
symbol : str
Benchmark symbol for which we're getting the returns.
localpath : str
absolute path where to find benchmark csv file.
"""
''' open saved csv files '''
current_dir = os.getcwd()
os.chdir(local_benchmark)
filename = str(symbol + '.csv')
data = pd.read_csv(filename)
data.columns = map(str.lower, data.columns)
data['date'] = pd.to_datetime(data['date']).copy()
data.set_index('date', drop=False, inplace=True)
try:
data = data['close']
except:
data = data['adj close']
os.chdir(current_dir)
data = data.fillna(method='ffill')
return data.sort_index().tz_localize('UTC').pct_change(1).iloc[1:]
|
apache-2.0
|
anntzer/scikit-learn
|
sklearn/tests/test_calibration.py
|
1
|
22504
|
# Authors: Alexandre Gramfort <[email protected]>
# License: BSD 3 clause
import pytest
import numpy as np
from numpy.testing import assert_allclose
from scipy import sparse
from sklearn.base import BaseEstimator
from sklearn.dummy import DummyClassifier
from sklearn.model_selection import LeaveOneOut, train_test_split
from sklearn.utils._testing import (assert_array_almost_equal,
assert_almost_equal,
assert_array_equal,
ignore_warnings)
from sklearn.utils.extmath import softmax
from sklearn.exceptions import NotFittedError
from sklearn.datasets import make_classification, make_blobs
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import KFold, cross_val_predict
from sklearn.naive_bayes import MultinomialNB
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.svm import LinearSVC
from sklearn.isotonic import IsotonicRegression
from sklearn.feature_extraction import DictVectorizer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.metrics import brier_score_loss
from sklearn.calibration import CalibratedClassifierCV, _CalibratedClassifier
from sklearn.calibration import _sigmoid_calibration, _SigmoidCalibration
from sklearn.calibration import calibration_curve
@pytest.fixture(scope="module")
def data():
X, y = make_classification(
n_samples=200, n_features=6, random_state=42
)
return X, y
@pytest.mark.parametrize('method', ['sigmoid', 'isotonic'])
@pytest.mark.parametrize('ensemble', [True, False])
def test_calibration(data, method, ensemble):
# Test calibration objects with isotonic and sigmoid
n_samples = 100
X, y = data
sample_weight = np.random.RandomState(seed=42).uniform(size=y.size)
X -= X.min() # MultinomialNB only allows positive X
# split train and test
X_train, y_train, sw_train = \
X[:n_samples], y[:n_samples], sample_weight[:n_samples]
X_test, y_test = X[n_samples:], y[n_samples:]
# Naive-Bayes
clf = MultinomialNB().fit(X_train, y_train, sample_weight=sw_train)
prob_pos_clf = clf.predict_proba(X_test)[:, 1]
cal_clf = CalibratedClassifierCV(clf, cv=y.size + 1, ensemble=ensemble)
with pytest.raises(ValueError):
cal_clf.fit(X, y)
# Naive Bayes with calibration
for this_X_train, this_X_test in [(X_train, X_test),
(sparse.csr_matrix(X_train),
sparse.csr_matrix(X_test))]:
cal_clf = CalibratedClassifierCV(
clf, method=method, cv=5, ensemble=ensemble
)
# Note that this fit overwrites the fit on the entire training
# set
cal_clf.fit(this_X_train, y_train, sample_weight=sw_train)
prob_pos_cal_clf = cal_clf.predict_proba(this_X_test)[:, 1]
# Check that brier score has improved after calibration
assert (brier_score_loss(y_test, prob_pos_clf) >
brier_score_loss(y_test, prob_pos_cal_clf))
# Check invariance against relabeling [0, 1] -> [1, 2]
cal_clf.fit(this_X_train, y_train + 1, sample_weight=sw_train)
prob_pos_cal_clf_relabeled = cal_clf.predict_proba(this_X_test)[:, 1]
assert_array_almost_equal(prob_pos_cal_clf,
prob_pos_cal_clf_relabeled)
# Check invariance against relabeling [0, 1] -> [-1, 1]
cal_clf.fit(this_X_train, 2 * y_train - 1, sample_weight=sw_train)
prob_pos_cal_clf_relabeled = cal_clf.predict_proba(this_X_test)[:, 1]
assert_array_almost_equal(prob_pos_cal_clf, prob_pos_cal_clf_relabeled)
# Check invariance against relabeling [0, 1] -> [1, 0]
cal_clf.fit(this_X_train, (y_train + 1) % 2, sample_weight=sw_train)
prob_pos_cal_clf_relabeled = cal_clf.predict_proba(this_X_test)[:, 1]
if method == "sigmoid":
assert_array_almost_equal(prob_pos_cal_clf,
1 - prob_pos_cal_clf_relabeled)
else:
# Isotonic calibration is not invariant against relabeling
# but should improve in both cases
assert (brier_score_loss(y_test, prob_pos_clf) >
brier_score_loss((y_test + 1) % 2,
prob_pos_cal_clf_relabeled))
@pytest.mark.parametrize('ensemble', [True, False])
def test_calibration_bad_method(data, ensemble):
# Check only "isotonic" and "sigmoid" are accepted as methods
X, y = data
clf = LinearSVC()
clf_invalid_method = CalibratedClassifierCV(
clf, method="foo", ensemble=ensemble
)
with pytest.raises(ValueError):
clf_invalid_method.fit(X, y)
@pytest.mark.parametrize('ensemble', [True, False])
def test_calibration_regressor(data, ensemble):
# `base-estimator` should provide either decision_function or
# predict_proba (most regressors, for instance, should fail)
X, y = data
clf_base_regressor = \
CalibratedClassifierCV(RandomForestRegressor(), ensemble=ensemble)
with pytest.raises(RuntimeError):
clf_base_regressor.fit(X, y)
def test_calibration_default_estimator(data):
# Check base_estimator default is LinearSVC
X, y = data
calib_clf = CalibratedClassifierCV(cv=2)
calib_clf.fit(X, y)
base_est = calib_clf.calibrated_classifiers_[0].base_estimator
assert isinstance(base_est, LinearSVC)
@pytest.mark.parametrize('ensemble', [True, False])
def test_calibration_cv_splitter(data, ensemble):
# Check when `cv` is a CV splitter
X, y = data
splits = 5
kfold = KFold(n_splits=splits)
calib_clf = CalibratedClassifierCV(cv=kfold, ensemble=ensemble)
assert isinstance(calib_clf.cv, KFold)
assert calib_clf.cv.n_splits == splits
calib_clf.fit(X, y)
expected_n_clf = splits if ensemble else 1
assert len(calib_clf.calibrated_classifiers_) == expected_n_clf
@pytest.mark.parametrize('method', ['sigmoid', 'isotonic'])
@pytest.mark.parametrize('ensemble', [True, False])
def test_sample_weight(data, method, ensemble):
n_samples = 100
X, y = data
sample_weight = np.random.RandomState(seed=42).uniform(size=len(y))
X_train, y_train, sw_train = \
X[:n_samples], y[:n_samples], sample_weight[:n_samples]
X_test = X[n_samples:]
base_estimator = LinearSVC(random_state=42)
calibrated_clf = CalibratedClassifierCV(
base_estimator, method=method, ensemble=ensemble
)
calibrated_clf.fit(X_train, y_train, sample_weight=sw_train)
probs_with_sw = calibrated_clf.predict_proba(X_test)
# As the weights are used for the calibration, they should still yield
# different predictions
calibrated_clf.fit(X_train, y_train)
probs_without_sw = calibrated_clf.predict_proba(X_test)
diff = np.linalg.norm(probs_with_sw - probs_without_sw)
assert diff > 0.1
@pytest.mark.parametrize('method', ['sigmoid', 'isotonic'])
@pytest.mark.parametrize('ensemble', [True, False])
def test_parallel_execution(data, method, ensemble):
"""Test parallel calibration"""
X, y = data
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
base_estimator = LinearSVC(random_state=42)
cal_clf_parallel = CalibratedClassifierCV(
base_estimator, method=method, n_jobs=2, ensemble=ensemble
)
cal_clf_parallel.fit(X_train, y_train)
probs_parallel = cal_clf_parallel.predict_proba(X_test)
cal_clf_sequential = CalibratedClassifierCV(
base_estimator, method=method, n_jobs=1, ensemble=ensemble
)
cal_clf_sequential.fit(X_train, y_train)
probs_sequential = cal_clf_sequential.predict_proba(X_test)
assert_allclose(probs_parallel, probs_sequential)
@pytest.mark.parametrize('method', ['sigmoid', 'isotonic'])
@pytest.mark.parametrize('ensemble', [True, False])
# increase the number of RNG seeds to assess the statistical stability of this
# test:
@pytest.mark.parametrize('seed', range(2))
def test_calibration_multiclass(method, ensemble, seed):
def multiclass_brier(y_true, proba_pred, n_classes):
Y_onehot = np.eye(n_classes)[y_true]
return np.sum((Y_onehot - proba_pred) ** 2) / Y_onehot.shape[0]
# Test calibration for multiclass with classifier that implements
# only decision function.
clf = LinearSVC(random_state=7)
X, y = make_blobs(n_samples=500, n_features=100, random_state=seed,
centers=10, cluster_std=15.0)
# Use an unbalanced dataset by collapsing 8 clusters into one class
# to make the naive calibration based on a softmax more unlikely
# to work.
y[y > 2] = 2
n_classes = np.unique(y).shape[0]
X_train, y_train = X[::2], y[::2]
X_test, y_test = X[1::2], y[1::2]
clf.fit(X_train, y_train)
cal_clf = CalibratedClassifierCV(
clf, method=method, cv=5, ensemble=ensemble
)
cal_clf.fit(X_train, y_train)
probas = cal_clf.predict_proba(X_test)
# Check probabilities sum to 1
assert_allclose(np.sum(probas, axis=1), np.ones(len(X_test)))
# Check that the dataset is not too trivial, otherwise it's hard
# to get interesting calibration data during the internal
# cross-validation loop.
assert 0.65 < clf.score(X_test, y_test) < 0.95
# Check that the accuracy of the calibrated model is never degraded
# too much compared to the original classifier.
assert cal_clf.score(X_test, y_test) > 0.95 * clf.score(X_test, y_test)
# Check that Brier loss of calibrated classifier is smaller than
# loss obtained by naively turning OvR decision function to
# probabilities via a softmax
uncalibrated_brier = \
multiclass_brier(y_test, softmax(clf.decision_function(X_test)),
n_classes=n_classes)
calibrated_brier = multiclass_brier(y_test, probas,
n_classes=n_classes)
assert calibrated_brier < 1.1 * uncalibrated_brier
# Test that calibration of a multiclass classifier decreases log-loss
# for RandomForestClassifier
clf = RandomForestClassifier(n_estimators=30, random_state=42)
clf.fit(X_train, y_train)
clf_probs = clf.predict_proba(X_test)
uncalibrated_brier = multiclass_brier(y_test, clf_probs,
n_classes=n_classes)
cal_clf = CalibratedClassifierCV(
clf, method=method, cv=5, ensemble=ensemble
)
cal_clf.fit(X_train, y_train)
cal_clf_probs = cal_clf.predict_proba(X_test)
calibrated_brier = multiclass_brier(y_test, cal_clf_probs,
n_classes=n_classes)
assert calibrated_brier < 1.1 * uncalibrated_brier
def test_calibration_zero_probability():
# Test an edge case where _CalibratedClassifier avoids numerical errors
# in the multiclass normalization step if all the calibrators output
# are zero all at once for a given sample and instead fallback to uniform
# probabilities.
class ZeroCalibrator():
# This function is called from _CalibratedClassifier.predict_proba.
def predict(self, X):
return np.zeros(X.shape[0])
X, y = make_blobs(n_samples=50, n_features=10, random_state=7,
centers=10, cluster_std=15.0)
clf = DummyClassifier().fit(X, y)
calibrator = ZeroCalibrator()
cal_clf = _CalibratedClassifier(
base_estimator=clf, calibrators=[calibrator], classes=clf.classes_)
probas = cal_clf.predict_proba(X)
# Check that all probabilities are uniformly 1. / clf.n_classes_
assert_allclose(probas, 1. / clf.n_classes_)
def test_calibration_prefit():
"""Test calibration for prefitted classifiers"""
n_samples = 50
X, y = make_classification(n_samples=3 * n_samples, n_features=6,
random_state=42)
sample_weight = np.random.RandomState(seed=42).uniform(size=y.size)
X -= X.min() # MultinomialNB only allows positive X
# split train and test
X_train, y_train, sw_train = \
X[:n_samples], y[:n_samples], sample_weight[:n_samples]
X_calib, y_calib, sw_calib = \
X[n_samples:2 * n_samples], y[n_samples:2 * n_samples], \
sample_weight[n_samples:2 * n_samples]
X_test, y_test = X[2 * n_samples:], y[2 * n_samples:]
# Naive-Bayes
clf = MultinomialNB()
# Check error if clf not prefit
unfit_clf = CalibratedClassifierCV(clf, cv="prefit")
with pytest.raises(NotFittedError):
unfit_clf.fit(X_calib, y_calib)
clf.fit(X_train, y_train, sw_train)
prob_pos_clf = clf.predict_proba(X_test)[:, 1]
# Naive Bayes with calibration
for this_X_calib, this_X_test in [(X_calib, X_test),
(sparse.csr_matrix(X_calib),
sparse.csr_matrix(X_test))]:
for method in ['isotonic', 'sigmoid']:
cal_clf = CalibratedClassifierCV(clf, method=method, cv="prefit")
for sw in [sw_calib, None]:
cal_clf.fit(this_X_calib, y_calib, sample_weight=sw)
y_prob = cal_clf.predict_proba(this_X_test)
y_pred = cal_clf.predict(this_X_test)
prob_pos_cal_clf = y_prob[:, 1]
assert_array_equal(y_pred,
np.array([0, 1])[np.argmax(y_prob, axis=1)])
assert (brier_score_loss(y_test, prob_pos_clf) >
brier_score_loss(y_test, prob_pos_cal_clf))
@pytest.mark.parametrize('method', ['sigmoid', 'isotonic'])
def test_calibration_ensemble_false(data, method):
# Test that `ensemble=False` is the same as using predictions from
# `cross_val_predict` to train calibrator.
X, y = data
clf = LinearSVC(random_state=7)
cal_clf = CalibratedClassifierCV(clf, method=method, cv=3, ensemble=False)
cal_clf.fit(X, y)
cal_probas = cal_clf.predict_proba(X)
# Get probas manually
unbiased_preds = cross_val_predict(
clf, X, y, cv=3, method='decision_function'
)
if method == 'isotonic':
calibrator = IsotonicRegression(out_of_bounds='clip')
else:
calibrator = _SigmoidCalibration()
calibrator.fit(unbiased_preds, y)
# Use `clf` fit on all data
clf.fit(X, y)
clf_df = clf.decision_function(X)
manual_probas = calibrator.predict(clf_df)
assert_allclose(cal_probas[:, 1], manual_probas)
def test_sigmoid_calibration():
"""Test calibration values with Platt sigmoid model"""
exF = np.array([5, -4, 1.0])
exY = np.array([1, -1, -1])
# computed from my python port of the C++ code in LibSVM
AB_lin_libsvm = np.array([-0.20261354391187855, 0.65236314980010512])
assert_array_almost_equal(AB_lin_libsvm,
_sigmoid_calibration(exF, exY), 3)
lin_prob = 1. / (1. + np.exp(AB_lin_libsvm[0] * exF + AB_lin_libsvm[1]))
sk_prob = _SigmoidCalibration().fit(exF, exY).predict(exF)
assert_array_almost_equal(lin_prob, sk_prob, 6)
# check that _SigmoidCalibration().fit only accepts 1d array or 2d column
# arrays
with pytest.raises(ValueError):
_SigmoidCalibration().fit(np.vstack((exF, exF)), exY)
def test_calibration_curve():
"""Check calibration_curve function"""
y_true = np.array([0, 0, 0, 1, 1, 1])
y_pred = np.array([0., 0.1, 0.2, 0.8, 0.9, 1.])
prob_true, prob_pred = calibration_curve(y_true, y_pred, n_bins=2)
prob_true_unnormalized, prob_pred_unnormalized = \
calibration_curve(y_true, y_pred * 2, n_bins=2, normalize=True)
assert len(prob_true) == len(prob_pred)
assert len(prob_true) == 2
assert_almost_equal(prob_true, [0, 1])
assert_almost_equal(prob_pred, [0.1, 0.9])
assert_almost_equal(prob_true, prob_true_unnormalized)
assert_almost_equal(prob_pred, prob_pred_unnormalized)
# probabilities outside [0, 1] should not be accepted when normalize
# is set to False
with pytest.raises(ValueError):
calibration_curve([1.1], [-0.1], normalize=False)
# test that quantiles work as expected
y_true2 = np.array([0, 0, 0, 0, 1, 1])
y_pred2 = np.array([0., 0.1, 0.2, 0.5, 0.9, 1.])
prob_true_quantile, prob_pred_quantile = calibration_curve(
y_true2, y_pred2, n_bins=2, strategy='quantile')
assert len(prob_true_quantile) == len(prob_pred_quantile)
assert len(prob_true_quantile) == 2
assert_almost_equal(prob_true_quantile, [0, 2 / 3])
assert_almost_equal(prob_pred_quantile, [0.1, 0.8])
# Check that error is raised when invalid strategy is selected
with pytest.raises(ValueError):
calibration_curve(y_true2, y_pred2, strategy='percentile')
@pytest.mark.parametrize('ensemble', [True, False])
def test_calibration_nan_imputer(ensemble):
"""Test that calibration can accept nan"""
X, y = make_classification(n_samples=10, n_features=2,
n_informative=2, n_redundant=0,
random_state=42)
X[0, 0] = np.nan
clf = Pipeline(
[('imputer', SimpleImputer()),
('rf', RandomForestClassifier(n_estimators=1))])
clf_c = CalibratedClassifierCV(
clf, cv=2, method='isotonic', ensemble=ensemble
)
clf_c.fit(X, y)
clf_c.predict(X)
@pytest.mark.parametrize('ensemble', [True, False])
def test_calibration_prob_sum(ensemble):
# Test that sum of probabilities is 1. A non-regression test for
# issue #7796
num_classes = 2
X, y = make_classification(n_samples=10, n_features=5,
n_classes=num_classes)
clf = LinearSVC(C=1.0, random_state=7)
clf_prob = CalibratedClassifierCV(
clf, method="sigmoid", cv=LeaveOneOut(), ensemble=ensemble
)
clf_prob.fit(X, y)
probs = clf_prob.predict_proba(X)
assert_array_almost_equal(probs.sum(axis=1), np.ones(probs.shape[0]))
@pytest.mark.parametrize('ensemble', [True, False])
def test_calibration_less_classes(ensemble):
# Test to check calibration works fine when train set in a test-train
# split does not contain all classes
# Since this test uses LOO, at each iteration train set will not contain a
# class label
X = np.random.randn(10, 5)
y = np.arange(10)
clf = LinearSVC(C=1.0, random_state=7)
cal_clf = CalibratedClassifierCV(
clf, method="sigmoid", cv=LeaveOneOut(), ensemble=ensemble
)
cal_clf.fit(X, y)
for i, calibrated_classifier in \
enumerate(cal_clf.calibrated_classifiers_):
proba = calibrated_classifier.predict_proba(X)
if ensemble:
# Check that the unobserved class has proba=0
assert_array_equal(proba[:, i], np.zeros(len(y)))
# Check for all other classes proba>0
assert np.all(proba[:, :i] > 0)
assert np.all(proba[:, i + 1:] > 0)
else:
# Check `proba` are all 1/n_classes
assert np.allclose(proba, 1 / proba.shape[0])
@ignore_warnings(category=FutureWarning)
@pytest.mark.parametrize('X', [np.random.RandomState(42).randn(15, 5, 2),
np.random.RandomState(42).randn(15, 5, 2, 6)])
def test_calibration_accepts_ndarray(X):
"""Test that calibration accepts n-dimensional arrays as input"""
y = [1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0]
class MockTensorClassifier(BaseEstimator):
"""A toy estimator that accepts tensor inputs"""
def fit(self, X, y):
self.classes_ = np.unique(y)
return self
def decision_function(self, X):
# toy decision function that just needs to have the right shape:
return X.reshape(X.shape[0], -1).sum(axis=1)
calibrated_clf = CalibratedClassifierCV(MockTensorClassifier())
# we should be able to fit this classifier with no error
calibrated_clf.fit(X, y)
@pytest.fixture
def text_data():
text_data = [
{'state': 'NY', 'age': 'adult'},
{'state': 'TX', 'age': 'adult'},
{'state': 'VT', 'age': 'child'},
]
text_labels = [1, 0, 1]
return text_data, text_labels
@pytest.fixture
def text_data_pipeline(text_data):
X, y = text_data
pipeline_prefit = Pipeline([
('vectorizer', DictVectorizer()),
('clf', RandomForestClassifier())
])
return pipeline_prefit.fit(X, y)
def test_calibration_pipeline(text_data, text_data_pipeline):
# Test that calibration works in prefit pipeline with transformer,
# where `X` is not array-like, sparse matrix or dataframe at the start.
# See https://github.com/scikit-learn/scikit-learn/issues/8710
X, y = text_data
clf = text_data_pipeline
calib_clf = CalibratedClassifierCV(clf, cv='prefit')
calib_clf.fit(X, y)
# Check attributes are obtained from fitted estimator
assert_array_equal(calib_clf.classes_, clf.classes_)
msg = "'CalibratedClassifierCV' object has no attribute"
with pytest.raises(AttributeError, match=msg):
calib_clf.n_features_in_
@pytest.mark.parametrize('clf, cv', [
pytest.param(LinearSVC(C=1), 2),
pytest.param(LinearSVC(C=1), 'prefit'),
])
def test_calibration_attributes(clf, cv):
# Check that `n_features_in_` and `classes_` attributes created properly
X, y = make_classification(n_samples=10, n_features=5,
n_classes=2, random_state=7)
if cv == 'prefit':
clf = clf.fit(X, y)
calib_clf = CalibratedClassifierCV(clf, cv=cv)
calib_clf.fit(X, y)
if cv == 'prefit':
assert_array_equal(calib_clf.classes_, clf.classes_)
assert calib_clf.n_features_in_ == clf.n_features_in_
else:
classes = LabelEncoder().fit(y).classes_
assert_array_equal(calib_clf.classes_, classes)
assert calib_clf.n_features_in_ == X.shape[1]
# FIXME: remove in 1.1
def test_calibrated_classifier_cv_deprecation(data):
# Check that we raise the proper deprecation warning if accessing
# `calibrators_` from the `_CalibratedClassifier`.
X, y = data
calib_clf = CalibratedClassifierCV(cv=2).fit(X, y)
with pytest.warns(FutureWarning):
calibrators = calib_clf.calibrated_classifiers_[0].calibrators_
for clf1, clf2 in zip(
calibrators, calib_clf.calibrated_classifiers_[0].calibrators
):
assert clf1 is clf2
|
bsd-3-clause
|
BhavyaLight/kaggle-predicting-Red-Hat-Business-Value
|
preprocessing/feature selection.py
|
1
|
1094
|
# code to upload ( Assuming pre-processing on merged dataset done )
from sklearn.cross_validation import train_test_split
from sklearn.ensemble import RandomForestClassifier
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2)
rf=RandomForestClassifier()
rf.fit(x_train,y_train)
results=[]
def topkfeatures(rf,k):
important_features = []
unsortarr=[]
sortarr=[]
for x,i in enumerate(rf.feature_importances_):
unsortarr.append([x,i])
sortarr=sorted(unsortarr, key=lambda x: x[1], reverse=True)
#Iterate depending on variable k
for j in sortarr[:k]:
important_features.append(j[0])
return important_features
#Can try smaller intervals to find optimal range
for j in range(5,60,5):
print(j)
feature_names=x_train.columns
important_names = feature_names[topkfeatures(rf,j)]
rf1=RandomForestClassifier()
x_train_opt=x_train[important_names]
x_test_opt=x_test[important_names]
rf1.fit(x_train_opt,y_train)
results.append([j,rf1.score(x_test_opt,y_test)])
print(important_names)
print(result)
|
mit
|
geoscixyz/em_examples
|
em_examples/DCWidgetResLayer2D.py
|
1
|
28082
|
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
from SimPEG import Mesh, Maps, SolverLU, Utils
from SimPEG.Utils import ExtractCoreMesh
import numpy as np
from SimPEG.EM.Static import DC
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.pylab as pylab
from matplotlib.ticker import LogFormatter
from matplotlib.path import Path
import matplotlib.patches as patches
from scipy.constants import epsilon_0
import copy
from ipywidgets import interact, IntSlider, FloatSlider, FloatText, ToggleButtons
from .Base import widgetify
# Mesh, sigmaMap can be globals global
npad = 15
growrate = 2.
cs = 0.5
hx = [(cs, npad, -growrate), (cs, 200), (cs, npad, growrate)]
hy = [(cs, npad, -growrate), (cs, 100)]
mesh = Mesh.TensorMesh([hx, hy], "CN")
idmap = Maps.IdentityMap(mesh)
sigmaMap = idmap
dx = 5
xr = np.arange(-40, 41, dx)
dxr = np.diff(xr)
xmin = -40.
xmax = 40.
ymin = -40.
ymax = 8.
xylim = np.c_[[xmin, ymin], [xmax, ymax]]
indCC, meshcore = ExtractCoreMesh(xylim, mesh)
indx = (mesh.gridFx[:, 0] >= xmin) & (mesh.gridFx[:, 0] <= xmax) \
& (mesh.gridFx[:, 1] >= ymin) & (mesh.gridFx[:, 1] <= ymax)
indy = (mesh.gridFy[:, 0] >= xmin) & (mesh.gridFy[:, 0] <= xmax) \
& (mesh.gridFy[:, 1] >= ymin) & (mesh.gridFy[:, 1] <= ymax)
indF = np.concatenate((indx, indy))
def model_fields(A, B, zcLayer, dzLayer, xc, zc, r, sigLayer, sigTarget, sigHalf):
# Create halfspace model
mhalf = sigHalf * np.ones([mesh.nC, ])
# Add layer to model
mLayer = addLayer2Mod(zcLayer, dzLayer, mhalf, sigLayer)
# Add plate or cylinder
# fullMod = addPlate2Mod(xc,zc,dx,dz,rotAng,LayerMod,sigTarget)
mtrue = addCylinder2Mod(xc, zc, r, mLayer, sigTarget)
Mx = np.empty(shape=(0, 2))
Nx = np.empty(shape=(0, 2))
rx = DC.Rx.Dipole(Mx, Nx)
if(B == []):
src = DC.Src.Pole([rx], np.r_[A, 0.])
else:
src = DC.Src.Dipole([rx], np.r_[A, 0.], np.r_[B, 0.])
survey = DC.Survey([src])
survey_prim = DC.Survey([src])
problem = DC.Problem3D_CC(mesh, sigmaMap=sigmaMap)
problem_prim = DC.Problem3D_CC(mesh, sigmaMap=sigmaMap)
problem.Solver = SolverLU
problem_prim.Solver = SolverLU
problem.pair(survey)
problem_prim.pair(survey_prim)
primary_field = problem_prim.fields(mhalf)
total_field = problem.fields(mtrue)
return mtrue, mhalf, src, primary_field, total_field
def addLayer2Mod(zcLayer, dzLayer, modd, sigLayer):
CCLocs = mesh.gridCC
mod = copy.copy(modd)
zmax = zcLayer + dzLayer / 2.
zmin = zcLayer - dzLayer / 2.
belowInd = np.where(CCLocs[:, 1] <= zmax)[0]
aboveInd = np.where(CCLocs[:, 1] >= zmin)[0]
layerInds = list(set(belowInd).intersection(aboveInd))
# # Check selected cell centers by plotting
# fig = plt.figure()
# ax = fig.add_subplot(111)
# plt.scatter(CCLocs[layerInds,0],CCLocs[layerInds,1])
# ax.set_xlim(-40,40)
# ax.set_ylim(-35,0)
# plt.axes().set_aspect('equal')
# plt.show()
mod[layerInds] = sigLayer
return mod
def getCylinderPoints(xc, zc, r):
xLocOrig1 = np.arange(-r, r + r / 10., r / 10.)
xLocOrig2 = np.arange(r, -r - r / 10., -r / 10.)
# Top half of cylinder
zLoc1 = np.sqrt(-xLocOrig1**2. + r**2.) + zc
# Bottom half of cylinder
zLoc2 = -np.sqrt(-xLocOrig2**2. + r**2.) + zc
# Shift from x = 0 to xc
xLoc1 = xLocOrig1 + xc * np.ones_like(xLocOrig1)
xLoc2 = xLocOrig2 + xc * np.ones_like(xLocOrig2)
topHalf = np.vstack([xLoc1, zLoc1]).T
topHalf = topHalf[0:-1, :]
bottomhalf = np.vstack([xLoc2, zLoc2]).T
bottomhalf = bottomhalf[0:-1, :]
cylinderPoints = np.vstack([topHalf, bottomhalf])
cylinderPoints = np.vstack([cylinderPoints, topHalf[0, :]])
return cylinderPoints
def addCylinder2Mod(xc, zc, r, modd, sigCylinder):
# Get points for cylinder outline
cylinderPoints = getCylinderPoints(xc, zc, r)
mod = copy.copy(modd)
verts = []
codes = []
for ii in range(0, cylinderPoints.shape[0]):
verts.append(cylinderPoints[ii, :])
if(ii == 0):
codes.append(Path.MOVETO)
elif(ii == cylinderPoints.shape[0] - 1):
codes.append(Path.CLOSEPOLY)
else:
codes.append(Path.LINETO)
path = Path(verts, codes)
CCLocs = mesh.gridCC
insideInd = np.where(path.contains_points(CCLocs))
# #Check selected cell centers by plotting
# # print insideInd
# fig = plt.figure()
# ax = fig.add_subplot(111)
# patch = patches.PathPatch(path, facecolor='none', lw=2)
# ax.add_patch(patch)
# plt.scatter(CCLocs[insideInd,0],CCLocs[insideInd,1])
# ax.set_xlim(-40,40)
# ax.set_ylim(-35,0)
# plt.axes().set_aspect('equal')
# plt.show()
mod[insideInd] = sigCylinder
return mod
# def getPlateCorners(xc, zc, dx, dz, rotAng):
# # Form rotation matix
# rotMat = np.array([[np.cos(rotAng*(np.pi/180.)), -np.sin(rotAng*(np.pi/180.))],[np.sin(rotAng*(np.pi/180.)), np.cos(rotAng*(np.pi/180.))]])
# originCorners = np.array([[-0.5*dx, 0.5*dz], [0.5*dx, 0.5*dz], [-0.5*dx, -0.5*dz], [0.5*dx, -0.5*dz]])
# rotPlateCorners = np.dot(originCorners,rotMat)
# plateCorners = rotPlateCorners + np.hstack([np.repeat(xc,4).reshape([4,1]),np.repeat(zc,4).reshape([4,1])])
# return plateCorners
# def addPlate2Mod(xc, zc, dx, dz, rotAng, mod, sigPlate):
# # use matplotlib paths to find CC inside of polygon
# plateCorners = getPlateCorners(xc,zc,dx,dz,rotAng)
# verts = [
# (plateCorners[0,:]), # left, top
# (plateCorners[1,:]), # right, top
# (plateCorners[3,:]), # right, bottom
# (plateCorners[2,:]), # left, bottom
# (plateCorners[0,:]), # left, top (closes polygon)
# ]
# codes = [Path.MOVETO,
# Path.LINETO,
# Path.LINETO,
# Path.LINETO,
# Path.CLOSEPOLY,
# ]
# path = Path(verts, codes)
# CCLocs = mesh.gridCC
# insideInd = np.where(path.contains_points(CCLocs))
# #Check selected cell centers by plotting
# # print insideInd
# # fig = plt.figure()
# # ax = fig.add_subplot(111)
# # patch = patches.PathPatch(path, facecolor='none', lw=2)
# # ax.add_patch(patch)
# # plt.scatter(CCLocs[insideInd,0],CCLocs[insideInd,1])
# # ax.set_xlim(-10,10)
# # ax.set_ylim(-20,0)
# # plt.axes().set_aspect('equal')
# # plt.show()
# mod[insideInd] = sigPlate
# return mod
def get_Surface_Potentials(survey, src, field_obj):
phi = field_obj[src, 'phi']
CCLoc = mesh.gridCC
zsurfaceLoc = np.max(CCLoc[:, 1])
surfaceInd = np.where(CCLoc[:, 1] == zsurfaceLoc)
phiSurface = phi[surfaceInd]
xSurface = CCLoc[surfaceInd, 0].T
phiScale = 0.
if(survey == "Pole-Dipole" or survey == "Pole-Pole"):
refInd = Utils.closestPoints(mesh, [xmax + 60., 0.], gridLoc='CC')
# refPoint = CCLoc[refInd]
# refSurfaceInd = np.where(xSurface == refPoint[0])
# phiScale = np.median(phiSurface)
phiScale = phi[refInd]
phiSurface = phiSurface - phiScale
return xSurface, phiSurface, phiScale
def sumCylinderCharges(xc, zc, r, qSecondary):
chargeRegionVerts = getCylinderPoints(xc, zc, r + 0.5)
codes = chargeRegionVerts.shape[0] * [Path.LINETO]
codes[0] = Path.MOVETO
codes[-1] = Path.CLOSEPOLY
chargeRegionPath = Path(chargeRegionVerts, codes)
CCLocs = mesh.gridCC
chargeRegionInsideInd = np.where(chargeRegionPath.contains_points(CCLocs))
plateChargeLocs = CCLocs[chargeRegionInsideInd]
plateCharge = qSecondary[chargeRegionInsideInd]
posInd = np.where(plateCharge >= 0)
negInd = np.where(plateCharge < 0)
qPos = Utils.mkvc(plateCharge[posInd])
qNeg = Utils.mkvc(plateCharge[negInd])
qPosLoc = plateChargeLocs[posInd, :][0]
qNegLoc = plateChargeLocs[negInd, :][0]
qPosData = np.vstack([qPosLoc[:, 0], qPosLoc[:, 1], qPos]).T
qNegData = np.vstack([qNegLoc[:, 0], qNegLoc[:, 1], qNeg]).T
if qNeg.shape == (0,) or qPos.shape == (0,):
qNegAvgLoc = np.r_[-10, -10]
qPosAvgLoc = np.r_[+10, -10]
else:
qNegAvgLoc = np.average(qNegLoc, axis=0, weights=qNeg)
qPosAvgLoc = np.average(qPosLoc, axis=0, weights=qPos)
qPosSum = np.sum(qPos)
qNegSum = np.sum(qNeg)
# # Check things by plotting
# fig = plt.figure()
# ax = fig.add_subplot(111)
# platePatch = patches.PathPatch(platePath, facecolor='none', lw=2)
# ax.add_patch(platePatch)
# chargeRegionPatch = patches.PathPatch(chargeRegionPath, facecolor='none', lw=2)
# ax.add_patch(chargeRegionPatch)
# plt.scatter(qNegAvgLoc[0],qNegAvgLoc[1],color='b')
# plt.scatter(qPosAvgLoc[0],qPosAvgLoc[1],color='r')
# ax.set_xlim(-15,5)
# ax.set_ylim(-25,-5)
# plt.axes().set_aspect('equal')
# plt.show()
return qPosSum, qNegSum, qPosAvgLoc, qNegAvgLoc
def getSensitivity(survey, A, B, M, N, model):
if(survey == "Dipole-Dipole"):
rx = DC.Rx.Dipole(np.r_[M, 0.], np.r_[N, 0.])
src = DC.Src.Dipole([rx], np.r_[A, 0.], np.r_[B, 0.])
elif(survey == "Pole-Dipole"):
rx = DC.Rx.Dipole(np.r_[M, 0.], np.r_[N, 0.])
src = DC.Src.Pole([rx], np.r_[A, 0.])
elif(survey == "Dipole-Pole"):
rx = DC.Rx.Pole(np.r_[M, 0.])
src = DC.Src.Dipole([rx], np.r_[A, 0.], np.r_[B, 0.])
elif(survey == "Pole-Pole"):
rx = DC.Rx.Pole(np.r_[M, 0.])
src = DC.Src.Pole([rx], np.r_[A, 0.])
survey = DC.Survey([src])
problem = DC.Problem3D_CC(mesh, sigmaMap=sigmaMap)
problem.Solver = SolverLU
problem.pair(survey)
fieldObj = problem.fields(model)
J = problem.Jtvec(model, np.array([1.]), f=fieldObj)
return J
def calculateRhoA(survey, VM, VN, A, B, M, N):
eps = 1e-9 # to stabilize division
if(survey == "Dipole-Dipole"):
G = 1. / (1. / (np.abs(A - M) + eps) - 1. / (np.abs(M - B) + eps) -
1. / (np.abs(N - A) + eps) + 1. / (np.abs(N - B) + eps))
rho_a = (VM - VN) * 2. * np.pi * G
elif(survey == "Pole-Dipole"):
G = 1. / (1. / (np.abs(A - M) + eps) - 1. / (np.abs(N - A) + eps))
rho_a = (VM - VN) * 2. * np.pi * G
elif(survey == "Dipole-Pole"):
G = 1. / (1. / (np.abs(A - M) + eps) - 1. / (np.abs(M - B) + eps))
rho_a = (VM) * 2. * np.pi * G
elif(survey == "Pole-Pole"):
G = 1. / (1. / (np.abs(A - M) + eps))
rho_a = (VM) * 2. * np.pi * G
return rho_a
# Inline functions for computing apparent resistivity
# eps = 1e-9 #to stabilize division
# G = lambda A, B, M, N: 1. / ( 1./(np.abs(A-M)+eps) - 1./(np.abs(M-B)+eps) - 1./(np.abs(N-A)+eps) + 1./(np.abs(N-B)+eps) )
# rho_a = lambda VM,VN, A,B,M,N: (VM-VN)*2.*np.pi*G(A,B,M,N)
def plot_Surface_Potentials(survey, A, B, M, N, zcLayer, dzLayer, xc, zc, r, rhoHalf, rhoLayer, rhoTarget, Field, Type, Scale):
labelsize = 16.
ticksize = 16.
sigTarget = 1. / rhoTarget
# rhoLayer = np.exp(logRhoLayer)
sigLayer = 1. / rhoLayer
sigHalf = 1. / rhoHalf
if(survey == "Pole-Dipole" or survey == "Pole-Pole"):
B = []
mtrue, mhalf, src, primary_field, total_field = model_fields(
A, B, zcLayer, dzLayer, xc, zc, r, sigLayer, sigTarget, sigHalf)
fig, ax = plt.subplots(2, 1, figsize=(9 * 1.5, 9 * 1.8), sharex=True)
fig.subplots_adjust(right=0.8, wspace=0.05, hspace=0.05)
xSurface, phiTotalSurface, phiScaleTotal = get_Surface_Potentials(
survey, src, total_field)
xSurface, phiPrimSurface, phiScalePrim = get_Surface_Potentials(
survey, src, primary_field)
ylim = np.r_[-1., 1.] * np.max(np.abs(phiTotalSurface))
xlim = np.array([-40, 40])
if(survey == "Dipole-Pole" or survey == "Pole-Pole"):
MInd = np.where(xSurface == M)
N = []
VM = phiTotalSurface[MInd[0]]
VN = 0.
VMprim = phiPrimSurface[MInd[0]]
VNprim = 0.
else:
MInd = np.where(xSurface == M)
NInd = np.where(xSurface == N)
VM = phiTotalSurface[MInd[0]]
VN = phiTotalSurface[NInd[0]]
VMprim = phiPrimSurface[MInd[0]]
VNprim = phiPrimSurface[NInd[0]]
# 2D geometric factor
G2D = rhoHalf / (calculateRhoA(survey, VMprim, VNprim, A, B, M, N))
ax[0].plot(xSurface, phiTotalSurface, color=[0.1, 0.5, 0.1], linewidth=2)
ax[0].plot(xSurface, phiPrimSurface,
linestyle='dashed', linewidth=0.5, color='k')
ax[0].grid(which='both', linestyle='-', linewidth=0.5,
color=[0.2, 0.2, 0.2], alpha=0.5)
if(survey == "Pole-Dipole" or survey == "Pole-Pole"):
ax[0].plot(A, 0, '+', markersize=12,
markeredgewidth=3, color=[1., 0., 0])
else:
ax[0].plot(A, 0, '+', markersize=12,
markeredgewidth=3, color=[1., 0., 0])
ax[0].plot(B, 0, '_', markersize=12,
markeredgewidth=3, color=[0., 0., 1.])
ax[0].set_ylabel('Potential, (V)', fontsize=14)
ax[0].set_xlabel('x (m)', fontsize=14)
ax[0].set_xlim(xlim)
ax[0].set_ylim(ylim)
if(survey == "Dipole-Pole" or survey == "Pole-Pole"):
ax[0].plot(M, VM, 'o', color='k')
xytextM = (
M + 0.5, np.max([np.min([VM, ylim.max()]), ylim.min()]) + 0.5)
ax[0].annotate('%2.1e' % (VM), xy=xytextM,
xytext=xytextM, fontsize=labelsize)
else:
ax[0].plot(M, VM, 'o', color='k')
ax[0].plot(N, VN, 'o', color='k')
xytextM = (
M + 0.5, np.max([np.min([VM, ylim.max()]), ylim.min()]) + 1.)
xytextN = (
N + 0.5, np.max([np.min([VN, ylim.max()]), ylim.min()]) + 1.)
ax[0].annotate('%2.1e' % (VM), xy=xytextM,
xytext=xytextM, fontsize=labelsize)
ax[0].annotate('%2.1e' % (VN), xy=xytextN,
xytext=xytextN, fontsize=labelsize)
ax[0].tick_params(axis='both', which='major', labelsize=ticksize)
props = dict(boxstyle='round', facecolor='grey', alpha=0.4)
ax[0].text(xlim.max() + 1, ylim.max() - 0.1 * ylim.max(), '$\\rho_a$ = %2.2f' % (G2D * calculateRhoA(survey, VM, VN, A, B, M, N)),
verticalalignment='bottom', bbox=props, fontsize=labelsize)
ax[0].legend(['Model Potential', 'Layered Earth Potential'],
loc=3, fontsize=labelsize)
if Field == 'Model':
label = 'Resisitivity (ohm-m)'
xtype = 'CC'
view = 'real'
streamOpts = None
ind = indCC
formatter = "%.1e"
pcolorOpts = {"cmap": "jet_r"}
if Scale == 'Log':
pcolorOpts = {'norm': matplotlib.colors.LogNorm(), "cmap": "jet_r"}
if Type == 'Total':
u = 1. / (sigmaMap * mtrue)
elif Type == 'Primary':
u = 1. / (sigmaMap * mhalf)
elif Type == 'Secondary':
u = 1. / (sigmaMap * mtrue) - 1. / (sigmaMap * mhalf)
if Scale == 'Log':
linthresh = 10.
pcolorOpts = {'norm': matplotlib.colors.SymLogNorm(
linthresh=linthresh, linscale=0.2), "cmap": "jet_r"}
elif Field == 'Potential':
label = 'Potential (V)'
xtype = 'CC'
view = 'real'
streamOpts = None
ind = indCC
formatter = "%.1e"
pcolorOpts = {"cmap": "viridis"}
if Scale == 'Log':
linthresh = 10.
pcolorOpts = {'norm': matplotlib.colors.SymLogNorm(
linthresh=linthresh, linscale=0.2), "cmap": "viridis"}
if Type == 'Total':
# formatter = LogFormatter(10, labelOnlyBase=False)
# pcolorOpts = {'norm':matplotlib.colors.SymLogNorm(linthresh=10, linscale=0.1)}
u = total_field[src, 'phi'] - phiScaleTotal
elif Type == 'Primary':
# formatter = LogFormatter(10, labelOnlyBase=False)
# pcolorOpts = {'norm':matplotlib.colors.SymLogNorm(linthresh=10, linscale=0.1)}
u = primary_field[src, 'phi'] - phiScalePrim
elif Type == 'Secondary':
# formatter = None
# pcolorOpts = {"cmap":"viridis"}
uTotal = total_field[src, 'phi'] - phiScaleTotal
uPrim = primary_field[src, 'phi'] - phiScalePrim
u = uTotal - uPrim
elif Field == 'E':
label = 'Electric Field (V/m)'
xtype = 'F'
view = 'vec'
streamOpts = {'color': 'w'}
ind = indF
#formatter = LogFormatter(10, labelOnlyBase=False)
pcolorOpts = {"cmap": "viridis"}
if Scale == 'Log':
pcolorOpts = {'norm': matplotlib.colors.LogNorm(),
"cmap": "viridis"}
formatter = "%.1e"
if Type == 'Total':
u = total_field[src, 'e']
elif Type == 'Primary':
u = primary_field[src, 'e']
elif Type == 'Secondary':
uTotal = total_field[src, 'e']
uPrim = primary_field[src, 'e']
u = uTotal - uPrim
elif Field == 'J':
label = 'Current density ($A/m^2$)'
xtype = 'F'
view = 'vec'
streamOpts = {'color': 'w'}
ind = indF
#formatter = LogFormatter(10, labelOnlyBase=False)
pcolorOpts = {"cmap": "viridis"}
if Scale == 'Log':
pcolorOpts = {'norm': matplotlib.colors.LogNorm(),
"cmap": "viridis"}
formatter = "%.1e"
if Type == 'Total':
u = total_field[src, 'j']
elif Type == 'Primary':
u = primary_field[src, 'j']
elif Type == 'Secondary':
uTotal = total_field[src, 'j']
uPrim = primary_field[src, 'j']
u = uTotal - uPrim
elif Field == 'Charge':
label = 'Charge Density ($C/m^2$)'
xtype = 'CC'
view = 'real'
streamOpts = None
ind = indCC
# formatter = LogFormatter(10, labelOnlyBase=False)
pcolorOpts = {"cmap": "RdBu_r"}
if Scale == 'Log':
linthresh = 1e-12
pcolorOpts = {'norm': matplotlib.colors.SymLogNorm(
linthresh=linthresh, linscale=0.2), "cmap": "RdBu_r"}
formatter = "%.1e"
if Type == 'Total':
u = total_field[src, 'charge']
elif Type == 'Primary':
u = primary_field[src, 'charge']
elif Type == 'Secondary':
uTotal = total_field[src, 'charge']
uPrim = primary_field[src, 'charge']
u = uTotal - uPrim
elif Field == 'Sensitivity':
label = 'Sensitivity'
xtype = 'CC'
view = 'real'
streamOpts = None
ind = indCC
# formatter = None
# pcolorOpts = {"cmap":"viridis"}
# formatter = LogFormatter(10, labelOnlyBase=False)
pcolorOpts = {"cmap": "viridis"}
if Scale == 'Log':
linthresh = 1.
pcolorOpts = {'norm': matplotlib.colors.SymLogNorm(
linthresh=linthresh, linscale=0.2), "cmap": "viridis"}
# formatter = formatter = "$10^{%.1f}$"
formatter = "%.1e"
if Type == 'Total':
u = getSensitivity(survey, A, B, M, N, mtrue)
elif Type == 'Primary':
u = getSensitivity(survey, A, B, M, N, mhalf)
elif Type == 'Secondary':
uTotal = getSensitivity(survey, A, B, M, N, mtrue)
uPrim = getSensitivity(survey, A, B, M, N, mhalf)
u = uTotal - uPrim
if Scale == 'Log':
eps = 1e-16
else:
eps = 0.
dat = meshcore.plotImage(u[ind] + eps, vType=xtype, ax=ax[1], grid=False, view=view,
streamOpts=streamOpts, pcolorOpts=pcolorOpts) # gridOpts={'color':'k', 'alpha':0.5}
# Get cylinder outline
cylinderPoints = getCylinderPoints(xc, zc, r)
if(rhoTarget != rhoHalf):
ax[1].plot(cylinderPoints[:, 0], cylinderPoints[
:, 1], linestyle='dashed', color='k')
if(rhoLayer != rhoHalf):
layerX = np.arange(xmin, xmax + 1)
layerTopY = (zcLayer + dzLayer / 2.) * np.ones_like(layerX)
layerBottomY = (zcLayer - dzLayer / 2.) * np.ones_like(layerX)
ax[1].plot(layerX, layerTopY, linestyle='dashed', color='k')
ax[1].plot(layerX, layerBottomY, linestyle='dashed', color='k')
if (Field == 'Charge') and (Type != 'Primary') and (Type != 'Total'):
qTotal = total_field[src, 'charge']
qPrim = primary_field[src, 'charge']
qSecondary = qTotal - qPrim
qPosSum, qNegSum, qPosAvgLoc, qNegAvgLoc = sumCylinderCharges(
xc, zc, r, qSecondary)
ax[1].plot(qPosAvgLoc[0], qPosAvgLoc[1], marker='.',
color='black', markersize=labelsize)
ax[1].plot(qNegAvgLoc[0], qNegAvgLoc[1], marker='.',
color='black', markersize=labelsize)
if(qPosAvgLoc[0] > qNegAvgLoc[0]):
xytext_qPos = (qPosAvgLoc[0] + 1., qPosAvgLoc[1] - 0.5)
xytext_qNeg = (qNegAvgLoc[0] - 15., qNegAvgLoc[1] - 0.5)
else:
xytext_qPos = (qPosAvgLoc[0] - 15., qPosAvgLoc[1] - 0.5)
xytext_qNeg = (qNegAvgLoc[0] + 1., qNegAvgLoc[1] - 0.5)
ax[1].annotate('+Q = %2.1e' % (qPosSum), xy=xytext_qPos,
xytext=xytext_qPos, fontsize=labelsize)
ax[1].annotate('-Q = %2.1e' % (qNegSum), xy=xytext_qNeg,
xytext=xytext_qNeg, fontsize=labelsize)
ax[1].set_xlabel('x (m)', fontsize=labelsize)
ax[1].set_ylabel('z (m)', fontsize=labelsize)
if(survey == "Dipole-Dipole"):
ax[1].plot(A, 1., marker='v', color='red', markersize=labelsize)
ax[1].plot(B, 1., marker='v', color='blue', markersize=labelsize)
ax[1].plot(M, 1., marker='^', color='yellow', markersize=labelsize)
ax[1].plot(N, 1., marker='^', color='green', markersize=labelsize)
xytextA1 = (A - 0.5, 2.5)
xytextB1 = (B - 0.5, 2.5)
xytextM1 = (M - 0.5, 2.5)
xytextN1 = (N - 0.5, 2.5)
ax[1].annotate('A', xy=xytextA1, xytext=xytextA1, fontsize=labelsize)
ax[1].annotate('B', xy=xytextB1, xytext=xytextB1, fontsize=labelsize)
ax[1].annotate('M', xy=xytextM1, xytext=xytextM1, fontsize=labelsize)
ax[1].annotate('N', xy=xytextN1, xytext=xytextN1, fontsize=labelsize)
elif(survey == "Pole-Dipole"):
ax[1].plot(A, 1., marker='v', color='red', markersize=labelsize)
ax[1].plot(M, 1., marker='^', color='yellow', markersize=labelsize)
ax[1].plot(N, 1., marker='^', color='green', markersize=labelsize)
xytextA1 = (A - 0.5, 2.5)
xytextM1 = (M - 0.5, 2.5)
xytextN1 = (N - 0.5, 2.5)
ax[1].annotate('A', xy=xytextA1, xytext=xytextA1, fontsize=labelsize)
ax[1].annotate('M', xy=xytextM1, xytext=xytextM1, fontsize=labelsize)
ax[1].annotate('N', xy=xytextN1, xytext=xytextN1, fontsize=labelsize)
elif(survey == "Dipole-Pole"):
ax[1].plot(A, 1., marker='v', color='red', markersize=labelsize)
ax[1].plot(B, 1., marker='v', color='blue', markersize=labelsize)
ax[1].plot(M, 1., marker='^', color='yellow', markersize=labelsize)
xytextA1 = (A - 0.5, 2.5)
xytextB1 = (B - 0.5, 2.5)
xytextM1 = (M - 0.5, 2.5)
ax[1].annotate('A', xy=xytextA1, xytext=xytextA1, fontsize=labelsize)
ax[1].annotate('B', xy=xytextB1, xytext=xytextB1, fontsize=labelsize)
ax[1].annotate('M', xy=xytextM1, xytext=xytextM1, fontsize=labelsize)
elif(survey == "Pole-Pole"):
ax[1].plot(A, 1., marker='v', color='red', markersize=labelsize)
ax[1].plot(M, 1., marker='^', color='yellow', markersize=labelsize)
xytextA1 = (A - 0.5, 2.5)
xytextM1 = (M - 0.5, 2.5)
ax[1].annotate('A', xy=xytextA1, xytext=xytextA1, fontsize=labelsize)
ax[1].annotate('M', xy=xytextM1, xytext=xytextM1, fontsize=labelsize)
ax[1].tick_params(axis='both', which='major', labelsize=ticksize)
cbar_ax = fig.add_axes([0.8, 0.05, 0.08, 0.5])
cbar_ax.axis('off')
vmin, vmax = dat[0].get_clim()
if Scale == 'Log':
if (Field == 'E') or (Field == 'J'):
cb = plt.colorbar(dat[0], ax=cbar_ax, format=formatter, ticks=np.logspace(
np.log10(vmin), np.log10(vmax), 5))
elif (Field == 'Model'):
if (Type == 'Secondary'):
cb = plt.colorbar(dat[0], ax=cbar_ax, format=formatter, ticks=np.r_[
np.minimum(0., vmin), np.maximum(0., vmax)])
else:
cb = plt.colorbar(dat[0], ax=cbar_ax, format=formatter, ticks=np.logspace(
np.log10(vmin), np.log10(vmax), 5))
else:
cb = plt.colorbar(dat[0], ax=cbar_ax, format=formatter, ticks=np.r_[-1. * np.logspace(
np.log10(-vmin - eps), np.log10(linthresh), 3)[:-1], 0., np.logspace(np.log10(linthresh), np.log10(vmax), 3)[1:]])
else:
if (Field == 'Model') and (Type == 'Secondary'):
cb = plt.colorbar(dat[0], ax=cbar_ax, format=formatter, ticks=np.r_[
np.minimum(0., vmin), np.maximum(0., vmax)])
else:
cb = plt.colorbar(
dat[0], ax=cbar_ax, format=formatter, ticks=np.linspace(vmin, vmax, 5))
cb.ax.tick_params(labelsize=ticksize)
cb.set_label(label, fontsize=labelsize)
ax[1].set_xlim([-40., 40.])
ax[1].set_ylim([-40., 8.])
ax[1].set_aspect('equal')
plt.show()
def ResLayer_app():
app = widgetify(plot_Surface_Potentials,
survey=ToggleButtons(options=[
'Dipole-Dipole', 'Dipole-Pole', 'Pole-Dipole', 'Pole-Pole'], value='Dipole-Dipole'),
zcLayer=FloatSlider(min=-10., max=0., step=1., value=-10.,
continuous_update=False, description="$zc_{layer}$"),
dzLayer=FloatSlider(min=0.5, max=5., step=0.5, value=1.,
continuous_update=False, description="$dz_{layer}$"),
rhoLayer=FloatText(
min=1e-8, max=1e8, value=5000., continuous_update=False, description='$\\rho_{2}$'),
xc=FloatSlider(min=-30., max=30., step=1.,
value=0., continuous_update=False),
zc=FloatSlider(min=-30., max=-15., step=0.5,
value=-25., continuous_update=False),
r=FloatSlider(min=1., max=10., step=0.5,
value=5., continuous_update=False),
rhoHalf=FloatText(
min=1e-8, max=1e8, value=500., continuous_update=False, description='$\\rho_{1}$'),
rhoTarget=FloatText(
min=1e-8, max=1e8, value=500., continuous_update=False, description='$\\rho_{3}$'),
A=FloatSlider(min=-30.25, max=30.25, step=0.5,
value=-30.25, continuous_update=False),
B=FloatSlider(min=-30.25, max=30.25, step=0.5,
value=30.25, continuous_update=False),
M=FloatSlider(min=-30.25, max=30.25, step=0.5,
value=-10.25, continuous_update=False),
N=FloatSlider(min=-30.25, max=30.25, step=0.5,
value=10.25, continuous_update=False),
Field=ToggleButtons(
options=['Model', 'Potential', 'E', 'J', 'Charge', 'Sensitivity'], value='Model'),
Type=ToggleButtons(
options=['Total', 'Primary', 'Secondary'], value='Total'),
Scale=ToggleButtons(
options=['Linear', 'Log'], value='Linear')
)
return app
|
mit
|
dwettstein/pattern-recognition-2016
|
mlp/model_selection/tests/test_validation.py
|
18
|
28537
|
"""Test the validation module"""
from __future__ import division
import sys
import warnings
import numpy as np
from scipy.sparse import coo_matrix, csr_matrix
from sklearn.utils.testing import assert_true
from sklearn.utils.testing import assert_false
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_almost_equal
from sklearn.utils.testing import assert_raises
from sklearn.utils.testing import assert_raise_message
from sklearn.utils.testing import assert_greater
from sklearn.utils.testing import assert_less
from sklearn.utils.testing import assert_array_almost_equal
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_warns
from sklearn.utils.mocking import CheckingClassifier, MockDataFrame
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import cross_val_predict
from sklearn.model_selection import permutation_test_score
from sklearn.model_selection import KFold
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import LeaveOneOut
from sklearn.model_selection import LeaveOneLabelOut
from sklearn.model_selection import LeavePLabelOut
from sklearn.model_selection import LabelKFold
from sklearn.model_selection import LabelShuffleSplit
from sklearn.model_selection import learning_curve
from sklearn.model_selection import validation_curve
from sklearn.model_selection._validation import _check_is_permutation
from sklearn.datasets import make_regression
from sklearn.datasets import load_boston
from sklearn.datasets import load_iris
from sklearn.metrics import explained_variance_score
from sklearn.metrics import make_scorer
from sklearn.metrics import precision_score
from sklearn.linear_model import Ridge
from sklearn.linear_model import PassiveAggressiveClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.cluster import KMeans
from sklearn.preprocessing import Imputer
from sklearn.pipeline import Pipeline
from sklearn.externals.six.moves import cStringIO as StringIO
from sklearn.base import BaseEstimator
from sklearn.multiclass import OneVsRestClassifier
from sklearn.datasets import make_classification
from sklearn.datasets import make_multilabel_classification
from test_split import MockClassifier
class MockImprovingEstimator(BaseEstimator):
"""Dummy classifier to test the learning curve"""
def __init__(self, n_max_train_sizes):
self.n_max_train_sizes = n_max_train_sizes
self.train_sizes = 0
self.X_subset = None
def fit(self, X_subset, y_subset=None):
self.X_subset = X_subset
self.train_sizes = X_subset.shape[0]
return self
def predict(self, X):
raise NotImplementedError
def score(self, X=None, Y=None):
# training score becomes worse (2 -> 1), test error better (0 -> 1)
if self._is_training_data(X):
return 2. - float(self.train_sizes) / self.n_max_train_sizes
else:
return float(self.train_sizes) / self.n_max_train_sizes
def _is_training_data(self, X):
return X is self.X_subset
class MockIncrementalImprovingEstimator(MockImprovingEstimator):
"""Dummy classifier that provides partial_fit"""
def __init__(self, n_max_train_sizes):
super(MockIncrementalImprovingEstimator,
self).__init__(n_max_train_sizes)
self.x = None
def _is_training_data(self, X):
return self.x in X
def partial_fit(self, X, y=None, **params):
self.train_sizes += X.shape[0]
self.x = X[0]
class MockEstimatorWithParameter(BaseEstimator):
"""Dummy classifier to test the validation curve"""
def __init__(self, param=0.5):
self.X_subset = None
self.param = param
def fit(self, X_subset, y_subset):
self.X_subset = X_subset
self.train_sizes = X_subset.shape[0]
return self
def predict(self, X):
raise NotImplementedError
def score(self, X=None, y=None):
return self.param if self._is_training_data(X) else 1 - self.param
def _is_training_data(self, X):
return X is self.X_subset
# XXX: use 2D array, since 1D X is being detected as a single sample in
# check_consistent_length
X = np.ones((10, 2))
X_sparse = coo_matrix(X)
y = np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4])
# The number of samples per class needs to be > n_folds, for StratifiedKFold(3)
y2 = np.array([1, 1, 1, 2, 2, 2, 3, 3, 3, 3])
def test_cross_val_score():
clf = MockClassifier()
for a in range(-10, 10):
clf.a = a
# Smoke test
scores = cross_val_score(clf, X, y2)
assert_array_equal(scores, clf.score(X, y2))
# test with multioutput y
multioutput_y = np.column_stack([y2, y2[::-1]])
scores = cross_val_score(clf, X_sparse, multioutput_y)
assert_array_equal(scores, clf.score(X_sparse, multioutput_y))
scores = cross_val_score(clf, X_sparse, y2)
assert_array_equal(scores, clf.score(X_sparse, y2))
# test with multioutput y
scores = cross_val_score(clf, X_sparse, multioutput_y)
assert_array_equal(scores, clf.score(X_sparse, multioutput_y))
# test with X and y as list
list_check = lambda x: isinstance(x, list)
clf = CheckingClassifier(check_X=list_check)
scores = cross_val_score(clf, X.tolist(), y2.tolist())
clf = CheckingClassifier(check_y=list_check)
scores = cross_val_score(clf, X, y2.tolist())
assert_raises(ValueError, cross_val_score, clf, X, y2, scoring="sklearn")
# test with 3d X and
X_3d = X[:, :, np.newaxis]
clf = MockClassifier(allow_nd=True)
scores = cross_val_score(clf, X_3d, y2)
clf = MockClassifier(allow_nd=False)
assert_raises(ValueError, cross_val_score, clf, X_3d, y2)
def test_cross_val_score_predict_labels():
# Check if ValueError (when labels is None) propagates to cross_val_score
# and cross_val_predict
# And also check if labels is correctly passed to the cv object
X, y = make_classification(n_samples=20, n_classes=2, random_state=0)
clf = SVC(kernel="linear")
label_cvs = [LeaveOneLabelOut(), LeavePLabelOut(2), LabelKFold(),
LabelShuffleSplit()]
for cv in label_cvs:
assert_raise_message(ValueError,
"The labels parameter should not be None",
cross_val_score, estimator=clf, X=X, y=y, cv=cv)
assert_raise_message(ValueError,
"The labels parameter should not be None",
cross_val_predict, estimator=clf, X=X, y=y, cv=cv)
def test_cross_val_score_pandas():
# check cross_val_score doesn't destroy pandas dataframe
types = [(MockDataFrame, MockDataFrame)]
try:
from pandas import Series, DataFrame
types.append((Series, DataFrame))
except ImportError:
pass
for TargetType, InputFeatureType in types:
# X dataframe, y series
# 3 fold cross val is used so we need atleast 3 samples per class
X_df, y_ser = InputFeatureType(X), TargetType(y2)
check_df = lambda x: isinstance(x, InputFeatureType)
check_series = lambda x: isinstance(x, TargetType)
clf = CheckingClassifier(check_X=check_df, check_y=check_series)
cross_val_score(clf, X_df, y_ser)
def test_cross_val_score_mask():
# test that cross_val_score works with boolean masks
svm = SVC(kernel="linear")
iris = load_iris()
X, y = iris.data, iris.target
kfold = KFold(5)
scores_indices = cross_val_score(svm, X, y, cv=kfold)
kfold = KFold(5)
cv_masks = []
for train, test in kfold.split(X, y):
mask_train = np.zeros(len(y), dtype=np.bool)
mask_test = np.zeros(len(y), dtype=np.bool)
mask_train[train] = 1
mask_test[test] = 1
cv_masks.append((train, test))
scores_masks = cross_val_score(svm, X, y, cv=cv_masks)
assert_array_equal(scores_indices, scores_masks)
def test_cross_val_score_precomputed():
# test for svm with precomputed kernel
svm = SVC(kernel="precomputed")
iris = load_iris()
X, y = iris.data, iris.target
linear_kernel = np.dot(X, X.T)
score_precomputed = cross_val_score(svm, linear_kernel, y)
svm = SVC(kernel="linear")
score_linear = cross_val_score(svm, X, y)
assert_array_equal(score_precomputed, score_linear)
# Error raised for non-square X
svm = SVC(kernel="precomputed")
assert_raises(ValueError, cross_val_score, svm, X, y)
# test error is raised when the precomputed kernel is not array-like
# or sparse
assert_raises(ValueError, cross_val_score, svm,
linear_kernel.tolist(), y)
def test_cross_val_score_fit_params():
clf = MockClassifier()
n_samples = X.shape[0]
n_classes = len(np.unique(y))
W_sparse = coo_matrix((np.array([1]), (np.array([1]), np.array([0]))),
shape=(10, 1))
P_sparse = coo_matrix(np.eye(5))
DUMMY_INT = 42
DUMMY_STR = '42'
DUMMY_OBJ = object()
def assert_fit_params(clf):
# Function to test that the values are passed correctly to the
# classifier arguments for non-array type
assert_equal(clf.dummy_int, DUMMY_INT)
assert_equal(clf.dummy_str, DUMMY_STR)
assert_equal(clf.dummy_obj, DUMMY_OBJ)
fit_params = {'sample_weight': np.ones(n_samples),
'class_prior': np.ones(n_classes) / n_classes,
'sparse_sample_weight': W_sparse,
'sparse_param': P_sparse,
'dummy_int': DUMMY_INT,
'dummy_str': DUMMY_STR,
'dummy_obj': DUMMY_OBJ,
'callback': assert_fit_params}
cross_val_score(clf, X, y, fit_params=fit_params)
def test_cross_val_score_score_func():
clf = MockClassifier()
_score_func_args = []
def score_func(y_test, y_predict):
_score_func_args.append((y_test, y_predict))
return 1.0
with warnings.catch_warnings(record=True):
scoring = make_scorer(score_func)
score = cross_val_score(clf, X, y, scoring=scoring)
assert_array_equal(score, [1.0, 1.0, 1.0])
assert len(_score_func_args) == 3
def test_cross_val_score_errors():
class BrokenEstimator:
pass
assert_raises(TypeError, cross_val_score, BrokenEstimator(), X)
def test_cross_val_score_with_score_func_classification():
iris = load_iris()
clf = SVC(kernel='linear')
# Default score (should be the accuracy score)
scores = cross_val_score(clf, iris.data, iris.target, cv=5)
assert_array_almost_equal(scores, [0.97, 1., 0.97, 0.97, 1.], 2)
# Correct classification score (aka. zero / one score) - should be the
# same as the default estimator score
zo_scores = cross_val_score(clf, iris.data, iris.target,
scoring="accuracy", cv=5)
assert_array_almost_equal(zo_scores, [0.97, 1., 0.97, 0.97, 1.], 2)
# F1 score (class are balanced so f1_score should be equal to zero/one
# score
f1_scores = cross_val_score(clf, iris.data, iris.target,
scoring="f1_weighted", cv=5)
assert_array_almost_equal(f1_scores, [0.97, 1., 0.97, 0.97, 1.], 2)
def test_cross_val_score_with_score_func_regression():
X, y = make_regression(n_samples=30, n_features=20, n_informative=5,
random_state=0)
reg = Ridge()
# Default score of the Ridge regression estimator
scores = cross_val_score(reg, X, y, cv=5)
assert_array_almost_equal(scores, [0.94, 0.97, 0.97, 0.99, 0.92], 2)
# R2 score (aka. determination coefficient) - should be the
# same as the default estimator score
r2_scores = cross_val_score(reg, X, y, scoring="r2", cv=5)
assert_array_almost_equal(r2_scores, [0.94, 0.97, 0.97, 0.99, 0.92], 2)
# Mean squared error; this is a loss function, so "scores" are negative
mse_scores = cross_val_score(reg, X, y, cv=5, scoring="mean_squared_error")
expected_mse = np.array([-763.07, -553.16, -274.38, -273.26, -1681.99])
assert_array_almost_equal(mse_scores, expected_mse, 2)
# Explained variance
scoring = make_scorer(explained_variance_score)
ev_scores = cross_val_score(reg, X, y, cv=5, scoring=scoring)
assert_array_almost_equal(ev_scores, [0.94, 0.97, 0.97, 0.99, 0.92], 2)
def test_permutation_score():
iris = load_iris()
X = iris.data
X_sparse = coo_matrix(X)
y = iris.target
svm = SVC(kernel='linear')
cv = StratifiedKFold(2)
score, scores, pvalue = permutation_test_score(
svm, X, y, n_permutations=30, cv=cv, scoring="accuracy")
assert_greater(score, 0.9)
assert_almost_equal(pvalue, 0.0, 1)
score_label, _, pvalue_label = permutation_test_score(
svm, X, y, n_permutations=30, cv=cv, scoring="accuracy",
labels=np.ones(y.size), random_state=0)
assert_true(score_label == score)
assert_true(pvalue_label == pvalue)
# check that we obtain the same results with a sparse representation
svm_sparse = SVC(kernel='linear')
cv_sparse = StratifiedKFold(2)
score_label, _, pvalue_label = permutation_test_score(
svm_sparse, X_sparse, y, n_permutations=30, cv=cv_sparse,
scoring="accuracy", labels=np.ones(y.size), random_state=0)
assert_true(score_label == score)
assert_true(pvalue_label == pvalue)
# test with custom scoring object
def custom_score(y_true, y_pred):
return (((y_true == y_pred).sum() - (y_true != y_pred).sum())
/ y_true.shape[0])
scorer = make_scorer(custom_score)
score, _, pvalue = permutation_test_score(
svm, X, y, n_permutations=100, scoring=scorer, cv=cv, random_state=0)
assert_almost_equal(score, .93, 2)
assert_almost_equal(pvalue, 0.01, 3)
# set random y
y = np.mod(np.arange(len(y)), 3)
score, scores, pvalue = permutation_test_score(
svm, X, y, n_permutations=30, cv=cv, scoring="accuracy")
assert_less(score, 0.5)
assert_greater(pvalue, 0.2)
def test_permutation_test_score_allow_nans():
# Check that permutation_test_score allows input data with NaNs
X = np.arange(200, dtype=np.float64).reshape(10, -1)
X[2, :] = np.nan
y = np.repeat([0, 1], X.shape[0] / 2)
p = Pipeline([
('imputer', Imputer(strategy='mean', missing_values='NaN')),
('classifier', MockClassifier()),
])
permutation_test_score(p, X, y, cv=5)
def test_cross_val_score_allow_nans():
# Check that cross_val_score allows input data with NaNs
X = np.arange(200, dtype=np.float64).reshape(10, -1)
X[2, :] = np.nan
y = np.repeat([0, 1], X.shape[0] / 2)
p = Pipeline([
('imputer', Imputer(strategy='mean', missing_values='NaN')),
('classifier', MockClassifier()),
])
cross_val_score(p, X, y, cv=5)
def test_cross_val_score_multilabel():
X = np.array([[-3, 4], [2, 4], [3, 3], [0, 2], [-3, 1],
[-2, 1], [0, 0], [-2, -1], [-1, -2], [1, -2]])
y = np.array([[1, 1], [0, 1], [0, 1], [0, 1], [1, 1],
[0, 1], [1, 0], [1, 1], [1, 0], [0, 0]])
clf = KNeighborsClassifier(n_neighbors=1)
scoring_micro = make_scorer(precision_score, average='micro')
scoring_macro = make_scorer(precision_score, average='macro')
scoring_samples = make_scorer(precision_score, average='samples')
score_micro = cross_val_score(clf, X, y, scoring=scoring_micro, cv=5)
score_macro = cross_val_score(clf, X, y, scoring=scoring_macro, cv=5)
score_samples = cross_val_score(clf, X, y, scoring=scoring_samples, cv=5)
assert_almost_equal(score_micro, [1, 1 / 2, 3 / 4, 1 / 2, 1 / 3])
assert_almost_equal(score_macro, [1, 1 / 2, 3 / 4, 1 / 2, 1 / 4])
assert_almost_equal(score_samples, [1, 1 / 2, 3 / 4, 1 / 2, 1 / 4])
def test_cross_val_predict():
boston = load_boston()
X, y = boston.data, boston.target
cv = KFold()
est = Ridge()
# Naive loop (should be same as cross_val_predict):
preds2 = np.zeros_like(y)
for train, test in cv.split(X, y):
est.fit(X[train], y[train])
preds2[test] = est.predict(X[test])
preds = cross_val_predict(est, X, y, cv=cv)
assert_array_almost_equal(preds, preds2)
preds = cross_val_predict(est, X, y)
assert_equal(len(preds), len(y))
cv = LeaveOneOut()
preds = cross_val_predict(est, X, y, cv=cv)
assert_equal(len(preds), len(y))
Xsp = X.copy()
Xsp *= (Xsp > np.median(Xsp))
Xsp = coo_matrix(Xsp)
preds = cross_val_predict(est, Xsp, y)
assert_array_almost_equal(len(preds), len(y))
preds = cross_val_predict(KMeans(), X)
assert_equal(len(preds), len(y))
class BadCV():
def split(self, X, y=None, labels=None):
for i in range(4):
yield np.array([0, 1, 2, 3]), np.array([4, 5, 6, 7, 8])
assert_raises(ValueError, cross_val_predict, est, X, y, cv=BadCV())
def test_cross_val_predict_input_types():
iris = load_iris()
X, y = iris.data, iris.target
X_sparse = coo_matrix(X)
multioutput_y = np.column_stack([y, y[::-1]])
clf = Ridge(fit_intercept=False, random_state=0)
# 3 fold cv is used --> atleast 3 samples per class
# Smoke test
predictions = cross_val_predict(clf, X, y)
assert_equal(predictions.shape, (150,))
# test with multioutput y
predictions = cross_val_predict(clf, X_sparse, multioutput_y)
assert_equal(predictions.shape, (150, 2))
predictions = cross_val_predict(clf, X_sparse, y)
assert_array_equal(predictions.shape, (150,))
# test with multioutput y
predictions = cross_val_predict(clf, X_sparse, multioutput_y)
assert_array_equal(predictions.shape, (150, 2))
# test with X and y as list
list_check = lambda x: isinstance(x, list)
clf = CheckingClassifier(check_X=list_check)
predictions = cross_val_predict(clf, X.tolist(), y.tolist())
clf = CheckingClassifier(check_y=list_check)
predictions = cross_val_predict(clf, X, y.tolist())
# test with 3d X and
X_3d = X[:, :, np.newaxis]
check_3d = lambda x: x.ndim == 3
clf = CheckingClassifier(check_X=check_3d)
predictions = cross_val_predict(clf, X_3d, y)
assert_array_equal(predictions.shape, (150,))
def test_cross_val_predict_pandas():
# check cross_val_score doesn't destroy pandas dataframe
types = [(MockDataFrame, MockDataFrame)]
try:
from pandas import Series, DataFrame
types.append((Series, DataFrame))
except ImportError:
pass
for TargetType, InputFeatureType in types:
# X dataframe, y series
X_df, y_ser = InputFeatureType(X), TargetType(y2)
check_df = lambda x: isinstance(x, InputFeatureType)
check_series = lambda x: isinstance(x, TargetType)
clf = CheckingClassifier(check_X=check_df, check_y=check_series)
cross_val_predict(clf, X_df, y_ser)
def test_cross_val_score_sparse_fit_params():
iris = load_iris()
X, y = iris.data, iris.target
clf = MockClassifier()
fit_params = {'sparse_sample_weight': coo_matrix(np.eye(X.shape[0]))}
a = cross_val_score(clf, X, y, fit_params=fit_params)
assert_array_equal(a, np.ones(3))
def test_learning_curve():
X, y = make_classification(n_samples=30, n_features=1, n_informative=1,
n_redundant=0, n_classes=2,
n_clusters_per_class=1, random_state=0)
estimator = MockImprovingEstimator(20)
with warnings.catch_warnings(record=True) as w:
train_sizes, train_scores, test_scores = learning_curve(
estimator, X, y, cv=3, train_sizes=np.linspace(0.1, 1.0, 10))
if len(w) > 0:
raise RuntimeError("Unexpected warning: %r" % w[0].message)
assert_equal(train_scores.shape, (10, 3))
assert_equal(test_scores.shape, (10, 3))
assert_array_equal(train_sizes, np.linspace(2, 20, 10))
assert_array_almost_equal(train_scores.mean(axis=1),
np.linspace(1.9, 1.0, 10))
assert_array_almost_equal(test_scores.mean(axis=1),
np.linspace(0.1, 1.0, 10))
def test_learning_curve_unsupervised():
X, _ = make_classification(n_samples=30, n_features=1, n_informative=1,
n_redundant=0, n_classes=2,
n_clusters_per_class=1, random_state=0)
estimator = MockImprovingEstimator(20)
train_sizes, train_scores, test_scores = learning_curve(
estimator, X, y=None, cv=3, train_sizes=np.linspace(0.1, 1.0, 10))
assert_array_equal(train_sizes, np.linspace(2, 20, 10))
assert_array_almost_equal(train_scores.mean(axis=1),
np.linspace(1.9, 1.0, 10))
assert_array_almost_equal(test_scores.mean(axis=1),
np.linspace(0.1, 1.0, 10))
def test_learning_curve_verbose():
X, y = make_classification(n_samples=30, n_features=1, n_informative=1,
n_redundant=0, n_classes=2,
n_clusters_per_class=1, random_state=0)
estimator = MockImprovingEstimator(20)
old_stdout = sys.stdout
sys.stdout = StringIO()
try:
train_sizes, train_scores, test_scores = \
learning_curve(estimator, X, y, cv=3, verbose=1)
finally:
out = sys.stdout.getvalue()
sys.stdout.close()
sys.stdout = old_stdout
assert("[learning_curve]" in out)
def test_learning_curve_incremental_learning_not_possible():
X, y = make_classification(n_samples=2, n_features=1, n_informative=1,
n_redundant=0, n_classes=2,
n_clusters_per_class=1, random_state=0)
# The mockup does not have partial_fit()
estimator = MockImprovingEstimator(1)
assert_raises(ValueError, learning_curve, estimator, X, y,
exploit_incremental_learning=True)
def test_learning_curve_incremental_learning():
X, y = make_classification(n_samples=30, n_features=1, n_informative=1,
n_redundant=0, n_classes=2,
n_clusters_per_class=1, random_state=0)
estimator = MockIncrementalImprovingEstimator(20)
train_sizes, train_scores, test_scores = learning_curve(
estimator, X, y, cv=3, exploit_incremental_learning=True,
train_sizes=np.linspace(0.1, 1.0, 10))
assert_array_equal(train_sizes, np.linspace(2, 20, 10))
assert_array_almost_equal(train_scores.mean(axis=1),
np.linspace(1.9, 1.0, 10))
assert_array_almost_equal(test_scores.mean(axis=1),
np.linspace(0.1, 1.0, 10))
def test_learning_curve_incremental_learning_unsupervised():
X, _ = make_classification(n_samples=30, n_features=1, n_informative=1,
n_redundant=0, n_classes=2,
n_clusters_per_class=1, random_state=0)
estimator = MockIncrementalImprovingEstimator(20)
train_sizes, train_scores, test_scores = learning_curve(
estimator, X, y=None, cv=3, exploit_incremental_learning=True,
train_sizes=np.linspace(0.1, 1.0, 10))
assert_array_equal(train_sizes, np.linspace(2, 20, 10))
assert_array_almost_equal(train_scores.mean(axis=1),
np.linspace(1.9, 1.0, 10))
assert_array_almost_equal(test_scores.mean(axis=1),
np.linspace(0.1, 1.0, 10))
def test_learning_curve_batch_and_incremental_learning_are_equal():
X, y = make_classification(n_samples=30, n_features=1, n_informative=1,
n_redundant=0, n_classes=2,
n_clusters_per_class=1, random_state=0)
train_sizes = np.linspace(0.2, 1.0, 5)
estimator = PassiveAggressiveClassifier(n_iter=1, shuffle=False)
train_sizes_inc, train_scores_inc, test_scores_inc = \
learning_curve(
estimator, X, y, train_sizes=train_sizes,
cv=3, exploit_incremental_learning=True)
train_sizes_batch, train_scores_batch, test_scores_batch = \
learning_curve(
estimator, X, y, cv=3, train_sizes=train_sizes,
exploit_incremental_learning=False)
assert_array_equal(train_sizes_inc, train_sizes_batch)
assert_array_almost_equal(train_scores_inc.mean(axis=1),
train_scores_batch.mean(axis=1))
assert_array_almost_equal(test_scores_inc.mean(axis=1),
test_scores_batch.mean(axis=1))
def test_learning_curve_n_sample_range_out_of_bounds():
X, y = make_classification(n_samples=30, n_features=1, n_informative=1,
n_redundant=0, n_classes=2,
n_clusters_per_class=1, random_state=0)
estimator = MockImprovingEstimator(20)
assert_raises(ValueError, learning_curve, estimator, X, y, cv=3,
train_sizes=[0, 1])
assert_raises(ValueError, learning_curve, estimator, X, y, cv=3,
train_sizes=[0.0, 1.0])
assert_raises(ValueError, learning_curve, estimator, X, y, cv=3,
train_sizes=[0.1, 1.1])
assert_raises(ValueError, learning_curve, estimator, X, y, cv=3,
train_sizes=[0, 20])
assert_raises(ValueError, learning_curve, estimator, X, y, cv=3,
train_sizes=[1, 21])
def test_learning_curve_remove_duplicate_sample_sizes():
X, y = make_classification(n_samples=3, n_features=1, n_informative=1,
n_redundant=0, n_classes=2,
n_clusters_per_class=1, random_state=0)
estimator = MockImprovingEstimator(2)
train_sizes, _, _ = assert_warns(
RuntimeWarning, learning_curve, estimator, X, y, cv=3,
train_sizes=np.linspace(0.33, 1.0, 3))
assert_array_equal(train_sizes, [1, 2])
def test_learning_curve_with_boolean_indices():
X, y = make_classification(n_samples=30, n_features=1, n_informative=1,
n_redundant=0, n_classes=2,
n_clusters_per_class=1, random_state=0)
estimator = MockImprovingEstimator(20)
cv = KFold(n_folds=3)
train_sizes, train_scores, test_scores = learning_curve(
estimator, X, y, cv=cv, train_sizes=np.linspace(0.1, 1.0, 10))
assert_array_equal(train_sizes, np.linspace(2, 20, 10))
assert_array_almost_equal(train_scores.mean(axis=1),
np.linspace(1.9, 1.0, 10))
assert_array_almost_equal(test_scores.mean(axis=1),
np.linspace(0.1, 1.0, 10))
def test_validation_curve():
X, y = make_classification(n_samples=2, n_features=1, n_informative=1,
n_redundant=0, n_classes=2,
n_clusters_per_class=1, random_state=0)
param_range = np.linspace(0, 1, 10)
with warnings.catch_warnings(record=True) as w:
train_scores, test_scores = validation_curve(
MockEstimatorWithParameter(), X, y, param_name="param",
param_range=param_range, cv=2
)
if len(w) > 0:
raise RuntimeError("Unexpected warning: %r" % w[0].message)
assert_array_almost_equal(train_scores.mean(axis=1), param_range)
assert_array_almost_equal(test_scores.mean(axis=1), 1 - param_range)
def test_check_is_permutation():
p = np.arange(100)
assert_true(_check_is_permutation(p, 100))
assert_false(_check_is_permutation(np.delete(p, 23), 100))
p[0] = 23
assert_false(_check_is_permutation(p, 100))
def test_cross_val_predict_sparse_prediction():
# check that cross_val_predict gives same result for sparse and dense input
X, y = make_multilabel_classification(n_classes=2, n_labels=1,
allow_unlabeled=False,
return_indicator=True,
random_state=1)
X_sparse = csr_matrix(X)
y_sparse = csr_matrix(y)
classif = OneVsRestClassifier(SVC(kernel='linear'))
preds = cross_val_predict(classif, X, y, cv=10)
preds_sparse = cross_val_predict(classif, X_sparse, y_sparse, cv=10)
preds_sparse = preds_sparse.toarray()
assert_array_almost_equal(preds_sparse, preds)
|
mit
|
rs2/pandas
|
scripts/validate_docstrings.py
|
2
|
14040
|
#!/usr/bin/env python3
"""
Analyze docstrings to detect errors.
If no argument is provided, it does a quick check of docstrings and returns
a csv with all API functions and results of basic checks.
If a function or method is provided in the form "pandas.function",
"pandas.module.class.method", etc. a list of all errors in the docstring for
the specified function or method.
Usage::
$ ./validate_docstrings.py
$ ./validate_docstrings.py pandas.DataFrame.head
"""
import argparse
import doctest
import glob
import importlib
import json
import os
import sys
import tempfile
from typing import List, Optional
import flake8.main.application
try:
from io import StringIO
except ImportError:
from cStringIO import StringIO
# Template backend makes matplotlib to not plot anything. This is useful
# to avoid that plot windows are open from the doctests while running the
# script. Setting here before matplotlib is loaded.
# We don't warn for the number of open plots, as none is actually being opened
os.environ["MPLBACKEND"] = "Template"
import matplotlib # noqa: E402 isort:skip
matplotlib.rc("figure", max_open_warning=10000)
import numpy # noqa: E402 isort:skip
BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(BASE_PATH))
import pandas # noqa: E402 isort:skip
sys.path.insert(1, os.path.join(BASE_PATH, "doc", "sphinxext"))
from numpydoc.validate import validate, Docstring # noqa: E402 isort:skip
PRIVATE_CLASSES = ["NDFrame", "IndexOpsMixin"]
ERROR_MSGS = {
"GL04": "Private classes ({mentioned_private_classes}) should not be "
"mentioned in public docstrings",
"SA05": "{reference_name} in `See Also` section does not need `pandas` "
"prefix, use {right_reference} instead.",
"EX02": "Examples do not pass tests:\n{doctest_log}",
"EX03": "flake8 error: {error_code} {error_message}{times_happening}",
"EX04": "Do not import {imported_library}, as it is imported "
"automatically for the examples (numpy as np, pandas as pd)",
}
def pandas_error(code, **kwargs):
"""
Copy of the numpydoc error function, since ERROR_MSGS can't be updated
with our custom errors yet.
"""
return (code, ERROR_MSGS[code].format(**kwargs))
def get_api_items(api_doc_fd):
"""
Yield information about all public API items.
Parse api.rst file from the documentation, and extract all the functions,
methods, classes, attributes... This should include all pandas public API.
Parameters
----------
api_doc_fd : file descriptor
A file descriptor of the API documentation page, containing the table
of contents with all the public API.
Yields
------
name : str
The name of the object (e.g. 'pandas.Series.str.upper).
func : function
The object itself. In most cases this will be a function or method,
but it can also be classes, properties, cython objects...
section : str
The name of the section in the API page where the object item is
located.
subsection : str
The name of the subsection in the API page where the object item is
located.
"""
current_module = "pandas"
previous_line = current_section = current_subsection = ""
position = None
for line in api_doc_fd:
line = line.strip()
if len(line) == len(previous_line):
if set(line) == set("-"):
current_section = previous_line
continue
if set(line) == set("~"):
current_subsection = previous_line
continue
if line.startswith(".. currentmodule::"):
current_module = line.replace(".. currentmodule::", "").strip()
continue
if line == ".. autosummary::":
position = "autosummary"
continue
if position == "autosummary":
if line == "":
position = "items"
continue
if position == "items":
if line == "":
position = None
continue
item = line.strip()
func = importlib.import_module(current_module)
for part in item.split("."):
func = getattr(func, part)
yield (
".".join([current_module, item]),
func,
current_section,
current_subsection,
)
previous_line = line
class PandasDocstring(Docstring):
@property
def mentioned_private_classes(self):
return [klass for klass in PRIVATE_CLASSES if klass in self.raw_doc]
@property
def examples_errors(self):
flags = doctest.NORMALIZE_WHITESPACE | doctest.IGNORE_EXCEPTION_DETAIL
finder = doctest.DocTestFinder()
runner = doctest.DocTestRunner(optionflags=flags)
context = {"np": numpy, "pd": pandas}
error_msgs = ""
for test in finder.find(self.raw_doc, self.name, globs=context):
f = StringIO()
runner.run(test, out=f.write)
error_msgs += f.getvalue()
return error_msgs
@property
def examples_source_code(self):
lines = doctest.DocTestParser().get_examples(self.raw_doc)
return [line.source for line in lines]
def validate_pep8(self):
if not self.examples:
return
# F401 is needed to not generate flake8 errors in examples
# that do not user numpy or pandas
content = "".join(
(
"import numpy as np # noqa: F401\n",
"import pandas as pd # noqa: F401\n",
*self.examples_source_code,
)
)
application = flake8.main.application.Application()
application.initialize(["--quiet"])
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8") as file:
file.write(content)
file.flush()
application.run_checks([file.name])
# We need this to avoid flake8 printing the names of the files to
# the standard output
application.formatter.write = lambda line, source: None
application.report()
yield from application.guide.stats.statistics_for("")
def pandas_validate(func_name: str):
"""
Call the numpydoc validation, and add the errors specific to pandas.
Parameters
----------
func_name : str
Name of the object of the docstring to validate.
Returns
-------
dict
Information about the docstring and the errors found.
"""
doc = PandasDocstring(func_name)
result = validate(func_name)
mentioned_errs = doc.mentioned_private_classes
if mentioned_errs:
result["errors"].append(
pandas_error("GL04", mentioned_private_classes=", ".join(mentioned_errs))
)
if doc.see_also:
for rel_name, rel_desc in doc.see_also.items():
if rel_name.startswith("pandas."):
result["errors"].append(
pandas_error(
"SA05",
reference_name=rel_name,
right_reference=rel_name[len("pandas.") :],
)
)
result["examples_errs"] = ""
if doc.examples:
result["examples_errs"] = doc.examples_errors
if result["examples_errs"]:
result["errors"].append(
pandas_error("EX02", doctest_log=result["examples_errs"])
)
for err in doc.validate_pep8():
result["errors"].append(
pandas_error(
"EX03",
error_code=err.error_code,
error_message=err.message,
times_happening=f" ({err.count} times)" if err.count > 1 else "",
)
)
examples_source_code = "".join(doc.examples_source_code)
for wrong_import in ("numpy", "pandas"):
if f"import {wrong_import}" in examples_source_code:
result["errors"].append(
pandas_error("EX04", imported_library=wrong_import)
)
return result
def validate_all(prefix, ignore_deprecated=False):
"""
Execute the validation of all docstrings, and return a dict with the
results.
Parameters
----------
prefix : str or None
If provided, only the docstrings that start with this pattern will be
validated. If None, all docstrings will be validated.
ignore_deprecated: bool, default False
If True, deprecated objects are ignored when validating docstrings.
Returns
-------
dict
A dictionary with an item for every function/method... containing
all the validation information.
"""
result = {}
seen = {}
api_doc_fnames = os.path.join(BASE_PATH, "doc", "source", "reference", "*.rst")
api_items = []
for api_doc_fname in glob.glob(api_doc_fnames):
with open(api_doc_fname) as f:
api_items += list(get_api_items(f))
for func_name, func_obj, section, subsection in api_items:
if prefix and not func_name.startswith(prefix):
continue
doc_info = pandas_validate(func_name)
if ignore_deprecated and doc_info["deprecated"]:
continue
result[func_name] = doc_info
shared_code_key = doc_info["file"], doc_info["file_line"]
shared_code = seen.get(shared_code_key, "")
result[func_name].update(
{
"in_api": True,
"section": section,
"subsection": subsection,
"shared_code_with": shared_code,
}
)
seen[shared_code_key] = func_name
return result
def print_validate_all_results(
prefix: str,
errors: Optional[List[str]],
output_format: str,
ignore_deprecated: bool,
):
if output_format not in ("default", "json", "actions"):
raise ValueError(f'Unknown output_format "{output_format}"')
result = validate_all(prefix, ignore_deprecated)
if output_format == "json":
sys.stdout.write(json.dumps(result))
return 0
prefix = "##[error]" if output_format == "actions" else ""
exit_status = 0
for name, res in result.items():
for err_code, err_desc in res["errors"]:
if errors and err_code not in errors:
continue
sys.stdout.write(
f'{prefix}{res["file"]}:{res["file_line"]}:'
f"{err_code}:{name}:{err_desc}\n"
)
exit_status += 1
return exit_status
def print_validate_one_results(func_name: str):
def header(title, width=80, char="#"):
full_line = char * width
side_len = (width - len(title) - 2) // 2
adj = "" if len(title) % 2 == 0 else " "
title_line = f"{char * side_len} {title}{adj} {char * side_len}"
return f"\n{full_line}\n{title_line}\n{full_line}\n\n"
result = pandas_validate(func_name)
sys.stderr.write(header(f"Docstring ({func_name})"))
sys.stderr.write(f"{result['docstring']}\n")
sys.stderr.write(header("Validation"))
if result["errors"]:
sys.stderr.write(f'{len(result["errors"])} Errors found:\n')
for err_code, err_desc in result["errors"]:
if err_code == "EX02": # Failing examples are printed at the end
sys.stderr.write("\tExamples do not pass tests\n")
continue
sys.stderr.write(f"\t{err_desc}\n")
else:
sys.stderr.write(f'Docstring for "{func_name}" correct. :)\n')
if result["examples_errs"]:
sys.stderr.write(header("Doctests"))
sys.stderr.write(result["examples_errs"])
def main(func_name, prefix, errors, output_format, ignore_deprecated):
"""
Main entry point. Call the validation for one or for all docstrings.
"""
if func_name is None:
return print_validate_all_results(
prefix, errors, output_format, ignore_deprecated
)
else:
print_validate_one_results(func_name)
return 0
if __name__ == "__main__":
format_opts = "default", "json", "actions"
func_help = (
"function or method to validate (e.g. pandas.DataFrame.head) "
"if not provided, all docstrings are validated and returned "
"as JSON"
)
argparser = argparse.ArgumentParser(description="validate pandas docstrings")
argparser.add_argument("function", nargs="?", default=None, help=func_help)
argparser.add_argument(
"--format",
default="default",
choices=format_opts,
help="format of the output when validating "
"multiple docstrings (ignored when validating one). "
"It can be {str(format_opts)[1:-1]}",
)
argparser.add_argument(
"--prefix",
default=None,
help="pattern for the "
"docstring names, in order to decide which ones "
'will be validated. A prefix "pandas.Series.str."'
"will make the script validate all the docstrings "
"of methods starting by this pattern. It is "
"ignored if parameter function is provided",
)
argparser.add_argument(
"--errors",
default=None,
help="comma separated "
"list of error codes to validate. By default it "
"validates all errors (ignored when validating "
"a single docstring)",
)
argparser.add_argument(
"--ignore_deprecated",
default=False,
action="store_true",
help="if this flag is set, "
"deprecated objects are ignored when validating "
"all docstrings",
)
args = argparser.parse_args()
sys.exit(
main(
args.function,
args.prefix,
args.errors.split(",") if args.errors else None,
args.format,
args.ignore_deprecated,
)
)
|
bsd-3-clause
|
mikebenfield/scikit-learn
|
examples/linear_model/plot_lasso_lars.py
|
363
|
1080
|
#!/usr/bin/env python
"""
=====================
Lasso path using LARS
=====================
Computes Lasso Path along the regularization parameter using the LARS
algorithm on the diabetes dataset. Each color represents a different
feature of the coefficient vector, and this is displayed as a function
of the regularization parameter.
"""
print(__doc__)
# Author: Fabian Pedregosa <[email protected]>
# Alexandre Gramfort <[email protected]>
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model
from sklearn import datasets
diabetes = datasets.load_diabetes()
X = diabetes.data
y = diabetes.target
print("Computing regularization path using the LARS ...")
alphas, _, coefs = linear_model.lars_path(X, y, method='lasso', verbose=True)
xx = np.sum(np.abs(coefs.T), axis=1)
xx /= xx[-1]
plt.plot(xx, coefs.T)
ymin, ymax = plt.ylim()
plt.vlines(xx, ymin, ymax, linestyle='dashed')
plt.xlabel('|coef| / max|coef|')
plt.ylabel('Coefficients')
plt.title('LASSO Path')
plt.axis('tight')
plt.show()
|
bsd-3-clause
|
idlead/scikit-learn
|
sklearn/tests/test_grid_search.py
|
68
|
28856
|
"""
Testing for grid search module (sklearn.grid_search)
"""
from collections import Iterable, Sized
from sklearn.externals.six.moves import cStringIO as StringIO
from sklearn.externals.six.moves import xrange
from itertools import chain, product
import pickle
import warnings
import sys
import numpy as np
import scipy.sparse as sp
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_not_equal
from sklearn.utils.testing import assert_raises
from sklearn.utils.testing import assert_warns
from sklearn.utils.testing import assert_raise_message
from sklearn.utils.testing import assert_false, assert_true
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_almost_equal
from sklearn.utils.testing import assert_array_almost_equal
from sklearn.utils.testing import assert_no_warnings
from sklearn.utils.testing import ignore_warnings
from sklearn.utils.mocking import CheckingClassifier, MockDataFrame
from scipy.stats import bernoulli, expon, uniform
from sklearn.externals.six.moves import zip
from sklearn.base import BaseEstimator
from sklearn.datasets import make_classification
from sklearn.datasets import make_blobs
from sklearn.datasets import make_multilabel_classification
from sklearn.svm import LinearSVC, SVC
from sklearn.tree import DecisionTreeRegressor
from sklearn.tree import DecisionTreeClassifier
from sklearn.cluster import KMeans
from sklearn.neighbors import KernelDensity
from sklearn.metrics import f1_score
from sklearn.metrics import make_scorer
from sklearn.metrics import roc_auc_score
from sklearn.exceptions import ChangedBehaviorWarning
from sklearn.exceptions import FitFailedWarning
with warnings.catch_warnings():
warnings.simplefilter('ignore')
from sklearn.grid_search import (GridSearchCV, RandomizedSearchCV,
ParameterGrid, ParameterSampler)
from sklearn.cross_validation import KFold, StratifiedKFold
from sklearn.preprocessing import Imputer
from sklearn.pipeline import Pipeline
# Neither of the following two estimators inherit from BaseEstimator,
# to test hyperparameter search on user-defined classifiers.
class MockClassifier(object):
"""Dummy classifier to test the cross-validation"""
def __init__(self, foo_param=0):
self.foo_param = foo_param
def fit(self, X, Y):
assert_true(len(X) == len(Y))
return self
def predict(self, T):
return T.shape[0]
predict_proba = predict
decision_function = predict
transform = predict
def score(self, X=None, Y=None):
if self.foo_param > 1:
score = 1.
else:
score = 0.
return score
def get_params(self, deep=False):
return {'foo_param': self.foo_param}
def set_params(self, **params):
self.foo_param = params['foo_param']
return self
class LinearSVCNoScore(LinearSVC):
"""An LinearSVC classifier that has no score method."""
@property
def score(self):
raise AttributeError
X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])
y = np.array([1, 1, 2, 2])
def assert_grid_iter_equals_getitem(grid):
assert_equal(list(grid), [grid[i] for i in range(len(grid))])
def test_parameter_grid():
# Test basic properties of ParameterGrid.
params1 = {"foo": [1, 2, 3]}
grid1 = ParameterGrid(params1)
assert_true(isinstance(grid1, Iterable))
assert_true(isinstance(grid1, Sized))
assert_equal(len(grid1), 3)
assert_grid_iter_equals_getitem(grid1)
params2 = {"foo": [4, 2],
"bar": ["ham", "spam", "eggs"]}
grid2 = ParameterGrid(params2)
assert_equal(len(grid2), 6)
# loop to assert we can iterate over the grid multiple times
for i in xrange(2):
# tuple + chain transforms {"a": 1, "b": 2} to ("a", 1, "b", 2)
points = set(tuple(chain(*(sorted(p.items())))) for p in grid2)
assert_equal(points,
set(("bar", x, "foo", y)
for x, y in product(params2["bar"], params2["foo"])))
assert_grid_iter_equals_getitem(grid2)
# Special case: empty grid (useful to get default estimator settings)
empty = ParameterGrid({})
assert_equal(len(empty), 1)
assert_equal(list(empty), [{}])
assert_grid_iter_equals_getitem(empty)
assert_raises(IndexError, lambda: empty[1])
has_empty = ParameterGrid([{'C': [1, 10]}, {}, {'C': [.5]}])
assert_equal(len(has_empty), 4)
assert_equal(list(has_empty), [{'C': 1}, {'C': 10}, {}, {'C': .5}])
assert_grid_iter_equals_getitem(has_empty)
def test_grid_search():
# Test that the best estimator contains the right value for foo_param
clf = MockClassifier()
grid_search = GridSearchCV(clf, {'foo_param': [1, 2, 3]}, verbose=3)
# make sure it selects the smallest parameter in case of ties
old_stdout = sys.stdout
sys.stdout = StringIO()
grid_search.fit(X, y)
sys.stdout = old_stdout
assert_equal(grid_search.best_estimator_.foo_param, 2)
for i, foo_i in enumerate([1, 2, 3]):
assert_true(grid_search.grid_scores_[i][0]
== {'foo_param': foo_i})
# Smoke test the score etc:
grid_search.score(X, y)
grid_search.predict_proba(X)
grid_search.decision_function(X)
grid_search.transform(X)
# Test exception handling on scoring
grid_search.scoring = 'sklearn'
assert_raises(ValueError, grid_search.fit, X, y)
@ignore_warnings
def test_grid_search_no_score():
# Test grid-search on classifier that has no score function.
clf = LinearSVC(random_state=0)
X, y = make_blobs(random_state=0, centers=2)
Cs = [.1, 1, 10]
clf_no_score = LinearSVCNoScore(random_state=0)
grid_search = GridSearchCV(clf, {'C': Cs}, scoring='accuracy')
grid_search.fit(X, y)
grid_search_no_score = GridSearchCV(clf_no_score, {'C': Cs},
scoring='accuracy')
# smoketest grid search
grid_search_no_score.fit(X, y)
# check that best params are equal
assert_equal(grid_search_no_score.best_params_, grid_search.best_params_)
# check that we can call score and that it gives the correct result
assert_equal(grid_search.score(X, y), grid_search_no_score.score(X, y))
# giving no scoring function raises an error
grid_search_no_score = GridSearchCV(clf_no_score, {'C': Cs})
assert_raise_message(TypeError, "no scoring", grid_search_no_score.fit,
[[1]])
def test_grid_search_score_method():
X, y = make_classification(n_samples=100, n_classes=2, flip_y=.2,
random_state=0)
clf = LinearSVC(random_state=0)
grid = {'C': [.1]}
search_no_scoring = GridSearchCV(clf, grid, scoring=None).fit(X, y)
search_accuracy = GridSearchCV(clf, grid, scoring='accuracy').fit(X, y)
search_no_score_method_auc = GridSearchCV(LinearSVCNoScore(), grid,
scoring='roc_auc').fit(X, y)
search_auc = GridSearchCV(clf, grid, scoring='roc_auc').fit(X, y)
# Check warning only occurs in situation where behavior changed:
# estimator requires score method to compete with scoring parameter
score_no_scoring = assert_no_warnings(search_no_scoring.score, X, y)
score_accuracy = assert_warns(ChangedBehaviorWarning,
search_accuracy.score, X, y)
score_no_score_auc = assert_no_warnings(search_no_score_method_auc.score,
X, y)
score_auc = assert_warns(ChangedBehaviorWarning,
search_auc.score, X, y)
# ensure the test is sane
assert_true(score_auc < 1.0)
assert_true(score_accuracy < 1.0)
assert_not_equal(score_auc, score_accuracy)
assert_almost_equal(score_accuracy, score_no_scoring)
assert_almost_equal(score_auc, score_no_score_auc)
def test_trivial_grid_scores():
# Test search over a "grid" with only one point.
# Non-regression test: grid_scores_ wouldn't be set by GridSearchCV.
clf = MockClassifier()
grid_search = GridSearchCV(clf, {'foo_param': [1]})
grid_search.fit(X, y)
assert_true(hasattr(grid_search, "grid_scores_"))
random_search = RandomizedSearchCV(clf, {'foo_param': [0]}, n_iter=1)
random_search.fit(X, y)
assert_true(hasattr(random_search, "grid_scores_"))
def test_no_refit():
# Test that grid search can be used for model selection only
clf = MockClassifier()
grid_search = GridSearchCV(clf, {'foo_param': [1, 2, 3]}, refit=False)
grid_search.fit(X, y)
assert_true(hasattr(grid_search, "best_params_"))
def test_grid_search_error():
# Test that grid search will capture errors on data with different
# length
X_, y_ = make_classification(n_samples=200, n_features=100, random_state=0)
clf = LinearSVC()
cv = GridSearchCV(clf, {'C': [0.1, 1.0]})
assert_raises(ValueError, cv.fit, X_[:180], y_)
def test_grid_search_iid():
# test the iid parameter
# noise-free simple 2d-data
X, y = make_blobs(centers=[[0, 0], [1, 0], [0, 1], [1, 1]], random_state=0,
cluster_std=0.1, shuffle=False, n_samples=80)
# split dataset into two folds that are not iid
# first one contains data of all 4 blobs, second only from two.
mask = np.ones(X.shape[0], dtype=np.bool)
mask[np.where(y == 1)[0][::2]] = 0
mask[np.where(y == 2)[0][::2]] = 0
# this leads to perfect classification on one fold and a score of 1/3 on
# the other
svm = SVC(kernel='linear')
# create "cv" for splits
cv = [[mask, ~mask], [~mask, mask]]
# once with iid=True (default)
grid_search = GridSearchCV(svm, param_grid={'C': [1, 10]}, cv=cv)
grid_search.fit(X, y)
first = grid_search.grid_scores_[0]
assert_equal(first.parameters['C'], 1)
assert_array_almost_equal(first.cv_validation_scores, [1, 1. / 3.])
# for first split, 1/4 of dataset is in test, for second 3/4.
# take weighted average
assert_almost_equal(first.mean_validation_score,
1 * 1. / 4. + 1. / 3. * 3. / 4.)
# once with iid=False
grid_search = GridSearchCV(svm, param_grid={'C': [1, 10]}, cv=cv,
iid=False)
grid_search.fit(X, y)
first = grid_search.grid_scores_[0]
assert_equal(first.parameters['C'], 1)
# scores are the same as above
assert_array_almost_equal(first.cv_validation_scores, [1, 1. / 3.])
# averaged score is just mean of scores
assert_almost_equal(first.mean_validation_score,
np.mean(first.cv_validation_scores))
def test_grid_search_one_grid_point():
X_, y_ = make_classification(n_samples=200, n_features=100, random_state=0)
param_dict = {"C": [1.0], "kernel": ["rbf"], "gamma": [0.1]}
clf = SVC()
cv = GridSearchCV(clf, param_dict)
cv.fit(X_, y_)
clf = SVC(C=1.0, kernel="rbf", gamma=0.1)
clf.fit(X_, y_)
assert_array_equal(clf.dual_coef_, cv.best_estimator_.dual_coef_)
def test_grid_search_bad_param_grid():
param_dict = {"C": 1.0}
clf = SVC()
assert_raises(ValueError, GridSearchCV, clf, param_dict)
param_dict = {"C": []}
clf = SVC()
assert_raises(ValueError, GridSearchCV, clf, param_dict)
param_dict = {"C": np.ones(6).reshape(3, 2)}
clf = SVC()
assert_raises(ValueError, GridSearchCV, clf, param_dict)
def test_grid_search_sparse():
# Test that grid search works with both dense and sparse matrices
X_, y_ = make_classification(n_samples=200, n_features=100, random_state=0)
clf = LinearSVC()
cv = GridSearchCV(clf, {'C': [0.1, 1.0]})
cv.fit(X_[:180], y_[:180])
y_pred = cv.predict(X_[180:])
C = cv.best_estimator_.C
X_ = sp.csr_matrix(X_)
clf = LinearSVC()
cv = GridSearchCV(clf, {'C': [0.1, 1.0]})
cv.fit(X_[:180].tocoo(), y_[:180])
y_pred2 = cv.predict(X_[180:])
C2 = cv.best_estimator_.C
assert_true(np.mean(y_pred == y_pred2) >= .9)
assert_equal(C, C2)
def test_grid_search_sparse_scoring():
X_, y_ = make_classification(n_samples=200, n_features=100, random_state=0)
clf = LinearSVC()
cv = GridSearchCV(clf, {'C': [0.1, 1.0]}, scoring="f1")
cv.fit(X_[:180], y_[:180])
y_pred = cv.predict(X_[180:])
C = cv.best_estimator_.C
X_ = sp.csr_matrix(X_)
clf = LinearSVC()
cv = GridSearchCV(clf, {'C': [0.1, 1.0]}, scoring="f1")
cv.fit(X_[:180], y_[:180])
y_pred2 = cv.predict(X_[180:])
C2 = cv.best_estimator_.C
assert_array_equal(y_pred, y_pred2)
assert_equal(C, C2)
# Smoke test the score
# np.testing.assert_allclose(f1_score(cv.predict(X_[:180]), y[:180]),
# cv.score(X_[:180], y[:180]))
# test loss where greater is worse
def f1_loss(y_true_, y_pred_):
return -f1_score(y_true_, y_pred_)
F1Loss = make_scorer(f1_loss, greater_is_better=False)
cv = GridSearchCV(clf, {'C': [0.1, 1.0]}, scoring=F1Loss)
cv.fit(X_[:180], y_[:180])
y_pred3 = cv.predict(X_[180:])
C3 = cv.best_estimator_.C
assert_equal(C, C3)
assert_array_equal(y_pred, y_pred3)
def test_grid_search_precomputed_kernel():
# Test that grid search works when the input features are given in the
# form of a precomputed kernel matrix
X_, y_ = make_classification(n_samples=200, n_features=100, random_state=0)
# compute the training kernel matrix corresponding to the linear kernel
K_train = np.dot(X_[:180], X_[:180].T)
y_train = y_[:180]
clf = SVC(kernel='precomputed')
cv = GridSearchCV(clf, {'C': [0.1, 1.0]})
cv.fit(K_train, y_train)
assert_true(cv.best_score_ >= 0)
# compute the test kernel matrix
K_test = np.dot(X_[180:], X_[:180].T)
y_test = y_[180:]
y_pred = cv.predict(K_test)
assert_true(np.mean(y_pred == y_test) >= 0)
# test error is raised when the precomputed kernel is not array-like
# or sparse
assert_raises(ValueError, cv.fit, K_train.tolist(), y_train)
def test_grid_search_precomputed_kernel_error_nonsquare():
# Test that grid search returns an error with a non-square precomputed
# training kernel matrix
K_train = np.zeros((10, 20))
y_train = np.ones((10, ))
clf = SVC(kernel='precomputed')
cv = GridSearchCV(clf, {'C': [0.1, 1.0]})
assert_raises(ValueError, cv.fit, K_train, y_train)
def test_grid_search_precomputed_kernel_error_kernel_function():
# Test that grid search returns an error when using a kernel_function
X_, y_ = make_classification(n_samples=200, n_features=100, random_state=0)
kernel_function = lambda x1, x2: np.dot(x1, x2.T)
clf = SVC(kernel=kernel_function)
cv = GridSearchCV(clf, {'C': [0.1, 1.0]})
assert_raises(ValueError, cv.fit, X_, y_)
class BrokenClassifier(BaseEstimator):
"""Broken classifier that cannot be fit twice"""
def __init__(self, parameter=None):
self.parameter = parameter
def fit(self, X, y):
assert_true(not hasattr(self, 'has_been_fit_'))
self.has_been_fit_ = True
def predict(self, X):
return np.zeros(X.shape[0])
@ignore_warnings
def test_refit():
# Regression test for bug in refitting
# Simulates re-fitting a broken estimator; this used to break with
# sparse SVMs.
X = np.arange(100).reshape(10, 10)
y = np.array([0] * 5 + [1] * 5)
clf = GridSearchCV(BrokenClassifier(), [{'parameter': [0, 1]}],
scoring="precision", refit=True)
clf.fit(X, y)
def test_gridsearch_nd():
# Pass X as list in GridSearchCV
X_4d = np.arange(10 * 5 * 3 * 2).reshape(10, 5, 3, 2)
y_3d = np.arange(10 * 7 * 11).reshape(10, 7, 11)
check_X = lambda x: x.shape[1:] == (5, 3, 2)
check_y = lambda x: x.shape[1:] == (7, 11)
clf = CheckingClassifier(check_X=check_X, check_y=check_y)
grid_search = GridSearchCV(clf, {'foo_param': [1, 2, 3]})
grid_search.fit(X_4d, y_3d).score(X, y)
assert_true(hasattr(grid_search, "grid_scores_"))
def test_X_as_list():
# Pass X as list in GridSearchCV
X = np.arange(100).reshape(10, 10)
y = np.array([0] * 5 + [1] * 5)
clf = CheckingClassifier(check_X=lambda x: isinstance(x, list))
cv = KFold(n=len(X), n_folds=3)
grid_search = GridSearchCV(clf, {'foo_param': [1, 2, 3]}, cv=cv)
grid_search.fit(X.tolist(), y).score(X, y)
assert_true(hasattr(grid_search, "grid_scores_"))
def test_y_as_list():
# Pass y as list in GridSearchCV
X = np.arange(100).reshape(10, 10)
y = np.array([0] * 5 + [1] * 5)
clf = CheckingClassifier(check_y=lambda x: isinstance(x, list))
cv = KFold(n=len(X), n_folds=3)
grid_search = GridSearchCV(clf, {'foo_param': [1, 2, 3]}, cv=cv)
grid_search.fit(X, y.tolist()).score(X, y)
assert_true(hasattr(grid_search, "grid_scores_"))
def test_pandas_input():
# check cross_val_score doesn't destroy pandas dataframe
types = [(MockDataFrame, MockDataFrame)]
try:
from pandas import Series, DataFrame
types.append((DataFrame, Series))
except ImportError:
pass
X = np.arange(100).reshape(10, 10)
y = np.array([0] * 5 + [1] * 5)
for InputFeatureType, TargetType in types:
# X dataframe, y series
X_df, y_ser = InputFeatureType(X), TargetType(y)
check_df = lambda x: isinstance(x, InputFeatureType)
check_series = lambda x: isinstance(x, TargetType)
clf = CheckingClassifier(check_X=check_df, check_y=check_series)
grid_search = GridSearchCV(clf, {'foo_param': [1, 2, 3]})
grid_search.fit(X_df, y_ser).score(X_df, y_ser)
grid_search.predict(X_df)
assert_true(hasattr(grid_search, "grid_scores_"))
def test_unsupervised_grid_search():
# test grid-search with unsupervised estimator
X, y = make_blobs(random_state=0)
km = KMeans(random_state=0)
grid_search = GridSearchCV(km, param_grid=dict(n_clusters=[2, 3, 4]),
scoring='adjusted_rand_score')
grid_search.fit(X, y)
# ARI can find the right number :)
assert_equal(grid_search.best_params_["n_clusters"], 3)
# Now without a score, and without y
grid_search = GridSearchCV(km, param_grid=dict(n_clusters=[2, 3, 4]))
grid_search.fit(X)
assert_equal(grid_search.best_params_["n_clusters"], 4)
def test_gridsearch_no_predict():
# test grid-search with an estimator without predict.
# slight duplication of a test from KDE
def custom_scoring(estimator, X):
return 42 if estimator.bandwidth == .1 else 0
X, _ = make_blobs(cluster_std=.1, random_state=1,
centers=[[0, 1], [1, 0], [0, 0]])
search = GridSearchCV(KernelDensity(),
param_grid=dict(bandwidth=[.01, .1, 1]),
scoring=custom_scoring)
search.fit(X)
assert_equal(search.best_params_['bandwidth'], .1)
assert_equal(search.best_score_, 42)
def test_param_sampler():
# test basic properties of param sampler
param_distributions = {"kernel": ["rbf", "linear"],
"C": uniform(0, 1)}
sampler = ParameterSampler(param_distributions=param_distributions,
n_iter=10, random_state=0)
samples = [x for x in sampler]
assert_equal(len(samples), 10)
for sample in samples:
assert_true(sample["kernel"] in ["rbf", "linear"])
assert_true(0 <= sample["C"] <= 1)
def test_randomized_search_grid_scores():
# Make a dataset with a lot of noise to get various kind of prediction
# errors across CV folds and parameter settings
X, y = make_classification(n_samples=200, n_features=100, n_informative=3,
random_state=0)
# XXX: as of today (scipy 0.12) it's not possible to set the random seed
# of scipy.stats distributions: the assertions in this test should thus
# not depend on the randomization
params = dict(C=expon(scale=10),
gamma=expon(scale=0.1))
n_cv_iter = 3
n_search_iter = 30
search = RandomizedSearchCV(SVC(), n_iter=n_search_iter, cv=n_cv_iter,
param_distributions=params, iid=False)
search.fit(X, y)
assert_equal(len(search.grid_scores_), n_search_iter)
# Check consistency of the structure of each cv_score item
for cv_score in search.grid_scores_:
assert_equal(len(cv_score.cv_validation_scores), n_cv_iter)
# Because we set iid to False, the mean_validation score is the
# mean of the fold mean scores instead of the aggregate sample-wise
# mean score
assert_almost_equal(np.mean(cv_score.cv_validation_scores),
cv_score.mean_validation_score)
assert_equal(list(sorted(cv_score.parameters.keys())),
list(sorted(params.keys())))
# Check the consistency with the best_score_ and best_params_ attributes
sorted_grid_scores = list(sorted(search.grid_scores_,
key=lambda x: x.mean_validation_score))
best_score = sorted_grid_scores[-1].mean_validation_score
assert_equal(search.best_score_, best_score)
tied_best_params = [s.parameters for s in sorted_grid_scores
if s.mean_validation_score == best_score]
assert_true(search.best_params_ in tied_best_params,
"best_params_={0} is not part of the"
" tied best models: {1}".format(
search.best_params_, tied_best_params))
def test_grid_search_score_consistency():
# test that correct scores are used
clf = LinearSVC(random_state=0)
X, y = make_blobs(random_state=0, centers=2)
Cs = [.1, 1, 10]
for score in ['f1', 'roc_auc']:
grid_search = GridSearchCV(clf, {'C': Cs}, scoring=score)
grid_search.fit(X, y)
cv = StratifiedKFold(n_folds=3, y=y)
for C, scores in zip(Cs, grid_search.grid_scores_):
clf.set_params(C=C)
scores = scores[2] # get the separate runs from grid scores
i = 0
for train, test in cv:
clf.fit(X[train], y[train])
if score == "f1":
correct_score = f1_score(y[test], clf.predict(X[test]))
elif score == "roc_auc":
dec = clf.decision_function(X[test])
correct_score = roc_auc_score(y[test], dec)
assert_almost_equal(correct_score, scores[i])
i += 1
def test_pickle():
# Test that a fit search can be pickled
clf = MockClassifier()
grid_search = GridSearchCV(clf, {'foo_param': [1, 2, 3]}, refit=True)
grid_search.fit(X, y)
pickle.dumps(grid_search) # smoke test
random_search = RandomizedSearchCV(clf, {'foo_param': [1, 2, 3]},
refit=True, n_iter=3)
random_search.fit(X, y)
pickle.dumps(random_search) # smoke test
def test_grid_search_with_multioutput_data():
# Test search with multi-output estimator
X, y = make_multilabel_classification(random_state=0)
est_parameters = {"max_depth": [1, 2, 3, 4]}
cv = KFold(y.shape[0], random_state=0)
estimators = [DecisionTreeRegressor(random_state=0),
DecisionTreeClassifier(random_state=0)]
# Test with grid search cv
for est in estimators:
grid_search = GridSearchCV(est, est_parameters, cv=cv)
grid_search.fit(X, y)
for parameters, _, cv_validation_scores in grid_search.grid_scores_:
est.set_params(**parameters)
for i, (train, test) in enumerate(cv):
est.fit(X[train], y[train])
correct_score = est.score(X[test], y[test])
assert_almost_equal(correct_score,
cv_validation_scores[i])
# Test with a randomized search
for est in estimators:
random_search = RandomizedSearchCV(est, est_parameters,
cv=cv, n_iter=3)
random_search.fit(X, y)
for parameters, _, cv_validation_scores in random_search.grid_scores_:
est.set_params(**parameters)
for i, (train, test) in enumerate(cv):
est.fit(X[train], y[train])
correct_score = est.score(X[test], y[test])
assert_almost_equal(correct_score,
cv_validation_scores[i])
def test_predict_proba_disabled():
# Test predict_proba when disabled on estimator.
X = np.arange(20).reshape(5, -1)
y = [0, 0, 1, 1, 1]
clf = SVC(probability=False)
gs = GridSearchCV(clf, {}, cv=2).fit(X, y)
assert_false(hasattr(gs, "predict_proba"))
def test_grid_search_allows_nans():
# Test GridSearchCV with Imputer
X = np.arange(20, dtype=np.float64).reshape(5, -1)
X[2, :] = np.nan
y = [0, 0, 1, 1, 1]
p = Pipeline([
('imputer', Imputer(strategy='mean', missing_values='NaN')),
('classifier', MockClassifier()),
])
GridSearchCV(p, {'classifier__foo_param': [1, 2, 3]}, cv=2).fit(X, y)
class FailingClassifier(BaseEstimator):
"""Classifier that raises a ValueError on fit()"""
FAILING_PARAMETER = 2
def __init__(self, parameter=None):
self.parameter = parameter
def fit(self, X, y=None):
if self.parameter == FailingClassifier.FAILING_PARAMETER:
raise ValueError("Failing classifier failed as required")
def predict(self, X):
return np.zeros(X.shape[0])
def test_grid_search_failing_classifier():
# GridSearchCV with on_error != 'raise'
# Ensures that a warning is raised and score reset where appropriate.
X, y = make_classification(n_samples=20, n_features=10, random_state=0)
clf = FailingClassifier()
# refit=False because we only want to check that errors caused by fits
# to individual folds will be caught and warnings raised instead. If
# refit was done, then an exception would be raised on refit and not
# caught by grid_search (expected behavior), and this would cause an
# error in this test.
gs = GridSearchCV(clf, [{'parameter': [0, 1, 2]}], scoring='accuracy',
refit=False, error_score=0.0)
assert_warns(FitFailedWarning, gs.fit, X, y)
# Ensure that grid scores were set to zero as required for those fits
# that are expected to fail.
assert all(np.all(this_point.cv_validation_scores == 0.0)
for this_point in gs.grid_scores_
if this_point.parameters['parameter'] ==
FailingClassifier.FAILING_PARAMETER)
gs = GridSearchCV(clf, [{'parameter': [0, 1, 2]}], scoring='accuracy',
refit=False, error_score=float('nan'))
assert_warns(FitFailedWarning, gs.fit, X, y)
assert all(np.all(np.isnan(this_point.cv_validation_scores))
for this_point in gs.grid_scores_
if this_point.parameters['parameter'] ==
FailingClassifier.FAILING_PARAMETER)
def test_grid_search_failing_classifier_raise():
# GridSearchCV with on_error == 'raise' raises the error
X, y = make_classification(n_samples=20, n_features=10, random_state=0)
clf = FailingClassifier()
# refit=False because we want to test the behaviour of the grid search part
gs = GridSearchCV(clf, [{'parameter': [0, 1, 2]}], scoring='accuracy',
refit=False, error_score='raise')
# FailingClassifier issues a ValueError so this is what we look for.
assert_raises(ValueError, gs.fit, X, y)
def test_parameters_sampler_replacement():
# raise error if n_iter too large
params = {'first': [0, 1], 'second': ['a', 'b', 'c']}
sampler = ParameterSampler(params, n_iter=7)
assert_raises(ValueError, list, sampler)
# degenerates to GridSearchCV if n_iter the same as grid_size
sampler = ParameterSampler(params, n_iter=6)
samples = list(sampler)
assert_equal(len(samples), 6)
for values in ParameterGrid(params):
assert_true(values in samples)
# test sampling without replacement in a large grid
params = {'a': range(10), 'b': range(10), 'c': range(10)}
sampler = ParameterSampler(params, n_iter=99, random_state=42)
samples = list(sampler)
assert_equal(len(samples), 99)
hashable_samples = ["a%db%dc%d" % (p['a'], p['b'], p['c'])
for p in samples]
assert_equal(len(set(hashable_samples)), 99)
# doesn't go into infinite loops
params_distribution = {'first': bernoulli(.5), 'second': ['a', 'b', 'c']}
sampler = ParameterSampler(params_distribution, n_iter=7)
samples = list(sampler)
assert_equal(len(samples), 7)
|
bsd-3-clause
|
amandalund/openmc
|
tests/regression_tests/mgxs_library_no_nuclides/test.py
|
6
|
2709
|
import hashlib
import openmc
import openmc.mgxs
from openmc.examples import pwr_pin_cell
from tests.testing_harness import PyAPITestHarness
class MGXSTestHarness(PyAPITestHarness):
def __init__(self, *args, **kwargs):
# Generate inputs using parent class routine
super().__init__(*args, **kwargs)
# Initialize a two-group structure
energy_groups = openmc.mgxs.EnergyGroups(group_edges=[0, 0.625, 20.e6])
# Initialize MGXS Library for a few cross section types
self.mgxs_lib = openmc.mgxs.Library(self._model.geometry)
self.mgxs_lib.by_nuclide = False
# Test relevant MGXS types
relevant_MGXS_TYPES = [item for item in openmc.mgxs.MGXS_TYPES
if item != 'current']
# Add in a subset of openmc.mgxs.ARBITRARY_VECTOR_TYPES and
# openmc.mgxs.ARBITRARY_MATRIX_TYPES so we can see the code works,
# but not use too much resources
relevant_MGXS_TYPES += [
"(n,elastic)", "(n,level)", "(n,2n)", "(n,na)", "(n,nc)",
"(n,gamma)", "(n,a)", "(n,Xa)", "heating", "damage-energy",
"(n,n1)", "(n,a0)", "(n,nc) matrix", "(n,n1) matrix",
"(n,2n) matrix"]
self.mgxs_lib.mgxs_types = tuple(relevant_MGXS_TYPES) + \
openmc.mgxs.MDGXS_TYPES
self.mgxs_lib.energy_groups = energy_groups
self.mgxs_lib.num_delayed_groups = 6
self.mgxs_lib.legendre_order = 3
self.mgxs_lib.domain_type = 'material'
self.mgxs_lib.build_library()
# Add tallies
self.mgxs_lib.add_to_tallies_file(self._model.tallies, merge=False)
def _get_results(self, hash_output=False):
"""Digest info in the statepoint and return as a string."""
# Read the statepoint file.
sp = openmc.StatePoint(self._sp_name)
# Load the MGXS library from the statepoint
self.mgxs_lib.load_from_statepoint(sp)
# Build a string from Pandas Dataframe for each MGXS
outstr = ''
for domain in self.mgxs_lib.domains:
for mgxs_type in self.mgxs_lib.mgxs_types:
mgxs = self.mgxs_lib.get_mgxs(domain, mgxs_type)
df = mgxs.get_pandas_dataframe()
outstr += mgxs_type + '\n' + df.to_string() + '\n'
# Hash the results if necessary
if hash_output:
sha512 = hashlib.sha512()
sha512.update(outstr.encode('utf-8'))
outstr = sha512.hexdigest()
return outstr
def test_mgxs_library_no_nuclides():
model = pwr_pin_cell()
harness = MGXSTestHarness('statepoint.10.h5', model)
harness.main()
|
mit
|
bearishtrader/trading-with-python
|
lib/backtest.py
|
74
|
7381
|
#-------------------------------------------------------------------------------
# Name: backtest
# Purpose: perform routine backtesting tasks.
# This module should be useable as a stand-alone library outide of the TWP package.
#
# Author: Jev Kuznetsov
#
# Created: 03/07/2014
# Copyright: (c) Jev Kuznetsov 2013
# Licence: BSD
#-------------------------------------------------------------------------------
import pandas as pd
import matplotlib.pyplot as plt
import sys
import numpy as np
def tradeBracket(price,entryBar,upper=None, lower=None, timeout=None):
'''
trade a bracket on price series, return price delta and exit bar #
Input
------
price : numpy array of price values
entryBar: entry bar number, *determines entry price*
upper : high stop
lower : low stop
timeout : max number of periods to hold
Returns exit price and number of bars held
'''
assert isinstance(price, np.ndarray) , 'price must be a numpy array'
# create list of exit indices and add max trade duration. Exits are relative to entry bar
if timeout: # set trade length to timeout or series length
exits = [min(timeout,len(price)-entryBar-1)]
else:
exits = [len(price)-entryBar-1]
p = price[entryBar:entryBar+exits[0]+1] # subseries of price
# extend exits list with conditional exits
# check upper bracket
if upper:
assert upper>p[0] , 'Upper bracket must be higher than entry price '
idx = np.where(p>upper)[0] # find where price is higher than the upper bracket
if idx.any():
exits.append(idx[0]) # append first occurence
# same for lower bracket
if lower:
assert lower<p[0] , 'Lower bracket must be lower than entry price '
idx = np.where(p<lower)[0]
if idx.any():
exits.append(idx[0])
exitBar = min(exits) # choose first exit
return p[exitBar], exitBar
class Backtest(object):
"""
Backtest class, simple vectorized one. Works with pandas objects.
"""
def __init__(self,price, signal, signalType='capital',initialCash = 0, roundShares=True):
"""
Arguments:
*price* Series with instrument price.
*signal* Series with capital to invest (long+,short-) or number of shares.
*sitnalType* capital to bet or number of shares 'capital' mode is default.
*initialCash* starting cash.
*roundShares* round off number of shares to integers
"""
#TODO: add auto rebalancing
# check for correct input
assert signalType in ['capital','shares'], "Wrong signal type provided, must be 'capital' or 'shares'"
#save internal settings to a dict
self.settings = {'signalType':signalType}
# first thing to do is to clean up the signal, removing nans and duplicate entries or exits
self.signal = signal.ffill().fillna(0)
# now find dates with a trade
tradeIdx = self.signal.diff().fillna(0) !=0 # days with trades are set to True
if signalType == 'shares':
self.trades = self.signal[tradeIdx] # selected rows where tradeDir changes value. trades are in Shares
elif signalType =='capital':
self.trades = (self.signal[tradeIdx]/price[tradeIdx])
if roundShares:
self.trades = self.trades.round()
# now create internal data structure
self.data = pd.DataFrame(index=price.index , columns = ['price','shares','value','cash','pnl'])
self.data['price'] = price
self.data['shares'] = self.trades.reindex(self.data.index).ffill().fillna(0)
self.data['value'] = self.data['shares'] * self.data['price']
delta = self.data['shares'].diff() # shares bought sold
self.data['cash'] = (-delta*self.data['price']).fillna(0).cumsum()+initialCash
self.data['pnl'] = self.data['cash']+self.data['value']-initialCash
@property
def sharpe(self):
''' return annualized sharpe ratio of the pnl '''
pnl = (self.data['pnl'].diff()).shift(-1)[self.data['shares']!=0] # use only days with position.
return sharpe(pnl) # need the diff here as sharpe works on daily returns.
@property
def pnl(self):
'''easy access to pnl data column '''
return self.data['pnl']
def plotTrades(self):
"""
visualise trades on the price chart
long entry : green triangle up
short entry : red triangle down
exit : black circle
"""
l = ['price']
p = self.data['price']
p.plot(style='x-')
# ---plot markers
# this works, but I rather prefer colored markers for each day of position rather than entry-exit signals
# indices = {'g^': self.trades[self.trades > 0].index ,
# 'ko':self.trades[self.trades == 0].index,
# 'rv':self.trades[self.trades < 0].index}
#
#
# for style, idx in indices.iteritems():
# if len(idx) > 0:
# p[idx].plot(style=style)
# --- plot trades
#colored line for long positions
idx = (self.data['shares'] > 0) | (self.data['shares'] > 0).shift(1)
if idx.any():
p[idx].plot(style='go')
l.append('long')
#colored line for short positions
idx = (self.data['shares'] < 0) | (self.data['shares'] < 0).shift(1)
if idx.any():
p[idx].plot(style='ro')
l.append('short')
plt.xlim([p.index[0],p.index[-1]]) # show full axis
plt.legend(l,loc='best')
plt.title('trades')
class ProgressBar:
def __init__(self, iterations):
self.iterations = iterations
self.prog_bar = '[]'
self.fill_char = '*'
self.width = 50
self.__update_amount(0)
def animate(self, iteration):
print '\r',self,
sys.stdout.flush()
self.update_iteration(iteration + 1)
def update_iteration(self, elapsed_iter):
self.__update_amount((elapsed_iter / float(self.iterations)) * 100.0)
self.prog_bar += ' %d of %s complete' % (elapsed_iter, self.iterations)
def __update_amount(self, new_amount):
percent_done = int(round((new_amount / 100.0) * 100.0))
all_full = self.width - 2
num_hashes = int(round((percent_done / 100.0) * all_full))
self.prog_bar = '[' + self.fill_char * num_hashes + ' ' * (all_full - num_hashes) + ']'
pct_place = (len(self.prog_bar) // 2) - len(str(percent_done))
pct_string = '%d%%' % percent_done
self.prog_bar = self.prog_bar[0:pct_place] + \
(pct_string + self.prog_bar[pct_place + len(pct_string):])
def __str__(self):
return str(self.prog_bar)
def sharpe(pnl):
return np.sqrt(250)*pnl.mean()/pnl.std()
|
bsd-3-clause
|
pstjohn/cobrapy
|
documentation_builder/conf.py
|
2
|
4432
|
# -*- coding: utf-8 -*-
#
# cobra documentation build configuration file, created by
# sphinx-quickstart on Wed Jun 13 19:17:34 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('..'))
# In order to build documentation that requires libraries to import
class Mock(object):
def __init__(self, *args, **kwargs):
return
def __call__(self, *args, **kwargs):
return Mock()
@classmethod
def __getattr__(cls, name):
if name in ('__file__', '__path__'):
return '/dev/null'
else:
return Mock()
MOCK_MODULES = ['numpy', 'scipy', 'scipy.sparse', 'scipy.io', 'scipy.stats',
'glpk', 'gurobipy', 'gurobipy.GRB', 'cplex', 'pp', 'libsbml',
'cplex.exceptions', 'pandas']
for mod_name in MOCK_MODULES:
sys.modules[mod_name] = Mock()
# -- General configuration ----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx',
'sphinx.ext.mathjax', 'sphinx.ext.viewcode',
'sphinx.ext.napoleon', 'sphinx.ext.mathjax', 'nbsphinx']
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'cobra'
copyright = u'2016, Daniel Robert Hyduke and Ali Ebrahim'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
from cobra.version import get_version, read_release_version
version = read_release_version()
# The full version, including alpha/beta/rc tags.
release = get_version()
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build', 'version.py', '.ipynb_checkpoints']
pygments_style = 'sphinx'
# -- Options for HTML output --------------------------------------------------
mathjax_path = 'https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
'preamble': r'\usepackage{amsmath,amssymb}',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'cobra.tex', u'cobra Documentation',
u'Daniel Robert Hyduke and Ali Ebrahim', 'manual'),
]
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'cobra', u'cobra Documentation',
[u'Daniel Robert Hyduke and Ali Ebrahim'], 1)
]
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'cobra', u'cobra Documentation',
u'Daniel Robert Hyduke and Ali Ebrahim', 'cobra',
'A package for constraints-based modeling of biological networks',
'Miscellaneous'),
]
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {"http://docs.python.org/": None,
"http://docs.scipy.org/doc/numpy/": None,
"http://docs.scipy.org/doc/scipy/reference": None}
intersphinx_cache_limit = 10 # days to keep the cached inventories
|
gpl-2.0
|
trustswz/IRTK
|
wrapping/cython/scripts/learn_mser.py
|
5
|
8173
|
#!/usr/bin/python
import cv2
import sys
import csv
import numpy as np
from math import cos,sin
import math
import SimpleITK as sitk
import argparse
from glob import glob
from sklearn import cluster
from sklearn import neighbors
from sklearn import svm
from sklearn.externals import joblib
from joblib import Parallel, delayed
from scipy.stats.mstats import mquantiles
######################################################################
def is_in_ellipse( (x,y), ((xe,ye),(we,he),theta)):
theta = theta / 180 * np.pi
u = cos(theta)*(x-xe)+ sin(theta)*(y-ye)
v = -sin(theta)*(x-xe)+cos(theta)*(y-ye)
# http://answers.opencv.org/question/497/extract-a-rotatedrect-area/
# http://felix.abecassis.me/2011/10/opencv-rotation-deskewing/
# if theta < -45:
# tmp = we
# we = he
# he = we
a = we/2
b = he/2
return (u/a)**2 + (v/b)**2 <= 1
def process_file( raw_file, ga, coordinates, size, classifier, N, NEW_SAMPLING, DEBUG=False ):
X = []
Y = []
ofd_model = np.array([ -4.97315445e-03,
3.19846853e-01,
-2.60839214e+00,
2.62679565e+01])
OFD = 0
for k in range(4):
OFD += ofd_model[3-k]*ga**k
OFD /= NEW_SAMPLING
mser = cv2.MSER( _delta=5,
_min_area=60,
_max_area=14400,
_max_variation=0.15,
_min_diversity=.1,
_max_evolution=200,
_area_threshold=1.01,
_min_margin=0.003,
_edge_blur_size=5)
sift = cv2.SIFT( nfeatures=0,
nOctaveLayers=3,
contrastThreshold=0.04,
edgeThreshold=10,
sigma=0.8)
siftExtractor = cv2.DescriptorExtractor_create("SIFT")
coordinates = np.array(map(float,coordinates.split(',')),dtype='float')
size = np.array(map(float,size.split(',')),dtype='float')
sitk_img = sitk.ReadImage( raw_file )
raw_spacing = sitk_img.GetSpacing()
## Resample
resample = sitk.ResampleImageFilter()
resample.SetOutputDirection(sitk_img.GetDirection())
resample.SetOutputOrigin(sitk_img.GetOrigin())
resample.SetOutputSpacing([NEW_SAMPLING,NEW_SAMPLING,raw_spacing[2]])
resample.SetSize([int(sitk_img.GetSize()[0]*raw_spacing[0]/NEW_SAMPLING),
int(sitk_img.GetSize()[1]*raw_spacing[1]/NEW_SAMPLING),
sitk_img.GetSize()[2]])
sitk_img = resample.Execute(sitk_img)
# Adjust coordinates and size
box = coordinates * np.array([1.0,raw_spacing[1]/NEW_SAMPLING,raw_spacing[0]/NEW_SAMPLING],dtype='float')
box_size = size * np.array([1.0,raw_spacing[1]/NEW_SAMPLING,raw_spacing[0]/NEW_SAMPLING],dtype='float')
z0,y0,x0 = box.astype('int')
d0,h0,w0 = box_size.astype('int')
brain_center = (x0 + w0/2, y0 + h0/2)
data = sitk.GetArrayFromImage( sitk_img ).astype("float")
## Contrast-stretch with saturation
q = mquantiles(data.flatten(),[0.01,0.99])
data[data<q[0]] = q[0]
data[data>q[1]] = q[1]
data -= data.min()
data /= data.max()
data *= 255
data = data.astype('uint8')
for z in range(data.shape[0]):
contours = mser.detect(data[z,:,:])
keypoints = sift.detect(data[z,:,:])
if keypoints is None or len(keypoints) == 0:
continue
(keypoints, descriptors) = siftExtractor.compute(data[z,:,:],keypoints)
for i,c in enumerate(contours):
hist = np.zeros(N, dtype='float')
ellipse = cv2.fitEllipse(np.array(map(lambda x:[x],
c),dtype='int32'))
# filter by size
if ( ellipse[1][0] > OFD
or ellipse[1][1] > OFD
or ellipse[1][0] < 0.5*OFD
or ellipse[1][1] < 0.5*OFD ) :
continue
# filter by eccentricity
# if math.sqrt(1-(np.min(ellipse[1])/np.max(ellipse[1]))**2) > 0.75:
# continue
distance = math.sqrt((ellipse[0][0]-brain_center[0])**2
+(ellipse[0][1]-brain_center[1])**2)
if max(w0,h0)/2 >= distance >= min(w0,h0)/8:
continue
for k,d in zip(keypoints,descriptors):
if is_in_ellipse(k.pt,ellipse):
c = classifier.kneighbors(d, return_distance=False)
hist[c] += 1
# Normalize histogram
norm = np.linalg.norm(hist)
if norm > 0:
hist /= norm
if distance > max(w0,h0)/4:
if DEBUG: print 0
X.append(hist)
Y.append(0)
else:
if distance < min(w0,h0)/8 and z0 + d0/8 <= z <= z0+7*d0/8:
if DEBUG: print 1
X.append(hist)
Y.append(1)
else:
continue
if DEBUG:
img_color = cv2.cvtColor( data[z,:,:], cv2.cv.CV_GRAY2RGB )
cv2.ellipse( img_color, (ellipse[0],
(ellipse[1][0],ellipse[1][1]),
ellipse[2]) , (0,0,255))
for k_id,k in enumerate(keypoints):
if is_in_ellipse(k.pt,ellipse):
if Y[-1] == 1:
cv2.circle( img_color,
(int(k.pt[0]),int(k.pt[1])),
2,
(0,255,0),
-1)
else:
cv2.circle( img_color,
(int(k.pt[0]),int(k.pt[1])),
2,
(0,0,255),
-1)
cv2.imwrite("/tmp/"+str(z) + '_' +str(i) +'_'+str(k_id)+".png",img_color)
# cv2.imshow("show",img_color)
# cv2.waitKey(0)
return X,Y
######################################################################
parser = argparse.ArgumentParser(
description='Learn MSER classifier using SIFT BOW.' )
parser.add_argument( '--training_patients' )
parser.add_argument( '--original_folder' )
parser.add_argument( '--ga_file' )
parser.add_argument( '--clean_brainboxes' )
parser.add_argument( '--new_sampling', type=float )
parser.add_argument( '--vocabulary' )
parser.add_argument( '--output' )
parser.add_argument( '--debug', action="store_true", default=False )
args = parser.parse_args()
vocabulary = open(args.vocabulary, 'rb')
voca = np.load(vocabulary)
classifier = neighbors.NearestNeighbors(1)
N = voca.shape[0]
classifier.fit(voca)
f = open( args.training_patients, "r" )
patients = []
for p in f:
patients.append(p.rstrip())
f.close()
reader = csv.reader( open( args.ga_file, "rb"), delimiter=" " )
all_ga = {}
for patient_id, ga in reader:
all_ga[patient_id] = float(ga)
reader = csv.reader( open( args.clean_brainboxes, "r" ),
delimiter='\t' )
training_patients = []
for patient_id, raw_file, cl, coordinates, size in reader:
if patient_id not in patients:
print "Skipping testing patient: " + patient_id
continue
training_patients.append((args.original_folder + '/' + raw_file,all_ga[patient_id],coordinates, size))
XY = Parallel(n_jobs=-1)(delayed(process_file)(raw_file,ga,coordinates, size, classifier,N,args.new_sampling,args.debug)
for raw_file,ga,coordinates, size in training_patients )
print len(XY)
X = []
Y = []
for x,y in XY:
X.extend(x)
Y.extend(y)
print "RATIO = ", np.sum(Y), len(Y)
X = np.array(X,dtype='float')
Y = np.array(Y,dtype='float')
# svc = svm.SVC()
svc = svm.LinearSVC(dual=False,)
svc.fit(X, Y)
print svc.score(X, Y)
joblib.dump(svc, args.output)
|
bsd-3-clause
|
pmeier82/spikeval
|
spikeval/plot/plot_waveforms.py
|
1
|
4681
|
# -*- coding: utf-8 -*-
#
# spikeval - plot.plot_waveforms.py
#
# Philipp Meier <pmeier82 at googlemail dot com>
# 2012-08-27
#
"""waveform plot for extracted spike waveforms"""
__docformat__ = 'restructuredtext'
__all__ = ['waveforms']
##---IMPORTS
import scipy as sp
from .common import COLOURS, gen_fig
##---FUNCTION
def waveforms(waveforms, samples_per_second=None, tf=None, plot_mean=False, plot_single_waveforms=True,
set_y_range=False, plot_separate=True, templates=None, colours=None, title=None):
"""plot one set of spiketrains or two sets of spkitrains with their
interspike alignment
:type waveforms: dict
:param waveforms: dict of ndarray, holding the waveforms for different units.
:type samples_per_second: int
:param samples_per_second: Scale factor for the axis.
:type tf: int
:param tf: The template length of the waveforms
:type plot_mean: bool
:param plot_mean: If True, plot the mean-waveform per unit.
:type plot_single_waveforms: bool
:param plot_single_waveforms: If True, plot the single waveforms per unit.
:type plot_separate: bool
:param plot_separate: If True, plot each units waveforms in a separate axis.
:type templates: dict
:param templates: dict holding one concatenates waveform per key
:type set_y_range: bool
:param set_y_range: Adjust the y-axis range so waveforms fit in nicely.
:type colours: list
:param colours: A list of matplotlib conform color values (rgb 3-tuples). If
None the common.plot.COLORS set is used.
:type title: str
:param title: Title for the plot. No title if None or ''.
:rtype: matplotlib.figure.Figure
"""
# init and checks
col_lst = colours or COLOURS
fig = gen_fig()
if plot_separate is False:
ax = fig.add_subplot(111)
else:
ax = None
if type(waveforms) is not dict:
waveforms = {'0': waveforms}
srate = samples_per_second or 1.0
for k in waveforms.keys():
if waveforms[k].ndim == 3:
waveforms[k] = sp.vstack(
[sp.hstack(
[waveforms[k][i, :, j]
for j in xrange(waveforms[k].shape[-1])])
for i in xrange(waveforms[k].shape[0])])
firstKey = waveforms.keys()[0]
nunits = len(waveforms)
my_ymin = waveforms[firstKey].min()
my_ymax = waveforms[firstKey].max()
my_xmax = waveforms[firstKey].shape[1] - 1
nc = 1
if tf is not None:
nc = int(waveforms[firstKey].shape[1] / tf)
# plot single waveforms
if plot_single_waveforms is True:
col_idx = 0
for u, k in enumerate(sorted(waveforms.keys())):
if plot_separate is True:
ax = fig.add_subplot(nunits, 1, u + 1, sharex=ax, sharey=ax)
nevent, nsample = waveforms[k].shape
my_ymin = min(my_ymin, waveforms[k].min())
my_ymax = max(my_ymax, waveforms[k].max())
my_xmax = max(my_xmax, waveforms[k].shape[1] - 1)
col = col_lst[col_idx % len(col_lst)]
if plot_mean is True:
col = 'gray'
for i in xrange(waveforms[k].shape[0]):
ax.plot(sp.arange(nsample) / srate, waveforms[k][i, :],
color=col)
col_idx += 1
# addition: per axis event count
ax.set_ylabel('n:%s' % nevent)
# plot mean waveforms
if plot_mean is True:
col_idx = 0
for u, k in enumerate(sorted(waveforms.keys())):
if plot_separate is True:
ax = fig.axes[u]
if templates is not None and k in templates:
my_mean = templates[k]
else:
my_mean = waveforms[k].mean(axis=0)
my_ymin = min(my_ymin, my_mean.min())
my_ymax = max(my_ymax, my_mean.max())
my_xmax = max(my_xmax, my_mean.size - 1)
ax.plot(sp.arange(my_mean.size) / srate, my_mean,
c=col_lst[col_idx % len(col_lst)], lw=2)
col_idx += 1
# if multichannel waveforms, plot vertical lines at channel borders
if tf is not None:
for i in xrange(1, nc):
for a in fig.axes:
a.axvline((tf * i) / srate, ls='dashed', color='y')
# fancy stuff
if title is not None:
fig.suptitle(title)
if samples_per_second is not None:
ax.set_xlabel('time [s]')
else:
ax.set_xlabel('time [samples]')
ax.set_xlim(0, my_xmax)
if set_y_range is True:
ax.set_ylim((1.01 * my_ymin, 1.01 * my_ymax))
# return
return fig
##---MAIN
if __name__ == '__main__':
pass
|
mit
|
jajcayn/pyclits
|
pyclits/mutual_inf.py
|
1
|
22903
|
"""
created on May 6, 2015
@author: Nikola Jajcay, jajcay(at)cs.cas.cz
last update on Sep 22, 2017
"""
import numpy as np
def get_time_series_condition(ts, tau=1, reversed=False, dim_of_condition=1, eta=0,
close_condition=False, phase_diff=False, add_cond=None):
"""
Returns time series for CMI as list in the sense
I(x; y | z), where x = x(t); y = y(t+tau) | z = [y(t), y(t-eta), y(t-2eta), ...] up to dim_of_condition
so x -- master time series, y -- slave time series, z -- list of condtions (slave time series in the past)
tau and eta are forward and backward time lags, respectively.
If reversed is True, the master (ts[0, :]) and the slave (ts[1, :]) are reversed (for CMI in other direction).
If close_condition is True, the conditions are returned as
z = [y(t+tau-1), y(t+tau-1-eta), y(t+tau-1-2eta), ...] up to dim_of_condition,
so the conditions are closer in temporal sense to the slave time series.
If phase_diff is True, as y, the phase differences (future - first cond.) will be used (use only with phase data, not raw).
add_cond if None, is time series of shape [x, len] where x is number of additional time series to be put into the
condition as of 'now', thus without any backward lag. These additional conditions are NOT counted in the dimension
of condition parameter.
"""
if isinstance(ts, list) and len(ts) > 1:
if len(ts) != 2:
raise Exception("Input must be a list of 1D arrays (or a 2 x length array).")
if ts[0].shape != ts[1].shape:
raise Exception("Both time series must be the same length.")
master = ts[1].copy() if reversed else ts[0].copy()
slave = ts[0].copy() if reversed else ts[1].copy()
elif isinstance(ts, np.ndarray):
if np.squeeze(ts).ndim != 2:
raise Exception("Input must be 2 x length array (or a list of 1D arrays).")
master = ts[1, :].copy() if reversed else ts[0, :].copy()
slave = ts[0, :].copy() if reversed else ts[1, :].copy()
else:
raise Exception("Input not understood. Use either list of 1D arrays or 2 x length array.")
if add_cond is not None:
add_cond = np.atleast_2d(add_cond)
assert add_cond.shape[1] == master.shape[0]
if dim_of_condition > 4:
print("** WARNING -- for %d dimensional condition the estimation might be biased." % (dim_of_condition))
if (dim_of_condition > 1 and eta == 0):
raise Exception("For multidimensional condition the backward lag eta must be chosen.")
n_eta = dim_of_condition - 1
n = master.shape[0] - tau - n_eta*eta
if eta is None:
eta = 0
else:
eta = int(eta)
x = master[n_eta*eta : -tau] # "now"
if x.shape[0] != n:
raise Exception("Something went wrong! Check input data.")
y = slave[n_eta*eta+tau :] # "tau future"
if y.shape[0] != n:
raise Exception("Something went wrong! Check input data.")
z = []
for i in range(dim_of_condition):
if close_condition:
cond = slave[(n_eta-i)*eta+tau-1 : -1-i*eta] # "almost future" until ...
else:
cond = slave[(n_eta-i)*eta : -tau-i*eta] # "now" until "n_eta eta past"
if cond.shape[0] != n:
raise Exception("Something went wrong! Check input data.")
z.append(cond)
if add_cond is not None:
for condextra in range(add_cond.shape[0]):
if close_condition:
extra_cond = add_cond[condextra, n_eta*eta+tau-1 : -1]
else:
extra_cond = add_cond[condextra, n_eta*eta : -tau] # "now"
if extra_cond.shape[0] != n:
raise Exception("Something went wrong! Check input data.")
z.append(extra_cond)
if phase_diff:
y = y - z[0]
y[y < -np.pi] += 2*np.pi
return (x, y, z)
def mutual_information(x, y, algorithm='EQQ', bins=8, log2=True):
"""
Computes mutual information between two time series x and y as
I(x; y) = sum( p(x,y) * log( p(x,y) / p(x)p(y) ),
where p(x), p(y) and p(x, y) are probability distributions.
The probability distributions could be estimated using these algorithms:
equiquantal binning - algorithm keyword 'EQQ' or 'EQQ2'
EQQ - equiquantality is forced (even if many samples have the same value
at and near the bin edge), can happen that samples with same value fall
into different bin
EQQ2 - if more than one sample has the same value at the bin edge, the edge is shifted,
so that all samples with the same value fall into the same bin, can happen that bins
do not necessarily contain the same amount of samples
equidistant binning - algorithm keyword 'EQD'
(preparing more...)
If log2 is True (default), the units of mutual information are bits, if False
the mutual information is be estimated using natural logarithm and therefore
units are nats.
"""
log_f = np.log2 if log2 else np.log
if algorithm == 'EQD':
x_bins = bins
y_bins = bins
xy_bins = bins
elif algorithm == 'EQQ':
# create EQQ bins
x_sorted = np.sort(x)
x_bins = [x.min()]
[x_bins.append(x_sorted[i*x.shape[0]/bins]) for i in range(1, bins)]
x_bins.append(x.max())
y_sorted = np.sort(y)
y_bins = [y.min()]
[y_bins.append(y_sorted[i*y.shape[0]/bins]) for i in range(1, bins)]
y_bins.append(y.max())
xy_bins = [x_bins, y_bins]
elif algorithm == 'EQQ2':
x_sorted = np.sort(x)
x_bins = [x.min()]
one_bin_count = x.shape[0] / bins
for i in range(1, bins):
idx = i * one_bin_count
if np.all(np.diff(x_sorted[idx-1:idx+2]) != 0):
x_bins.append(x_sorted[idx])
elif np.any(np.diff(x_sorted[idx-1:idx+2]) == 0):
where = np.where(np.diff(x_sorted[idx-1:idx+2]) != 0)[0]
expand_idx = 1
while where.size == 0:
where = np.where(np.diff(x_sorted[idx-expand_idx:idx+1+expand_idx]) != 0)[0]
expand_idx += 1
if where[0] == 0:
x_bins.append(x_sorted[idx-expand_idx])
else:
x_bins.append(x_sorted[idx+expand_idx])
x_bins.append(x.max())
y_sorted = np.sort(y)
y_bins = [y.min()]
one_bin_count = y.shape[0] / bins
for i in range(1, bins):
idx = i * one_bin_count
if np.all(np.diff(y_sorted[idx-1:idx+2]) != 0):
y_bins.append(y_sorted[idx])
elif np.any(np.diff(y_sorted[idx-1:idx+2]) == 0):
where = np.where(np.diff(y_sorted[idx-1:idx+2]) != 0)[0]
expand_idx = 1
while where.size == 0:
where = np.where(np.diff(y_sorted[idx-expand_idx:idx+1+expand_idx]) != 0)[0]
expand_idx += 1
if where[0] == 0:
y_bins.append(y_sorted[idx-expand_idx])
else:
y_bins.append(y_sorted[idx+expand_idx])
y_bins.append(y.max())
xy_bins = [x_bins, y_bins]
# histo
count_x = np.histogramdd([x], bins = [x_bins])[0]
count_y = np.histogramdd([y], bins = [y_bins])[0]
count_xy = np.histogramdd([x, y], bins = xy_bins)[0]
# normalise
count_xy /= np.float(np.sum(count_xy))
count_x /= np.float(np.sum(count_x))
count_y /= np.float(np.sum(count_y))
# sum
mi = 0
for i in range(bins):
for j in range(bins):
if count_x[i] != 0 and count_y[j] != 0 and count_xy[i, j] != 0:
mi += count_xy[i, j] * log_f(count_xy[i, j] / (count_x[i] * count_y[j]))
return mi
def knn_mutual_information(x, y, k, standardize = True, symm_algorithm = True, dualtree = True):
"""
Computes mutual information between two time series x and y as
I(x; y) = sum( p(x,y) * log( p(x,y) / p(x)p(y) ),
where p(x), p(y) and p(x, y) are probability distributions.
Performs k-nearest neighbours search using k-dimensional tree.
Uses sklearn.neighbors for KDTree class.
standardize - whether transform data to zero mean and unit variance
symm_algorithm
True - use symmetric algorithm with one eps in both dimensions
False - use different eps_x and eps_y in respective dimensions -- SOME PROBLEMS, DON'T USE NOW
dualtree - whether to use dualtree formalism in k-d tree for the k-NN search
could lead to better performance with large N
According to Kraskov A., Stogbauer H. and Grassberger P., Phys. Rev. E, 69, 2004.
"""
from sklearn.neighbors import KDTree
from scipy.special import digamma
# prepare data
if standardize:
x = _center_ts(x)
y = _center_ts(y)
data = np.vstack([x, y]).T
# build k-d tree using the maximum (Chebyshev) norm
tree = KDTree(data, leaf_size = 15, metric = "chebyshev")
# find k-nearest neighbour indices for each point
dist, ind = tree.query(data, k = k + 1, return_distance = True, dualtree = dualtree)
sum_ = 0
for n in range(data.shape[0]):
# find x and y distances between nth point and its k-nearest neighbour
eps_x = np.abs(data[n, 0] - data[ind[n, -1], 0])
eps_y = np.abs(data[n, 1] - data[ind[n, -1], 1])
if symm_algorithm:
# use symmetric algorithm with one eps - see the paper
eps = np.max((eps_x, eps_y))
# find number of points within eps distance
n_x = np.sum(np.less(np.abs(x - x[n]), eps)) - 1
n_y = np.sum(np.less(np.abs(y - y[n]), eps)) - 1
# add to digamma sum
sum_ += digamma(n_x + 1) + digamma(n_y + 1)
else:
# use asymmetric algorithm with eps_x and eps_y - see the paper
# find number of points within eps distance
n_x = np.sum(np.less(np.abs(x - x[n]), eps_x)) - 1
n_y = np.sum(np.less(np.abs(y - y[n]), eps_y)) - 1
# add to digamma sum
if n_x != 0:
sum_ += digamma(n_x)
if n_y != 0:
sum_ += digamma(n_y)
sum_ /= data.shape[0]
if symm_algorithm:
return digamma(k) - sum_ + digamma(data.shape[0])
else:
return digamma(k) - 1./k - sum_ + digamma(data.shape[0])
def _center_ts(ts):
"""
Returns centered time series with zero mean and unit variance.
"""
if np.squeeze(ts).ndim != 1:
raise Exception("Only 1D time series can be centered")
ts -= np.mean(ts)
ts /= np.std(ts, ddof = 1)
return ts
def _get_corr_entropy(list_ts, log2 = True):
"""
Returns modified entropy to use in Gaussian correlation matrix CMI computation.
H = -0.5 * sum( log(eigvals) )
where eigvals are eigenvalues of correlation matrix between time series.
"""
log_f = np.log2 if log2 else np.log
corr_matrix = np.corrcoef(list_ts)
eigvals = np.linalg.eigvals(corr_matrix)
eigvals = eigvals[eigvals > 0.]
return -0.5 * np.nansum(log_f(eigvals))
def cond_mutual_information(x, y, z, algorithm = 'EQQ', bins = 8, log2 = True):
"""
Computes conditional mutual information between two time series x and y
conditioned on a third z (which can be multi-dimensional) as
I(x; y | z) = sum( p(x,y,z) * log( p(z)*p(x,y,z) / p(x,z)*p(y,z) ),
where p(z), p(x,z), p(y,z) and p(x,y,z) are probability distributions.
The probability distributions could be estimated using these algorithms:
equiquantal binning - algorithm keyword 'EQQ' or 'EQQ2'
EQQ - equiquantality is forced (even if many samples have the same value
at and near the bin edge), can happen that samples with same value fall
into different bin
EQQ2 - if more than one sample has the same value at the bin edge, the edge is shifted,
so that all samples with the same value fall into the same bin, can happen that bins
do not necessarily contain the same amount of samples
equidistant binning - algorithm keyword 'EQD'
Gaussian correlation matrix - algorithm keyword 'GCM' (for phase - amplitude dependence)
(preparing more...)
If log2 is True (default), the units of cond. mutual information are bits, if False
the mutual information is estimated using natural logarithm and therefore
units are nats.
"""
log_f = np.log2 if log2 else np.log
# binning algorithms
if 'EQ' in algorithm:
# for multi-dimensional condition -- create array from list as (dim x length of ts)
x = np.atleast_2d(x)
y = np.atleast_2d(y)
z = np.atleast_2d(z)
if algorithm == 'EQQ':
# create EQQ bins -- condition [possibly multidimensional]
z_bins = [] # arrays of bins for all conditions
for cond in range(z.shape[0]):
z_sorted = np.sort(z[cond, :])
z_bin = [z_sorted.min()]
[z_bin.append(z_sorted[i*z_sorted.shape[0]/bins]) for i in range(1, bins)]
z_bin.append(z_sorted.max())
z_bins.append(np.array(z_bin))
# create EQQ bins -- variables
x_bins = []
for cond in range(x.shape[0]):
x_sorted = np.sort(x[cond, :])
x_bin = [x_sorted.min()]
[x_bin.append(x_sorted[i*x_sorted.shape[0]/bins]) for i in range(1, bins)]
x_bin.append(x_sorted.max())
x_bins.append(np.array(x_bin))
y_bins = []
for cond in range(y.shape[0]):
y_sorted = np.sort(y[cond, :])
y_bin = [y_sorted.min()]
[y_bin.append(y_sorted[i*y_sorted.shape[0]/bins]) for i in range(1, bins)]
y_bin.append(y_sorted.max())
y_bins.append(np.array(y_bin))
# create multidim bins for histogram
xyz_bins = x_bins + y_bins + z_bins
xz_bins = x_bins + z_bins
yz_bins = y_bins + z_bins
elif algorithm == 'EQQ2':
# create EQQ bins -- condition [possibly multidimensional]
z_bins = [] # arrays of bins for all conditions
for cond in range(z.shape[0]):
z_sorted = np.sort(z[cond, :])
z_bin = [z_sorted.min()]
one_bin_count = z_sorted.shape[0] / bins
for i in range(1, bins):
idx = i * one_bin_count
if np.all(np.diff(z_sorted[idx-1:idx+2]) != 0):
z_bin.append(z_sorted[idx])
elif np.any(np.diff(z_sorted[idx-1:idx+2]) == 0):
where = np.where(np.diff(z_sorted[idx-1:idx+2]) != 0)[0]
expand_idx = 1
while where.size == 0:
where = np.where(np.diff(z_sorted[idx-expand_idx:idx+1+expand_idx]) != 0)[0]
expand_idx += 1
if where[0] == 0:
z_bin.append(z_sorted[idx-expand_idx])
else:
z_bin.append(z_sorted[idx+expand_idx])
z_bin.append(z_sorted.max())
z_bin = np.array(z_bin)
z_bins.append(np.array(z_bin))
# create EQQ bins -- variables
x_bins = [] # arrays of bins for all conditions
for cond in range(x.shape[0]):
x_sorted = np.sort(x[cond, :])
x_bin = [x_sorted.min()]
one_bin_count = x_sorted.shape[0] / bins
for i in range(1, bins):
idx = i * one_bin_count
if np.all(np.diff(x_sorted[idx-1:idx+2]) != 0):
x_bin.append(x_sorted[idx])
elif np.any(np.diff(x_sorted[idx-1:idx+2]) == 0):
where = np.where(np.diff(x_sorted[idx-1:idx+2]) != 0)[0]
expand_idx = 1
while where.size == 0:
where = np.where(np.diff(x_sorted[idx-expand_idx:idx+1+expand_idx]) != 0)[0]
expand_idx += 1
if where[0] == 0:
x_bin.append(x_sorted[idx-expand_idx])
else:
x_bin.append(x_sorted[idx+expand_idx])
x_bin.append(x_sorted.max())
x_bin = np.array(x_bin)
x_bins.append(np.array(x_bin))
y_bins = [] # arrays of bins for all conditions
for cond in range(y.shape[0]):
y_sorted = np.sort(y[cond, :])
y_bin = [y_sorted.min()]
one_bin_count = y_sorted.shape[0] / bins
for i in range(1, bins):
idx = i * one_bin_count
if np.all(np.diff(y_sorted[idx-1:idx+2]) != 0):
y_bin.append(y_sorted[idx])
elif np.any(np.diff(y_sorted[idx-1:idx+2]) == 0):
where = np.where(np.diff(y_sorted[idx-1:idx+2]) != 0)[0]
expand_idx = 1
while where.size == 0:
where = np.where(np.diff(y_sorted[idx-expand_idx:idx+1+expand_idx]) != 0)[0]
expand_idx += 1
if where[0] == 0:
y_bin.append(y_sorted[idx-expand_idx])
else:
y_bin.append(y_sorted[idx+expand_idx])
y_bin.append(y_sorted.max())
y_bin = np.array(y_bin)
y_bins.append(np.array(y_bin))
# create multidim bins for histogram
xyz_bins = x_bins + y_bins + z_bins
xz_bins = x_bins + z_bins
yz_bins = y_bins + z_bins
elif algorithm == 'EQD':
# bins are just integer
xyz_bins = bins
xz_bins = bins
yz_bins = bins
z_bins = bins
# histo
count_z = np.histogramdd(z.T, bins = z_bins)[0]
xyz = np.vstack((x, y, z))
count_xyz = np.histogramdd(xyz.T, bins = xyz_bins)[0]
xz = np.vstack((x, z))
count_xz = np.histogramdd(xz.T, bins = xz_bins)[0]
yz = np.vstack((y, z))
count_yz = np.histogramdd(yz.T, bins = yz_bins)[0]
# normalise
count_z /= np.float(np.sum(count_z))
count_xyz /= np.float(np.sum(count_xyz))
count_xz /= np.float(np.sum(count_xz))
count_yz /= np.float(np.sum(count_yz))
# sum
cmi = 0
iterator = np.nditer(count_xyz, flags = ['multi_index'])
while not iterator.finished:
idx = iterator.multi_index
xz_idx = tuple([ item for sublist in [idx[:len(x)], idx[-len(z):]] for item in sublist ]) # creates index for xz histo
yz_idx = idx[-len(z)-len(y):]
z_idx = idx[-len(z):]
if count_xyz[idx] == 0 or count_z[z_idx] == 0 or count_xz[xz_idx] == 0 or count_yz[yz_idx] == 0:
iterator.iternext()
continue
else:
cmi += count_xyz[idx] * log_f(count_z[z_idx] * count_xyz[idx] / (count_xz[xz_idx] * count_yz[yz_idx]))
iterator.iternext()
elif algorithm == 'GCM':
if len(z) <= 1:
raise Exception("Gaussian correlation matrix method should be used with multidimensional condition.")
# center time series - zero mean, unit variance
x = _center_ts(x)
y = _center_ts(y)
for cond_ts in z:
cond_ts = _center_ts(cond_ts)
# get CMI
Hall = _get_corr_entropy([x, y] + list(z), log2 = log2)
Hxz = _get_corr_entropy([x] + list(z), log2 = log2)
Hyz = _get_corr_entropy([y] + list(z), log2 = log2)
Hz = _get_corr_entropy(z, log2 = log2)
cmi = Hall - Hxz - Hyz + Hz
return cmi
def _neg_harmonic(n):
"""
Returns a negative Nth harmonic number.
For knn CMI computation
"""
return -np.sum(1./np.arange(1,n+1))
def knn_cond_mutual_information(x, y, z, k, standardize = True, dualtree = True):
"""
Computes conditional mutual information between two time series x and y
conditioned on a third z (which can be multi-dimensional) as
I(x; y | z) = sum( p(x,y,z) * log( p(z)*p(x,y,z) / p(x,z)*p(y,z) ),
where p(z), p(x,z), p(y,z) and p(x,y,z) are probability distributions.
Performs k-nearest neighbours search using k-dimensional tree.
Uses sklearn.neighbors for KDTree class.
standardize - whether transform data to zero mean and unit variance
dualtree - whether to use dualtree formalism in k-d tree for the k-NN search
could lead to better performance with large N
According to Frenzel S. and Pompe B., Phys. Rev. Lett., 99, 2007.
"""
from sklearn.neighbors import KDTree
# prepare data
if standardize:
x = _center_ts(x)
y = _center_ts(y)
if isinstance(z, np.ndarray):
z = _center_ts(z)
elif isinstance(z, list):
for cond_ts in z:
cond_ts = _center_ts(cond_ts)
z = np.atleast_2d(z)
data = np.vstack([x, y, z]).T
# build k-d tree using the maximum (Chebyshev) norm
tree = KDTree(data, leaf_size = 15, metric = "chebyshev")
# find distance to k-nearest neighbour per point
dist, _ = tree.query(data, k = k + 1, return_distance = True, dualtree = dualtree)
sum_ = 0
# prepare marginal vectors xz, yz and z
n_x_z_data = np.delete(data, 1, axis = 1)
n_y_z_data = np.delete(data, 0, axis = 1)
n_z_data = np.delete(data, [0, 1], axis = 1)
# build and query k-d trees in marginal spaces for number of points in a given dist from a point
tree_x_z = KDTree(n_x_z_data, leaf_size = 15, metric = "chebyshev")
n_x_z = tree_x_z.query_radius(n_x_z_data, r = dist[:, -1], count_only = True) - 2
tree_y_z = KDTree(n_y_z_data, leaf_size = 15, metric = "chebyshev")
n_y_z = tree_y_z.query_radius(n_y_z_data, r = dist[:, -1], count_only = True) - 2
tree_z = KDTree(n_z_data, leaf_size = 15, metric = "chebyshev")
n_z = tree_z.query_radius(n_z_data, r = dist[:, -1], count_only = True) - 2
# count points
for n in range(data.shape[0]):
sum_ += _neg_harmonic(n_x_z[n]) + _neg_harmonic(n_y_z[n]) - _neg_harmonic(n_z[n])
sum_ /= data.shape[0]
return sum_ - _neg_harmonic(k-1)
|
mit
|
phdowling/scikit-learn
|
sklearn/neighbors/approximate.py
|
128
|
22351
|
"""Approximate nearest neighbor search"""
# Author: Maheshakya Wijewardena <[email protected]>
# Joel Nothman <[email protected]>
import numpy as np
import warnings
from scipy import sparse
from .base import KNeighborsMixin, RadiusNeighborsMixin
from ..base import BaseEstimator
from ..utils.validation import check_array
from ..utils import check_random_state
from ..metrics.pairwise import pairwise_distances
from ..random_projection import GaussianRandomProjection
__all__ = ["LSHForest"]
HASH_DTYPE = '>u4'
MAX_HASH_SIZE = np.dtype(HASH_DTYPE).itemsize * 8
def _find_matching_indices(tree, bin_X, left_mask, right_mask):
"""Finds indices in sorted array of integers.
Most significant h bits in the binary representations of the
integers are matched with the items' most significant h bits.
"""
left_index = np.searchsorted(tree, bin_X & left_mask)
right_index = np.searchsorted(tree, bin_X | right_mask,
side='right')
return left_index, right_index
def _find_longest_prefix_match(tree, bin_X, hash_size,
left_masks, right_masks):
"""Find the longest prefix match in tree for each query in bin_X
Most significant bits are considered as the prefix.
"""
hi = np.empty_like(bin_X, dtype=np.intp)
hi.fill(hash_size)
lo = np.zeros_like(bin_X, dtype=np.intp)
res = np.empty_like(bin_X, dtype=np.intp)
left_idx, right_idx = _find_matching_indices(tree, bin_X,
left_masks[hi],
right_masks[hi])
found = right_idx > left_idx
res[found] = lo[found] = hash_size
r = np.arange(bin_X.shape[0])
kept = r[lo < hi] # indices remaining in bin_X mask
while kept.shape[0]:
mid = (lo.take(kept) + hi.take(kept)) // 2
left_idx, right_idx = _find_matching_indices(tree,
bin_X.take(kept),
left_masks[mid],
right_masks[mid])
found = right_idx > left_idx
mid_found = mid[found]
lo[kept[found]] = mid_found + 1
res[kept[found]] = mid_found
hi[kept[~found]] = mid[~found]
kept = r[lo < hi]
return res
class ProjectionToHashMixin(object):
"""Turn a transformed real-valued array into a hash"""
@staticmethod
def _to_hash(projected):
if projected.shape[1] % 8 != 0:
raise ValueError('Require reduced dimensionality to be a multiple '
'of 8 for hashing')
# XXX: perhaps non-copying operation better
out = np.packbits((projected > 0).astype(int)).view(dtype=HASH_DTYPE)
return out.reshape(projected.shape[0], -1)
def fit_transform(self, X, y=None):
self.fit(X)
return self.transform(X)
def transform(self, X, y=None):
return self._to_hash(super(ProjectionToHashMixin, self).transform(X))
class GaussianRandomProjectionHash(ProjectionToHashMixin,
GaussianRandomProjection):
"""Use GaussianRandomProjection to produce a cosine LSH fingerprint"""
def __init__(self,
n_components=8,
random_state=None):
super(GaussianRandomProjectionHash, self).__init__(
n_components=n_components,
random_state=random_state)
def _array_of_arrays(list_of_arrays):
"""Creates an array of array from list of arrays."""
out = np.empty(len(list_of_arrays), dtype=object)
out[:] = list_of_arrays
return out
class LSHForest(BaseEstimator, KNeighborsMixin, RadiusNeighborsMixin):
"""Performs approximate nearest neighbor search using LSH forest.
LSH Forest: Locality Sensitive Hashing forest [1] is an alternative
method for vanilla approximate nearest neighbor search methods.
LSH forest data structure has been implemented using sorted
arrays and binary search and 32 bit fixed-length hashes.
Random projection is used as the hash family which approximates
cosine distance.
The cosine distance is defined as ``1 - cosine_similarity``: the lowest
value is 0 (identical point) but it is bounded above by 2 for the farthest
points. Its value does not depend on the norm of the vector points but
only on their relative angles.
Read more in the :ref:`User Guide <approximate_nearest_neighbors>`.
Parameters
----------
n_estimators : int (default = 10)
Number of trees in the LSH Forest.
min_hash_match : int (default = 4)
lowest hash length to be searched when candidate selection is
performed for nearest neighbors.
n_candidates : int (default = 10)
Minimum number of candidates evaluated per estimator, assuming enough
items meet the `min_hash_match` constraint.
n_neighbors : int (default = 5)
Number of neighbors to be returned from query function when
it is not provided to the :meth:`kneighbors` method.
radius : float, optinal (default = 1.0)
Radius from the data point to its neighbors. This is the parameter
space to use by default for the :meth`radius_neighbors` queries.
radius_cutoff_ratio : float, optional (default = 0.9)
A value ranges from 0 to 1. Radius neighbors will be searched until
the ratio between total neighbors within the radius and the total
candidates becomes less than this value unless it is terminated by
hash length reaching `min_hash_match`.
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`.
Attributes
----------
hash_functions_ : list of GaussianRandomProjectionHash objects
Hash function g(p,x) for a tree is an array of 32 randomly generated
float arrays with the same dimenstion as the data set. This array is
stored in GaussianRandomProjectionHash object and can be obtained
from ``components_`` attribute.
trees_ : array, shape (n_estimators, n_samples)
Each tree (corresponding to a hash function) contains an array of
sorted hashed values. The array representation may change in future
versions.
original_indices_ : array, shape (n_estimators, n_samples)
Original indices of sorted hashed values in the fitted index.
References
----------
.. [1] M. Bawa, T. Condie and P. Ganesan, "LSH Forest: Self-Tuning
Indexes for Similarity Search", WWW '05 Proceedings of the
14th international conference on World Wide Web, 651-660,
2005.
Examples
--------
>>> from sklearn.neighbors import LSHForest
>>> X_train = [[5, 5, 2], [21, 5, 5], [1, 1, 1], [8, 9, 1], [6, 10, 2]]
>>> X_test = [[9, 1, 6], [3, 1, 10], [7, 10, 3]]
>>> lshf = LSHForest()
>>> lshf.fit(X_train) # doctest: +NORMALIZE_WHITESPACE
LSHForest(min_hash_match=4, n_candidates=50, n_estimators=10,
n_neighbors=5, radius=1.0, radius_cutoff_ratio=0.9,
random_state=None)
>>> distances, indices = lshf.kneighbors(X_test, n_neighbors=2)
>>> distances # doctest: +ELLIPSIS
array([[ 0.069..., 0.149...],
[ 0.229..., 0.481...],
[ 0.004..., 0.014...]])
>>> indices
array([[1, 2],
[2, 0],
[4, 0]])
"""
def __init__(self, n_estimators=10, radius=1.0, n_candidates=50,
n_neighbors=5, min_hash_match=4, radius_cutoff_ratio=.9,
random_state=None):
self.n_estimators = n_estimators
self.radius = radius
self.random_state = random_state
self.n_candidates = n_candidates
self.n_neighbors = n_neighbors
self.min_hash_match = min_hash_match
self.radius_cutoff_ratio = radius_cutoff_ratio
def _compute_distances(self, query, candidates):
"""Computes the cosine distance.
Distance is from the query to points in the candidates array.
Returns argsort of distances in the candidates
array and sorted distances.
"""
if candidates.shape == (0,):
# needed since _fit_X[np.array([])] doesn't work if _fit_X sparse
return np.empty(0, dtype=np.int), np.empty(0, dtype=float)
if sparse.issparse(self._fit_X):
candidate_X = self._fit_X[candidates]
else:
candidate_X = self._fit_X.take(candidates, axis=0, mode='clip')
distances = pairwise_distances(query, candidate_X,
metric='cosine')[0]
distance_positions = np.argsort(distances)
distances = distances.take(distance_positions, mode='clip', axis=0)
return distance_positions, distances
def _generate_masks(self):
"""Creates left and right masks for all hash lengths."""
tri_size = MAX_HASH_SIZE + 1
# Called once on fitting, output is independent of hashes
left_mask = np.tril(np.ones((tri_size, tri_size), dtype=int))[:, 1:]
right_mask = left_mask[::-1, ::-1]
self._left_mask = np.packbits(left_mask).view(dtype=HASH_DTYPE)
self._right_mask = np.packbits(right_mask).view(dtype=HASH_DTYPE)
def _get_candidates(self, query, max_depth, bin_queries, n_neighbors):
"""Performs the Synchronous ascending phase.
Returns an array of candidates, their distance ranks and
distances.
"""
index_size = self._fit_X.shape[0]
# Number of candidates considered including duplicates
# XXX: not sure whether this is being calculated correctly wrt
# duplicates from different iterations through a single tree
n_candidates = 0
candidate_set = set()
min_candidates = self.n_candidates * self.n_estimators
while (max_depth > self.min_hash_match and
(n_candidates < min_candidates or
len(candidate_set) < n_neighbors)):
left_mask = self._left_mask[max_depth]
right_mask = self._right_mask[max_depth]
for i in range(self.n_estimators):
start, stop = _find_matching_indices(self.trees_[i],
bin_queries[i],
left_mask, right_mask)
n_candidates += stop - start
candidate_set.update(
self.original_indices_[i][start:stop].tolist())
max_depth -= 1
candidates = np.fromiter(candidate_set, count=len(candidate_set),
dtype=np.intp)
# For insufficient candidates, candidates are filled.
# Candidates are filled from unselected indices uniformly.
if candidates.shape[0] < n_neighbors:
warnings.warn(
"Number of candidates is not sufficient to retrieve"
" %i neighbors with"
" min_hash_match = %i. Candidates are filled up"
" uniformly from unselected"
" indices." % (n_neighbors, self.min_hash_match))
remaining = np.setdiff1d(np.arange(0, index_size), candidates)
to_fill = n_neighbors - candidates.shape[0]
candidates = np.concatenate((candidates, remaining[:to_fill]))
ranks, distances = self._compute_distances(query,
candidates.astype(int))
return (candidates[ranks[:n_neighbors]],
distances[:n_neighbors])
def _get_radius_neighbors(self, query, max_depth, bin_queries, radius):
"""Finds radius neighbors from the candidates obtained.
Their distances from query are smaller than radius.
Returns radius neighbors and distances.
"""
ratio_within_radius = 1
threshold = 1 - self.radius_cutoff_ratio
total_candidates = np.array([], dtype=int)
total_neighbors = np.array([], dtype=int)
total_distances = np.array([], dtype=float)
while (max_depth > self.min_hash_match and
ratio_within_radius > threshold):
left_mask = self._left_mask[max_depth]
right_mask = self._right_mask[max_depth]
candidates = []
for i in range(self.n_estimators):
start, stop = _find_matching_indices(self.trees_[i],
bin_queries[i],
left_mask, right_mask)
candidates.extend(
self.original_indices_[i][start:stop].tolist())
candidates = np.setdiff1d(candidates, total_candidates)
total_candidates = np.append(total_candidates, candidates)
ranks, distances = self._compute_distances(query, candidates)
m = np.searchsorted(distances, radius, side='right')
positions = np.searchsorted(total_distances, distances[:m])
total_neighbors = np.insert(total_neighbors, positions,
candidates[ranks[:m]])
total_distances = np.insert(total_distances, positions,
distances[:m])
ratio_within_radius = (total_neighbors.shape[0] /
float(total_candidates.shape[0]))
max_depth = max_depth - 1
return total_neighbors, total_distances
def fit(self, X, y=None):
"""Fit the LSH forest on the data.
This creates binary hashes of input data points by getting the
dot product of input points and hash_function then
transforming the projection into a binary string array based
on the sign (positive/negative) of the projection.
A sorted array of binary hashes is created.
Parameters
----------
X : array_like or sparse (CSR) matrix, shape (n_samples, n_features)
List of n_features-dimensional data points. Each row
corresponds to a single data point.
Returns
-------
self : object
Returns self.
"""
self._fit_X = check_array(X, accept_sparse='csr')
# Creates a g(p,x) for each tree
self.hash_functions_ = []
self.trees_ = []
self.original_indices_ = []
rng = check_random_state(self.random_state)
int_max = np.iinfo(np.int32).max
for i in range(self.n_estimators):
# This is g(p,x) for a particular tree.
# Builds a single tree. Hashing is done on an array of data points.
# `GaussianRandomProjection` is used for hashing.
# `n_components=hash size and n_features=n_dim.
hasher = GaussianRandomProjectionHash(MAX_HASH_SIZE,
rng.randint(0, int_max))
hashes = hasher.fit_transform(self._fit_X)[:, 0]
original_index = np.argsort(hashes)
bin_hashes = hashes[original_index]
self.original_indices_.append(original_index)
self.trees_.append(bin_hashes)
self.hash_functions_.append(hasher)
self._generate_masks()
return self
def _query(self, X):
"""Performs descending phase to find maximum depth."""
# Calculate hashes of shape (n_samples, n_estimators, [hash_size])
bin_queries = np.asarray([hasher.transform(X)[:, 0]
for hasher in self.hash_functions_])
bin_queries = np.rollaxis(bin_queries, 1)
# descend phase
depths = [_find_longest_prefix_match(tree, tree_queries, MAX_HASH_SIZE,
self._left_mask, self._right_mask)
for tree, tree_queries in zip(self.trees_,
np.rollaxis(bin_queries, 1))]
return bin_queries, np.max(depths, axis=0)
def kneighbors(self, X, n_neighbors=None, return_distance=True):
"""Returns n_neighbors of approximate nearest neighbors.
Parameters
----------
X : array_like or sparse (CSR) matrix, shape (n_samples, n_features)
List of n_features-dimensional data points. Each row
corresponds to a single query.
n_neighbors : int, opitonal (default = None)
Number of neighbors required. If not provided, this will
return the number specified at the initialization.
return_distance : boolean, optional (default = False)
Returns the distances of neighbors if set to True.
Returns
-------
dist : array, shape (n_samples, n_neighbors)
Array representing the cosine distances to each point,
only present if return_distance=True.
ind : array, shape (n_samples, n_neighbors)
Indices of the approximate nearest points in the population
matrix.
"""
if not hasattr(self, 'hash_functions_'):
raise ValueError("estimator should be fitted.")
if n_neighbors is None:
n_neighbors = self.n_neighbors
X = check_array(X, accept_sparse='csr')
neighbors, distances = [], []
bin_queries, max_depth = self._query(X)
for i in range(X.shape[0]):
neighs, dists = self._get_candidates(X[i], max_depth[i],
bin_queries[i],
n_neighbors)
neighbors.append(neighs)
distances.append(dists)
if return_distance:
return np.array(distances), np.array(neighbors)
else:
return np.array(neighbors)
def radius_neighbors(self, X, radius=None, return_distance=True):
"""Finds the neighbors within a given radius of a point or points.
Return the indices and distances of some points from the dataset
lying in a ball with size ``radius`` around the points of the query
array. Points lying on the boundary are included in the results.
The result points are *not* necessarily sorted by distance to their
query point.
LSH Forest being an approximate method, some true neighbors from the
indexed dataset might be missing from the results.
Parameters
----------
X : array_like or sparse (CSR) matrix, shape (n_samples, n_features)
List of n_features-dimensional data points. Each row
corresponds to a single query.
radius : float
Limiting distance of neighbors to return.
(default is the value passed to the constructor).
return_distance : boolean, optional (default = False)
Returns the distances of neighbors if set to True.
Returns
-------
dist : array, shape (n_samples,) of arrays
Each element is an array representing the cosine distances
to some points found within ``radius`` of the respective query.
Only present if ``return_distance=True``.
ind : array, shape (n_samples,) of arrays
Each element is an array of indices for neighbors within ``radius``
of the respective query.
"""
if not hasattr(self, 'hash_functions_'):
raise ValueError("estimator should be fitted.")
if radius is None:
radius = self.radius
X = check_array(X, accept_sparse='csr')
neighbors, distances = [], []
bin_queries, max_depth = self._query(X)
for i in range(X.shape[0]):
neighs, dists = self._get_radius_neighbors(X[i], max_depth[i],
bin_queries[i], radius)
neighbors.append(neighs)
distances.append(dists)
if return_distance:
return _array_of_arrays(distances), _array_of_arrays(neighbors)
else:
return _array_of_arrays(neighbors)
def partial_fit(self, X, y=None):
"""
Inserts new data into the already fitted LSH Forest.
Cost is proportional to new total size, so additions
should be batched.
Parameters
----------
X : array_like or sparse (CSR) matrix, shape (n_samples, n_features)
New data point to be inserted into the LSH Forest.
"""
X = check_array(X, accept_sparse='csr')
if not hasattr(self, 'hash_functions_'):
return self.fit(X)
if X.shape[1] != self._fit_X.shape[1]:
raise ValueError("Number of features in X and"
" fitted array does not match.")
n_samples = X.shape[0]
n_indexed = self._fit_X.shape[0]
for i in range(self.n_estimators):
bin_X = self.hash_functions_[i].transform(X)[:, 0]
# gets the position to be added in the tree.
positions = self.trees_[i].searchsorted(bin_X)
# adds the hashed value into the tree.
self.trees_[i] = np.insert(self.trees_[i],
positions, bin_X)
# add the entry into the original_indices_.
self.original_indices_[i] = np.insert(self.original_indices_[i],
positions,
np.arange(n_indexed,
n_indexed +
n_samples))
# adds the entry into the input_array.
if sparse.issparse(X) or sparse.issparse(self._fit_X):
self._fit_X = sparse.vstack((self._fit_X, X))
else:
self._fit_X = np.row_stack((self._fit_X, X))
return self
|
bsd-3-clause
|
plissonf/scikit-learn
|
sklearn/datasets/tests/test_mldata.py
|
384
|
5221
|
"""Test functionality of mldata fetching utilities."""
import os
import shutil
import tempfile
import scipy as sp
from sklearn import datasets
from sklearn.datasets import mldata_filename, fetch_mldata
from sklearn.utils.testing import assert_in
from sklearn.utils.testing import assert_not_in
from sklearn.utils.testing import mock_mldata_urlopen
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_raises
from sklearn.utils.testing import with_setup
from sklearn.utils.testing import assert_array_equal
tmpdir = None
def setup_tmpdata():
# create temporary dir
global tmpdir
tmpdir = tempfile.mkdtemp()
os.makedirs(os.path.join(tmpdir, 'mldata'))
def teardown_tmpdata():
# remove temporary dir
if tmpdir is not None:
shutil.rmtree(tmpdir)
def test_mldata_filename():
cases = [('datasets-UCI iris', 'datasets-uci-iris'),
('news20.binary', 'news20binary'),
('book-crossing-ratings-1.0', 'book-crossing-ratings-10'),
('Nile Water Level', 'nile-water-level'),
('MNIST (original)', 'mnist-original')]
for name, desired in cases:
assert_equal(mldata_filename(name), desired)
@with_setup(setup_tmpdata, teardown_tmpdata)
def test_download():
"""Test that fetch_mldata is able to download and cache a data set."""
_urlopen_ref = datasets.mldata.urlopen
datasets.mldata.urlopen = mock_mldata_urlopen({
'mock': {
'label': sp.ones((150,)),
'data': sp.ones((150, 4)),
},
})
try:
mock = fetch_mldata('mock', data_home=tmpdir)
for n in ["COL_NAMES", "DESCR", "target", "data"]:
assert_in(n, mock)
assert_equal(mock.target.shape, (150,))
assert_equal(mock.data.shape, (150, 4))
assert_raises(datasets.mldata.HTTPError,
fetch_mldata, 'not_existing_name')
finally:
datasets.mldata.urlopen = _urlopen_ref
@with_setup(setup_tmpdata, teardown_tmpdata)
def test_fetch_one_column():
_urlopen_ref = datasets.mldata.urlopen
try:
dataname = 'onecol'
# create fake data set in cache
x = sp.arange(6).reshape(2, 3)
datasets.mldata.urlopen = mock_mldata_urlopen({dataname: {'x': x}})
dset = fetch_mldata(dataname, data_home=tmpdir)
for n in ["COL_NAMES", "DESCR", "data"]:
assert_in(n, dset)
assert_not_in("target", dset)
assert_equal(dset.data.shape, (2, 3))
assert_array_equal(dset.data, x)
# transposing the data array
dset = fetch_mldata(dataname, transpose_data=False, data_home=tmpdir)
assert_equal(dset.data.shape, (3, 2))
finally:
datasets.mldata.urlopen = _urlopen_ref
@with_setup(setup_tmpdata, teardown_tmpdata)
def test_fetch_multiple_column():
_urlopen_ref = datasets.mldata.urlopen
try:
# create fake data set in cache
x = sp.arange(6).reshape(2, 3)
y = sp.array([1, -1])
z = sp.arange(12).reshape(4, 3)
# by default
dataname = 'threecol-default'
datasets.mldata.urlopen = mock_mldata_urlopen({
dataname: (
{
'label': y,
'data': x,
'z': z,
},
['z', 'data', 'label'],
),
})
dset = fetch_mldata(dataname, data_home=tmpdir)
for n in ["COL_NAMES", "DESCR", "target", "data", "z"]:
assert_in(n, dset)
assert_not_in("x", dset)
assert_not_in("y", dset)
assert_array_equal(dset.data, x)
assert_array_equal(dset.target, y)
assert_array_equal(dset.z, z.T)
# by order
dataname = 'threecol-order'
datasets.mldata.urlopen = mock_mldata_urlopen({
dataname: ({'y': y, 'x': x, 'z': z},
['y', 'x', 'z']), })
dset = fetch_mldata(dataname, data_home=tmpdir)
for n in ["COL_NAMES", "DESCR", "target", "data", "z"]:
assert_in(n, dset)
assert_not_in("x", dset)
assert_not_in("y", dset)
assert_array_equal(dset.data, x)
assert_array_equal(dset.target, y)
assert_array_equal(dset.z, z.T)
# by number
dataname = 'threecol-number'
datasets.mldata.urlopen = mock_mldata_urlopen({
dataname: ({'y': y, 'x': x, 'z': z},
['z', 'x', 'y']),
})
dset = fetch_mldata(dataname, target_name=2, data_name=0,
data_home=tmpdir)
for n in ["COL_NAMES", "DESCR", "target", "data", "x"]:
assert_in(n, dset)
assert_not_in("y", dset)
assert_not_in("z", dset)
assert_array_equal(dset.data, z)
assert_array_equal(dset.target, y)
# by name
dset = fetch_mldata(dataname, target_name='y', data_name='z',
data_home=tmpdir)
for n in ["COL_NAMES", "DESCR", "target", "data", "x"]:
assert_in(n, dset)
assert_not_in("y", dset)
assert_not_in("z", dset)
finally:
datasets.mldata.urlopen = _urlopen_ref
|
bsd-3-clause
|
pombreda/nmrglue
|
examples/plotting/2d_spectrum/plot_spectrum_pts.py
|
10
|
1340
|
#! /usr/bin/env python
# Create contour plots of a 2D NMRPipe spectrum
import nmrglue as ng
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm
# plot parameters
cmap = matplotlib.cm.Blues_r # contour map (colors to use for contours)
contour_start = 30000 # contour level start value
contour_num = 20 # number of contour levels
contour_factor = 1.20 # scaling factor between contour levels
# calculate contour levels
cl = [contour_start*contour_factor**x for x in xrange(contour_num)]
# read in the data from a NMRPipe file
dic,data = ng.pipe.read("../../common_data/2d_pipe/test.ft2")
# create the figure
fig = plt.figure()
ax = fig.add_subplot(111)
# plot the contours
ax.contour(data,cl,cmap=cmap,extent=(0,data.shape[1]-1,0,data.shape[0]-1))
# add some labels
ax.text(2006,1322,"T49",size=8,color='r')
ax.text(2010,1290,"T11",size=8,color='k')
# plot slices in each direction
xslice = data[1187,:]
ax.plot(xrange(data.shape[1]),xslice/3.e3+1187)
yslice = data[:,1976]
ax.plot(-yslice/3.e3+1976,xrange(data.shape[0]))
# decorate the axes
ax.set_ylabel("15N (points)")
ax.set_xlabel("13C (points)")
ax.set_title("Protein 2D NCa Spectrum")
ax.set_xlim(1900,2200)
ax.set_ylim(750,1400)
# save the figure
fig.savefig("spectrum_pts.png") #change to .pdf, .ps, etc for different formats
|
bsd-3-clause
|
rednaxelafx/apache-spark
|
python/pyspark/sql/pandas/group_ops.py
|
2
|
14199
|
#
# 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.
#
import sys
import warnings
from pyspark import since
from pyspark.rdd import PythonEvalType
from pyspark.sql.column import Column
from pyspark.sql.dataframe import DataFrame
class PandasGroupedOpsMixin(object):
"""
Min-in for pandas grouped operations. Currently, only :class:`GroupedData`
can use this class.
"""
@since(2.3)
def apply(self, udf):
"""
It is an alias of :meth:`pyspark.sql.GroupedData.applyInPandas`; however, it takes a
:meth:`pyspark.sql.functions.pandas_udf` whereas
:meth:`pyspark.sql.GroupedData.applyInPandas` takes a Python native function.
.. note:: It is preferred to use :meth:`pyspark.sql.GroupedData.applyInPandas` over this
API. This API will be deprecated in the future releases.
:param udf: a grouped map user-defined function returned by
:func:`pyspark.sql.functions.pandas_udf`.
>>> from pyspark.sql.functions import pandas_udf, PandasUDFType
>>> df = spark.createDataFrame(
... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],
... ("id", "v"))
>>> @pandas_udf("id long, v double", PandasUDFType.GROUPED_MAP) # doctest: +SKIP
... def normalize(pdf):
... v = pdf.v
... return pdf.assign(v=(v - v.mean()) / v.std())
>>> df.groupby("id").apply(normalize).show() # doctest: +SKIP
+---+-------------------+
| id| v|
+---+-------------------+
| 1|-0.7071067811865475|
| 1| 0.7071067811865475|
| 2|-0.8320502943378437|
| 2|-0.2773500981126146|
| 2| 1.1094003924504583|
+---+-------------------+
.. seealso:: :meth:`pyspark.sql.functions.pandas_udf`
"""
# Columns are special because hasattr always return True
if isinstance(udf, Column) or not hasattr(udf, 'func') \
or udf.evalType != PythonEvalType.SQL_GROUPED_MAP_PANDAS_UDF:
raise ValueError("Invalid udf: the udf argument must be a pandas_udf of type "
"GROUPED_MAP.")
warnings.warn(
"It is preferred to use 'applyInPandas' over this "
"API. This API will be deprecated in the future releases. See SPARK-28264 for "
"more details.", UserWarning)
return self.applyInPandas(udf.func, schema=udf.returnType)
@since(3.0)
def applyInPandas(self, func, schema):
"""
Maps each group of the current :class:`DataFrame` using a pandas udf and returns the result
as a `DataFrame`.
The function should take a `pandas.DataFrame` and return another
`pandas.DataFrame`. For each group, all columns are passed together as a `pandas.DataFrame`
to the user-function and the returned `pandas.DataFrame` are combined as a
:class:`DataFrame`.
The `schema` should be a :class:`StructType` describing the schema of the returned
`pandas.DataFrame`. The column labels of the returned `pandas.DataFrame` must either match
the field names in the defined schema if specified as strings, or match the
field data types by position if not strings, e.g. integer indices.
The length of the returned `pandas.DataFrame` can be arbitrary.
:param func: a Python native function that takes a `pandas.DataFrame`, and outputs a
`pandas.DataFrame`.
:param schema: the return type of the `func` in PySpark. The value can be either a
:class:`pyspark.sql.types.DataType` object or a DDL-formatted type string.
>>> import pandas as pd # doctest: +SKIP
>>> from pyspark.sql.functions import pandas_udf, ceil
>>> df = spark.createDataFrame(
... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],
... ("id", "v")) # doctest: +SKIP
>>> def normalize(pdf):
... v = pdf.v
... return pdf.assign(v=(v - v.mean()) / v.std())
>>> df.groupby("id").applyInPandas(
... normalize, schema="id long, v double").show() # doctest: +SKIP
+---+-------------------+
| id| v|
+---+-------------------+
| 1|-0.7071067811865475|
| 1| 0.7071067811865475|
| 2|-0.8320502943378437|
| 2|-0.2773500981126146|
| 2| 1.1094003924504583|
+---+-------------------+
Alternatively, the user can pass a function that takes two arguments.
In this case, the grouping key(s) will be passed as the first argument and the data will
be passed as the second argument. The grouping key(s) will be passed as a tuple of numpy
data types, e.g., `numpy.int32` and `numpy.float64`. The data will still be passed in
as a `pandas.DataFrame` containing all columns from the original Spark DataFrame.
This is useful when the user does not want to hardcode grouping key(s) in the function.
>>> df = spark.createDataFrame(
... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],
... ("id", "v")) # doctest: +SKIP
>>> def mean_func(key, pdf):
... # key is a tuple of one numpy.int64, which is the value
... # of 'id' for the current group
... return pd.DataFrame([key + (pdf.v.mean(),)])
>>> df.groupby('id').applyInPandas(
... mean_func, schema="id long, v double").show() # doctest: +SKIP
+---+---+
| id| v|
+---+---+
| 1|1.5|
| 2|6.0|
+---+---+
>>> def sum_func(key, pdf):
... # key is a tuple of two numpy.int64s, which is the values
... # of 'id' and 'ceil(df.v / 2)' for the current group
... return pd.DataFrame([key + (pdf.v.sum(),)])
>>> df.groupby(df.id, ceil(df.v / 2)).applyInPandas(
... sum_func, schema="id long, `ceil(v / 2)` long, v double").show() # doctest: +SKIP
+---+-----------+----+
| id|ceil(v / 2)| v|
+---+-----------+----+
| 2| 5|10.0|
| 1| 1| 3.0|
| 2| 3| 5.0|
| 2| 2| 3.0|
+---+-----------+----+
.. note:: This function requires a full shuffle. All the data of a group will be loaded
into memory, so the user should be aware of the potential OOM risk if data is skewed
and certain groups are too large to fit in memory.
.. note:: If returning a new `pandas.DataFrame` constructed with a dictionary, it is
recommended to explicitly index the columns by name to ensure the positions are correct,
or alternatively use an `OrderedDict`.
For example, `pd.DataFrame({'id': ids, 'a': data}, columns=['id', 'a'])` or
`pd.DataFrame(OrderedDict([('id', ids), ('a', data)]))`.
.. note:: Experimental
.. seealso:: :meth:`pyspark.sql.functions.pandas_udf`
"""
from pyspark.sql import GroupedData
from pyspark.sql.functions import pandas_udf, PandasUDFType
assert isinstance(self, GroupedData)
udf = pandas_udf(
func, returnType=schema, functionType=PandasUDFType.GROUPED_MAP)
df = self._df
udf_column = udf(*[df[col] for col in df.columns])
jdf = self._jgd.flatMapGroupsInPandas(udf_column._jc.expr())
return DataFrame(jdf, self.sql_ctx)
@since(3.0)
def cogroup(self, other):
"""
Cogroups this group with another group so that we can run cogrouped operations.
See :class:`PandasCogroupedOps` for the operations that can be run.
"""
from pyspark.sql import GroupedData
assert isinstance(self, GroupedData)
return PandasCogroupedOps(self, other)
class PandasCogroupedOps(object):
"""
A logical grouping of two :class:`GroupedData`,
created by :func:`GroupedData.cogroup`.
.. note:: Experimental
.. versionadded:: 3.0
"""
def __init__(self, gd1, gd2):
self._gd1 = gd1
self._gd2 = gd2
self.sql_ctx = gd1.sql_ctx
@since(3.0)
def applyInPandas(self, func, schema):
"""
Applies a function to each cogroup using pandas and returns the result
as a `DataFrame`.
The function should take two `pandas.DataFrame`\\s and return another
`pandas.DataFrame`. For each side of the cogroup, all columns are passed together as a
`pandas.DataFrame` to the user-function and the returned `pandas.DataFrame` are combined as
a :class:`DataFrame`.
The `schema` should be a :class:`StructType` describing the schema of the returned
`pandas.DataFrame`. The column labels of the returned `pandas.DataFrame` must either match
the field names in the defined schema if specified as strings, or match the
field data types by position if not strings, e.g. integer indices.
The length of the returned `pandas.DataFrame` can be arbitrary.
:param func: a Python native function that takes two `pandas.DataFrame`\\s, and
outputs a `pandas.DataFrame`, or that takes one tuple (grouping keys) and two
pandas ``DataFrame``\\s, and outputs a pandas ``DataFrame``.
:param schema: the return type of the `func` in PySpark. The value can be either a
:class:`pyspark.sql.types.DataType` object or a DDL-formatted type string.
>>> from pyspark.sql.functions import pandas_udf
>>> df1 = spark.createDataFrame(
... [(20000101, 1, 1.0), (20000101, 2, 2.0), (20000102, 1, 3.0), (20000102, 2, 4.0)],
... ("time", "id", "v1"))
>>> df2 = spark.createDataFrame(
... [(20000101, 1, "x"), (20000101, 2, "y")],
... ("time", "id", "v2"))
>>> def asof_join(l, r):
... return pd.merge_asof(l, r, on="time", by="id")
>>> df1.groupby("id").cogroup(df2.groupby("id")).applyInPandas(
... asof_join, schema="time int, id int, v1 double, v2 string"
... ).show() # doctest: +SKIP
+--------+---+---+---+
| time| id| v1| v2|
+--------+---+---+---+
|20000101| 1|1.0| x|
|20000102| 1|3.0| x|
|20000101| 2|2.0| y|
|20000102| 2|4.0| y|
+--------+---+---+---+
Alternatively, the user can define a function that takes three arguments. In this case,
the grouping key(s) will be passed as the first argument and the data will be passed as the
second and third arguments. The grouping key(s) will be passed as a tuple of numpy data
types, e.g., `numpy.int32` and `numpy.float64`. The data will still be passed in as two
`pandas.DataFrame` containing all columns from the original Spark DataFrames.
>>> def asof_join(k, l, r):
... if k == (1,):
... return pd.merge_asof(l, r, on="time", by="id")
... else:
... return pd.DataFrame(columns=['time', 'id', 'v1', 'v2'])
>>> df1.groupby("id").cogroup(df2.groupby("id")).applyInPandas(
... asof_join, "time int, id int, v1 double, v2 string").show() # doctest: +SKIP
+--------+---+---+---+
| time| id| v1| v2|
+--------+---+---+---+
|20000101| 1|1.0| x|
|20000102| 1|3.0| x|
+--------+---+---+---+
.. note:: This function requires a full shuffle. All the data of a cogroup will be loaded
into memory, so the user should be aware of the potential OOM risk if data is skewed
and certain groups are too large to fit in memory.
.. note:: If returning a new `pandas.DataFrame` constructed with a dictionary, it is
recommended to explicitly index the columns by name to ensure the positions are correct,
or alternatively use an `OrderedDict`.
For example, `pd.DataFrame({'id': ids, 'a': data}, columns=['id', 'a'])` or
`pd.DataFrame(OrderedDict([('id', ids), ('a', data)]))`.
.. note:: Experimental
.. seealso:: :meth:`pyspark.sql.functions.pandas_udf`
"""
from pyspark.sql.pandas.functions import pandas_udf
udf = pandas_udf(
func, returnType=schema, functionType=PythonEvalType.SQL_COGROUPED_MAP_PANDAS_UDF)
all_cols = self._extract_cols(self._gd1) + self._extract_cols(self._gd2)
udf_column = udf(*all_cols)
jdf = self._gd1._jgd.flatMapCoGroupsInPandas(self._gd2._jgd, udf_column._jc.expr())
return DataFrame(jdf, self.sql_ctx)
@staticmethod
def _extract_cols(gd):
df = gd._df
return [df[col] for col in df.columns]
def _test():
import doctest
from pyspark.sql import SparkSession
import pyspark.sql.pandas.group_ops
globs = pyspark.sql.pandas.group_ops.__dict__.copy()
spark = SparkSession.builder\
.master("local[4]")\
.appName("sql.pandas.group tests")\
.getOrCreate()
globs['spark'] = spark
(failure_count, test_count) = doctest.testmod(
pyspark.sql.pandas.group_ops, globs=globs,
optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE | doctest.REPORT_NDIFF)
spark.stop()
if failure_count:
sys.exit(-1)
if __name__ == "__main__":
_test()
|
apache-2.0
|
jaidevd/scikit-learn
|
sklearn/model_selection/tests/test_validation.py
|
2
|
41903
|
"""Test the validation module"""
from __future__ import division
import sys
import warnings
import tempfile
import os
from time import sleep
import numpy as np
from scipy.sparse import coo_matrix, csr_matrix
from sklearn.utils.testing import assert_true
from sklearn.utils.testing import assert_false
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_almost_equal
from sklearn.utils.testing import assert_raises
from sklearn.utils.testing import assert_raise_message
from sklearn.utils.testing import assert_greater
from sklearn.utils.testing import assert_less
from sklearn.utils.testing import assert_array_almost_equal
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_warns
from sklearn.utils.mocking import CheckingClassifier, MockDataFrame
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import cross_val_predict
from sklearn.model_selection import permutation_test_score
from sklearn.model_selection import KFold
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import LeaveOneOut
from sklearn.model_selection import LeaveOneGroupOut
from sklearn.model_selection import LeavePGroupsOut
from sklearn.model_selection import GroupKFold
from sklearn.model_selection import GroupShuffleSplit
from sklearn.model_selection import learning_curve
from sklearn.model_selection import validation_curve
from sklearn.model_selection._validation import _check_is_permutation
from sklearn.datasets import make_regression
from sklearn.datasets import load_boston
from sklearn.datasets import load_iris
from sklearn.metrics import explained_variance_score
from sklearn.metrics import make_scorer
from sklearn.metrics import precision_score
from sklearn.linear_model import Ridge, LogisticRegression
from sklearn.linear_model import PassiveAggressiveClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.cluster import KMeans
from sklearn.preprocessing import Imputer
from sklearn.preprocessing import LabelEncoder
from sklearn.pipeline import Pipeline
from sklearn.externals.six.moves import cStringIO as StringIO
from sklearn.base import BaseEstimator
from sklearn.multiclass import OneVsRestClassifier
from sklearn.utils import shuffle
from sklearn.datasets import make_classification
from sklearn.datasets import make_multilabel_classification
from sklearn.model_selection.tests.common import OneTimeSplitter
try:
WindowsError
except NameError:
WindowsError = None
class MockImprovingEstimator(BaseEstimator):
"""Dummy classifier to test the learning curve"""
def __init__(self, n_max_train_sizes):
self.n_max_train_sizes = n_max_train_sizes
self.train_sizes = 0
self.X_subset = None
def fit(self, X_subset, y_subset=None):
self.X_subset = X_subset
self.train_sizes = X_subset.shape[0]
return self
def predict(self, X):
raise NotImplementedError
def score(self, X=None, Y=None):
# training score becomes worse (2 -> 1), test error better (0 -> 1)
if self._is_training_data(X):
return 2. - float(self.train_sizes) / self.n_max_train_sizes
else:
return float(self.train_sizes) / self.n_max_train_sizes
def _is_training_data(self, X):
return X is self.X_subset
class MockIncrementalImprovingEstimator(MockImprovingEstimator):
"""Dummy classifier that provides partial_fit"""
def __init__(self, n_max_train_sizes):
super(MockIncrementalImprovingEstimator,
self).__init__(n_max_train_sizes)
self.x = None
def _is_training_data(self, X):
return self.x in X
def partial_fit(self, X, y=None, **params):
self.train_sizes += X.shape[0]
self.x = X[0]
class MockEstimatorWithParameter(BaseEstimator):
"""Dummy classifier to test the validation curve"""
def __init__(self, param=0.5):
self.X_subset = None
self.param = param
def fit(self, X_subset, y_subset):
self.X_subset = X_subset
self.train_sizes = X_subset.shape[0]
return self
def predict(self, X):
raise NotImplementedError
def score(self, X=None, y=None):
return self.param if self._is_training_data(X) else 1 - self.param
def _is_training_data(self, X):
return X is self.X_subset
class MockClassifier(object):
"""Dummy classifier to test the cross-validation"""
def __init__(self, a=0, allow_nd=False):
self.a = a
self.allow_nd = allow_nd
def fit(self, X, Y=None, sample_weight=None, class_prior=None,
sparse_sample_weight=None, sparse_param=None, dummy_int=None,
dummy_str=None, dummy_obj=None, callback=None):
"""The dummy arguments are to test that this fit function can
accept non-array arguments through cross-validation, such as:
- int
- str (this is actually array-like)
- object
- function
"""
self.dummy_int = dummy_int
self.dummy_str = dummy_str
self.dummy_obj = dummy_obj
if callback is not None:
callback(self)
if self.allow_nd:
X = X.reshape(len(X), -1)
if X.ndim >= 3 and not self.allow_nd:
raise ValueError('X cannot be d')
if sample_weight is not None:
assert_true(sample_weight.shape[0] == X.shape[0],
'MockClassifier extra fit_param sample_weight.shape[0]'
' is {0}, should be {1}'.format(sample_weight.shape[0],
X.shape[0]))
if class_prior is not None:
assert_true(class_prior.shape[0] == len(np.unique(y)),
'MockClassifier extra fit_param class_prior.shape[0]'
' is {0}, should be {1}'.format(class_prior.shape[0],
len(np.unique(y))))
if sparse_sample_weight is not None:
fmt = ('MockClassifier extra fit_param sparse_sample_weight'
'.shape[0] is {0}, should be {1}')
assert_true(sparse_sample_weight.shape[0] == X.shape[0],
fmt.format(sparse_sample_weight.shape[0], X.shape[0]))
if sparse_param is not None:
fmt = ('MockClassifier extra fit_param sparse_param.shape '
'is ({0}, {1}), should be ({2}, {3})')
assert_true(sparse_param.shape == P_sparse.shape,
fmt.format(sparse_param.shape[0],
sparse_param.shape[1],
P_sparse.shape[0], P_sparse.shape[1]))
return self
def predict(self, T):
if self.allow_nd:
T = T.reshape(len(T), -1)
return T[:, 0]
def score(self, X=None, Y=None):
return 1. / (1 + np.abs(self.a))
def get_params(self, deep=False):
return {'a': self.a, 'allow_nd': self.allow_nd}
# XXX: use 2D array, since 1D X is being detected as a single sample in
# check_consistent_length
X = np.ones((10, 2))
X_sparse = coo_matrix(X)
y = np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4])
# The number of samples per class needs to be > n_splits,
# for StratifiedKFold(n_splits=3)
y2 = np.array([1, 1, 1, 2, 2, 2, 3, 3, 3, 3])
P_sparse = coo_matrix(np.eye(5))
def test_cross_val_score():
clf = MockClassifier()
for a in range(-10, 10):
clf.a = a
# Smoke test
scores = cross_val_score(clf, X, y2)
assert_array_equal(scores, clf.score(X, y2))
# test with multioutput y
multioutput_y = np.column_stack([y2, y2[::-1]])
scores = cross_val_score(clf, X_sparse, multioutput_y)
assert_array_equal(scores, clf.score(X_sparse, multioutput_y))
scores = cross_val_score(clf, X_sparse, y2)
assert_array_equal(scores, clf.score(X_sparse, y2))
# test with multioutput y
scores = cross_val_score(clf, X_sparse, multioutput_y)
assert_array_equal(scores, clf.score(X_sparse, multioutput_y))
# test with X and y as list
list_check = lambda x: isinstance(x, list)
clf = CheckingClassifier(check_X=list_check)
scores = cross_val_score(clf, X.tolist(), y2.tolist())
clf = CheckingClassifier(check_y=list_check)
scores = cross_val_score(clf, X, y2.tolist())
assert_raises(ValueError, cross_val_score, clf, X, y2, scoring="sklearn")
# test with 3d X and
X_3d = X[:, :, np.newaxis]
clf = MockClassifier(allow_nd=True)
scores = cross_val_score(clf, X_3d, y2)
clf = MockClassifier(allow_nd=False)
assert_raises(ValueError, cross_val_score, clf, X_3d, y2)
def test_cross_val_score_predict_groups():
# Check if ValueError (when groups is None) propagates to cross_val_score
# and cross_val_predict
# And also check if groups is correctly passed to the cv object
X, y = make_classification(n_samples=20, n_classes=2, random_state=0)
clf = SVC(kernel="linear")
group_cvs = [LeaveOneGroupOut(), LeavePGroupsOut(2), GroupKFold(),
GroupShuffleSplit()]
for cv in group_cvs:
assert_raise_message(ValueError,
"The groups parameter should not be None",
cross_val_score, estimator=clf, X=X, y=y, cv=cv)
assert_raise_message(ValueError,
"The groups parameter should not be None",
cross_val_predict, estimator=clf, X=X, y=y, cv=cv)
def test_cross_val_score_pandas():
# check cross_val_score doesn't destroy pandas dataframe
types = [(MockDataFrame, MockDataFrame)]
try:
from pandas import Series, DataFrame
types.append((Series, DataFrame))
except ImportError:
pass
for TargetType, InputFeatureType in types:
# X dataframe, y series
# 3 fold cross val is used so we need atleast 3 samples per class
X_df, y_ser = InputFeatureType(X), TargetType(y2)
check_df = lambda x: isinstance(x, InputFeatureType)
check_series = lambda x: isinstance(x, TargetType)
clf = CheckingClassifier(check_X=check_df, check_y=check_series)
cross_val_score(clf, X_df, y_ser)
def test_cross_val_score_mask():
# test that cross_val_score works with boolean masks
svm = SVC(kernel="linear")
iris = load_iris()
X, y = iris.data, iris.target
kfold = KFold(5)
scores_indices = cross_val_score(svm, X, y, cv=kfold)
kfold = KFold(5)
cv_masks = []
for train, test in kfold.split(X, y):
mask_train = np.zeros(len(y), dtype=np.bool)
mask_test = np.zeros(len(y), dtype=np.bool)
mask_train[train] = 1
mask_test[test] = 1
cv_masks.append((train, test))
scores_masks = cross_val_score(svm, X, y, cv=cv_masks)
assert_array_equal(scores_indices, scores_masks)
def test_cross_val_score_precomputed():
# test for svm with precomputed kernel
svm = SVC(kernel="precomputed")
iris = load_iris()
X, y = iris.data, iris.target
linear_kernel = np.dot(X, X.T)
score_precomputed = cross_val_score(svm, linear_kernel, y)
svm = SVC(kernel="linear")
score_linear = cross_val_score(svm, X, y)
assert_array_almost_equal(score_precomputed, score_linear)
# test with callable
svm = SVC(kernel=lambda x, y: np.dot(x, y.T))
score_callable = cross_val_score(svm, X, y)
assert_array_almost_equal(score_precomputed, score_callable)
# Error raised for non-square X
svm = SVC(kernel="precomputed")
assert_raises(ValueError, cross_val_score, svm, X, y)
# test error is raised when the precomputed kernel is not array-like
# or sparse
assert_raises(ValueError, cross_val_score, svm,
linear_kernel.tolist(), y)
def test_cross_val_score_fit_params():
clf = MockClassifier()
n_samples = X.shape[0]
n_classes = len(np.unique(y))
W_sparse = coo_matrix((np.array([1]), (np.array([1]), np.array([0]))),
shape=(10, 1))
P_sparse = coo_matrix(np.eye(5))
DUMMY_INT = 42
DUMMY_STR = '42'
DUMMY_OBJ = object()
def assert_fit_params(clf):
# Function to test that the values are passed correctly to the
# classifier arguments for non-array type
assert_equal(clf.dummy_int, DUMMY_INT)
assert_equal(clf.dummy_str, DUMMY_STR)
assert_equal(clf.dummy_obj, DUMMY_OBJ)
fit_params = {'sample_weight': np.ones(n_samples),
'class_prior': np.ones(n_classes) / n_classes,
'sparse_sample_weight': W_sparse,
'sparse_param': P_sparse,
'dummy_int': DUMMY_INT,
'dummy_str': DUMMY_STR,
'dummy_obj': DUMMY_OBJ,
'callback': assert_fit_params}
cross_val_score(clf, X, y, fit_params=fit_params)
def test_cross_val_score_score_func():
clf = MockClassifier()
_score_func_args = []
def score_func(y_test, y_predict):
_score_func_args.append((y_test, y_predict))
return 1.0
with warnings.catch_warnings(record=True):
scoring = make_scorer(score_func)
score = cross_val_score(clf, X, y, scoring=scoring)
assert_array_equal(score, [1.0, 1.0, 1.0])
assert len(_score_func_args) == 3
def test_cross_val_score_errors():
class BrokenEstimator:
pass
assert_raises(TypeError, cross_val_score, BrokenEstimator(), X)
def test_cross_val_score_with_score_func_classification():
iris = load_iris()
clf = SVC(kernel='linear')
# Default score (should be the accuracy score)
scores = cross_val_score(clf, iris.data, iris.target, cv=5)
assert_array_almost_equal(scores, [0.97, 1., 0.97, 0.97, 1.], 2)
# Correct classification score (aka. zero / one score) - should be the
# same as the default estimator score
zo_scores = cross_val_score(clf, iris.data, iris.target,
scoring="accuracy", cv=5)
assert_array_almost_equal(zo_scores, [0.97, 1., 0.97, 0.97, 1.], 2)
# F1 score (class are balanced so f1_score should be equal to zero/one
# score
f1_scores = cross_val_score(clf, iris.data, iris.target,
scoring="f1_weighted", cv=5)
assert_array_almost_equal(f1_scores, [0.97, 1., 0.97, 0.97, 1.], 2)
def test_cross_val_score_with_score_func_regression():
X, y = make_regression(n_samples=30, n_features=20, n_informative=5,
random_state=0)
reg = Ridge()
# Default score of the Ridge regression estimator
scores = cross_val_score(reg, X, y, cv=5)
assert_array_almost_equal(scores, [0.94, 0.97, 0.97, 0.99, 0.92], 2)
# R2 score (aka. determination coefficient) - should be the
# same as the default estimator score
r2_scores = cross_val_score(reg, X, y, scoring="r2", cv=5)
assert_array_almost_equal(r2_scores, [0.94, 0.97, 0.97, 0.99, 0.92], 2)
# Mean squared error; this is a loss function, so "scores" are negative
neg_mse_scores = cross_val_score(reg, X, y, cv=5,
scoring="neg_mean_squared_error")
expected_neg_mse = np.array([-763.07, -553.16, -274.38, -273.26, -1681.99])
assert_array_almost_equal(neg_mse_scores, expected_neg_mse, 2)
# Explained variance
scoring = make_scorer(explained_variance_score)
ev_scores = cross_val_score(reg, X, y, cv=5, scoring=scoring)
assert_array_almost_equal(ev_scores, [0.94, 0.97, 0.97, 0.99, 0.92], 2)
def test_permutation_score():
iris = load_iris()
X = iris.data
X_sparse = coo_matrix(X)
y = iris.target
svm = SVC(kernel='linear')
cv = StratifiedKFold(2)
score, scores, pvalue = permutation_test_score(
svm, X, y, n_permutations=30, cv=cv, scoring="accuracy")
assert_greater(score, 0.9)
assert_almost_equal(pvalue, 0.0, 1)
score_group, _, pvalue_group = permutation_test_score(
svm, X, y, n_permutations=30, cv=cv, scoring="accuracy",
groups=np.ones(y.size), random_state=0)
assert_true(score_group == score)
assert_true(pvalue_group == pvalue)
# check that we obtain the same results with a sparse representation
svm_sparse = SVC(kernel='linear')
cv_sparse = StratifiedKFold(2)
score_group, _, pvalue_group = permutation_test_score(
svm_sparse, X_sparse, y, n_permutations=30, cv=cv_sparse,
scoring="accuracy", groups=np.ones(y.size), random_state=0)
assert_true(score_group == score)
assert_true(pvalue_group == pvalue)
# test with custom scoring object
def custom_score(y_true, y_pred):
return (((y_true == y_pred).sum() - (y_true != y_pred).sum()) /
y_true.shape[0])
scorer = make_scorer(custom_score)
score, _, pvalue = permutation_test_score(
svm, X, y, n_permutations=100, scoring=scorer, cv=cv, random_state=0)
assert_almost_equal(score, .93, 2)
assert_almost_equal(pvalue, 0.01, 3)
# set random y
y = np.mod(np.arange(len(y)), 3)
score, scores, pvalue = permutation_test_score(
svm, X, y, n_permutations=30, cv=cv, scoring="accuracy")
assert_less(score, 0.5)
assert_greater(pvalue, 0.2)
def test_permutation_test_score_allow_nans():
# Check that permutation_test_score allows input data with NaNs
X = np.arange(200, dtype=np.float64).reshape(10, -1)
X[2, :] = np.nan
y = np.repeat([0, 1], X.shape[0] / 2)
p = Pipeline([
('imputer', Imputer(strategy='mean', missing_values='NaN')),
('classifier', MockClassifier()),
])
permutation_test_score(p, X, y, cv=5)
def test_cross_val_score_allow_nans():
# Check that cross_val_score allows input data with NaNs
X = np.arange(200, dtype=np.float64).reshape(10, -1)
X[2, :] = np.nan
y = np.repeat([0, 1], X.shape[0] / 2)
p = Pipeline([
('imputer', Imputer(strategy='mean', missing_values='NaN')),
('classifier', MockClassifier()),
])
cross_val_score(p, X, y, cv=5)
def test_cross_val_score_multilabel():
X = np.array([[-3, 4], [2, 4], [3, 3], [0, 2], [-3, 1],
[-2, 1], [0, 0], [-2, -1], [-1, -2], [1, -2]])
y = np.array([[1, 1], [0, 1], [0, 1], [0, 1], [1, 1],
[0, 1], [1, 0], [1, 1], [1, 0], [0, 0]])
clf = KNeighborsClassifier(n_neighbors=1)
scoring_micro = make_scorer(precision_score, average='micro')
scoring_macro = make_scorer(precision_score, average='macro')
scoring_samples = make_scorer(precision_score, average='samples')
score_micro = cross_val_score(clf, X, y, scoring=scoring_micro, cv=5)
score_macro = cross_val_score(clf, X, y, scoring=scoring_macro, cv=5)
score_samples = cross_val_score(clf, X, y, scoring=scoring_samples, cv=5)
assert_almost_equal(score_micro, [1, 1 / 2, 3 / 4, 1 / 2, 1 / 3])
assert_almost_equal(score_macro, [1, 1 / 2, 3 / 4, 1 / 2, 1 / 4])
assert_almost_equal(score_samples, [1, 1 / 2, 3 / 4, 1 / 2, 1 / 4])
def test_cross_val_predict():
boston = load_boston()
X, y = boston.data, boston.target
cv = KFold()
est = Ridge()
# Naive loop (should be same as cross_val_predict):
preds2 = np.zeros_like(y)
for train, test in cv.split(X, y):
est.fit(X[train], y[train])
preds2[test] = est.predict(X[test])
preds = cross_val_predict(est, X, y, cv=cv)
assert_array_almost_equal(preds, preds2)
preds = cross_val_predict(est, X, y)
assert_equal(len(preds), len(y))
cv = LeaveOneOut()
preds = cross_val_predict(est, X, y, cv=cv)
assert_equal(len(preds), len(y))
Xsp = X.copy()
Xsp *= (Xsp > np.median(Xsp))
Xsp = coo_matrix(Xsp)
preds = cross_val_predict(est, Xsp, y)
assert_array_almost_equal(len(preds), len(y))
preds = cross_val_predict(KMeans(), X)
assert_equal(len(preds), len(y))
class BadCV():
def split(self, X, y=None, groups=None):
for i in range(4):
yield np.array([0, 1, 2, 3]), np.array([4, 5, 6, 7, 8])
assert_raises(ValueError, cross_val_predict, est, X, y, cv=BadCV())
def test_cross_val_predict_input_types():
iris = load_iris()
X, y = iris.data, iris.target
X_sparse = coo_matrix(X)
multioutput_y = np.column_stack([y, y[::-1]])
clf = Ridge(fit_intercept=False, random_state=0)
# 3 fold cv is used --> atleast 3 samples per class
# Smoke test
predictions = cross_val_predict(clf, X, y)
assert_equal(predictions.shape, (150,))
# test with multioutput y
predictions = cross_val_predict(clf, X_sparse, multioutput_y)
assert_equal(predictions.shape, (150, 2))
predictions = cross_val_predict(clf, X_sparse, y)
assert_array_equal(predictions.shape, (150,))
# test with multioutput y
predictions = cross_val_predict(clf, X_sparse, multioutput_y)
assert_array_equal(predictions.shape, (150, 2))
# test with X and y as list
list_check = lambda x: isinstance(x, list)
clf = CheckingClassifier(check_X=list_check)
predictions = cross_val_predict(clf, X.tolist(), y.tolist())
clf = CheckingClassifier(check_y=list_check)
predictions = cross_val_predict(clf, X, y.tolist())
# test with 3d X and
X_3d = X[:, :, np.newaxis]
check_3d = lambda x: x.ndim == 3
clf = CheckingClassifier(check_X=check_3d)
predictions = cross_val_predict(clf, X_3d, y)
assert_array_equal(predictions.shape, (150,))
def test_cross_val_predict_pandas():
# check cross_val_score doesn't destroy pandas dataframe
types = [(MockDataFrame, MockDataFrame)]
try:
from pandas import Series, DataFrame
types.append((Series, DataFrame))
except ImportError:
pass
for TargetType, InputFeatureType in types:
# X dataframe, y series
X_df, y_ser = InputFeatureType(X), TargetType(y2)
check_df = lambda x: isinstance(x, InputFeatureType)
check_series = lambda x: isinstance(x, TargetType)
clf = CheckingClassifier(check_X=check_df, check_y=check_series)
cross_val_predict(clf, X_df, y_ser)
def test_cross_val_score_sparse_fit_params():
iris = load_iris()
X, y = iris.data, iris.target
clf = MockClassifier()
fit_params = {'sparse_sample_weight': coo_matrix(np.eye(X.shape[0]))}
a = cross_val_score(clf, X, y, fit_params=fit_params)
assert_array_equal(a, np.ones(3))
def test_learning_curve():
n_samples = 30
n_splits = 3
X, y = make_classification(n_samples=n_samples, n_features=1,
n_informative=1, n_redundant=0, n_classes=2,
n_clusters_per_class=1, random_state=0)
estimator = MockImprovingEstimator(n_samples * ((n_splits - 1) / n_splits))
for shuffle_train in [False, True]:
with warnings.catch_warnings(record=True) as w:
train_sizes, train_scores, test_scores = learning_curve(
estimator, X, y, cv=KFold(n_splits=n_splits),
train_sizes=np.linspace(0.1, 1.0, 10),
shuffle=shuffle_train)
if len(w) > 0:
raise RuntimeError("Unexpected warning: %r" % w[0].message)
assert_equal(train_scores.shape, (10, 3))
assert_equal(test_scores.shape, (10, 3))
assert_array_equal(train_sizes, np.linspace(2, 20, 10))
assert_array_almost_equal(train_scores.mean(axis=1),
np.linspace(1.9, 1.0, 10))
assert_array_almost_equal(test_scores.mean(axis=1),
np.linspace(0.1, 1.0, 10))
# Test a custom cv splitter that can iterate only once
with warnings.catch_warnings(record=True) as w:
train_sizes2, train_scores2, test_scores2 = learning_curve(
estimator, X, y,
cv=OneTimeSplitter(n_splits=n_splits, n_samples=n_samples),
train_sizes=np.linspace(0.1, 1.0, 10),
shuffle=shuffle_train)
if len(w) > 0:
raise RuntimeError("Unexpected warning: %r" % w[0].message)
assert_array_almost_equal(train_scores2, train_scores)
assert_array_almost_equal(test_scores2, test_scores)
def test_learning_curve_unsupervised():
X, _ = make_classification(n_samples=30, n_features=1, n_informative=1,
n_redundant=0, n_classes=2,
n_clusters_per_class=1, random_state=0)
estimator = MockImprovingEstimator(20)
train_sizes, train_scores, test_scores = learning_curve(
estimator, X, y=None, cv=3, train_sizes=np.linspace(0.1, 1.0, 10))
assert_array_equal(train_sizes, np.linspace(2, 20, 10))
assert_array_almost_equal(train_scores.mean(axis=1),
np.linspace(1.9, 1.0, 10))
assert_array_almost_equal(test_scores.mean(axis=1),
np.linspace(0.1, 1.0, 10))
def test_learning_curve_verbose():
X, y = make_classification(n_samples=30, n_features=1, n_informative=1,
n_redundant=0, n_classes=2,
n_clusters_per_class=1, random_state=0)
estimator = MockImprovingEstimator(20)
old_stdout = sys.stdout
sys.stdout = StringIO()
try:
train_sizes, train_scores, test_scores = \
learning_curve(estimator, X, y, cv=3, verbose=1)
finally:
out = sys.stdout.getvalue()
sys.stdout.close()
sys.stdout = old_stdout
assert("[learning_curve]" in out)
def test_learning_curve_incremental_learning_not_possible():
X, y = make_classification(n_samples=2, n_features=1, n_informative=1,
n_redundant=0, n_classes=2,
n_clusters_per_class=1, random_state=0)
# The mockup does not have partial_fit()
estimator = MockImprovingEstimator(1)
assert_raises(ValueError, learning_curve, estimator, X, y,
exploit_incremental_learning=True)
def test_learning_curve_incremental_learning():
X, y = make_classification(n_samples=30, n_features=1, n_informative=1,
n_redundant=0, n_classes=2,
n_clusters_per_class=1, random_state=0)
estimator = MockIncrementalImprovingEstimator(20)
for shuffle_train in [False, True]:
train_sizes, train_scores, test_scores = learning_curve(
estimator, X, y, cv=3, exploit_incremental_learning=True,
train_sizes=np.linspace(0.1, 1.0, 10), shuffle=shuffle_train)
assert_array_equal(train_sizes, np.linspace(2, 20, 10))
assert_array_almost_equal(train_scores.mean(axis=1),
np.linspace(1.9, 1.0, 10))
assert_array_almost_equal(test_scores.mean(axis=1),
np.linspace(0.1, 1.0, 10))
def test_learning_curve_incremental_learning_unsupervised():
X, _ = make_classification(n_samples=30, n_features=1, n_informative=1,
n_redundant=0, n_classes=2,
n_clusters_per_class=1, random_state=0)
estimator = MockIncrementalImprovingEstimator(20)
train_sizes, train_scores, test_scores = learning_curve(
estimator, X, y=None, cv=3, exploit_incremental_learning=True,
train_sizes=np.linspace(0.1, 1.0, 10))
assert_array_equal(train_sizes, np.linspace(2, 20, 10))
assert_array_almost_equal(train_scores.mean(axis=1),
np.linspace(1.9, 1.0, 10))
assert_array_almost_equal(test_scores.mean(axis=1),
np.linspace(0.1, 1.0, 10))
def test_learning_curve_batch_and_incremental_learning_are_equal():
X, y = make_classification(n_samples=30, n_features=1, n_informative=1,
n_redundant=0, n_classes=2,
n_clusters_per_class=1, random_state=0)
train_sizes = np.linspace(0.2, 1.0, 5)
estimator = PassiveAggressiveClassifier(n_iter=1, shuffle=False)
train_sizes_inc, train_scores_inc, test_scores_inc = \
learning_curve(
estimator, X, y, train_sizes=train_sizes,
cv=3, exploit_incremental_learning=True)
train_sizes_batch, train_scores_batch, test_scores_batch = \
learning_curve(
estimator, X, y, cv=3, train_sizes=train_sizes,
exploit_incremental_learning=False)
assert_array_equal(train_sizes_inc, train_sizes_batch)
assert_array_almost_equal(train_scores_inc.mean(axis=1),
train_scores_batch.mean(axis=1))
assert_array_almost_equal(test_scores_inc.mean(axis=1),
test_scores_batch.mean(axis=1))
def test_learning_curve_n_sample_range_out_of_bounds():
X, y = make_classification(n_samples=30, n_features=1, n_informative=1,
n_redundant=0, n_classes=2,
n_clusters_per_class=1, random_state=0)
estimator = MockImprovingEstimator(20)
assert_raises(ValueError, learning_curve, estimator, X, y, cv=3,
train_sizes=[0, 1])
assert_raises(ValueError, learning_curve, estimator, X, y, cv=3,
train_sizes=[0.0, 1.0])
assert_raises(ValueError, learning_curve, estimator, X, y, cv=3,
train_sizes=[0.1, 1.1])
assert_raises(ValueError, learning_curve, estimator, X, y, cv=3,
train_sizes=[0, 20])
assert_raises(ValueError, learning_curve, estimator, X, y, cv=3,
train_sizes=[1, 21])
def test_learning_curve_remove_duplicate_sample_sizes():
X, y = make_classification(n_samples=3, n_features=1, n_informative=1,
n_redundant=0, n_classes=2,
n_clusters_per_class=1, random_state=0)
estimator = MockImprovingEstimator(2)
train_sizes, _, _ = assert_warns(
RuntimeWarning, learning_curve, estimator, X, y, cv=3,
train_sizes=np.linspace(0.33, 1.0, 3))
assert_array_equal(train_sizes, [1, 2])
def test_learning_curve_with_boolean_indices():
X, y = make_classification(n_samples=30, n_features=1, n_informative=1,
n_redundant=0, n_classes=2,
n_clusters_per_class=1, random_state=0)
estimator = MockImprovingEstimator(20)
cv = KFold(n_splits=3)
train_sizes, train_scores, test_scores = learning_curve(
estimator, X, y, cv=cv, train_sizes=np.linspace(0.1, 1.0, 10))
assert_array_equal(train_sizes, np.linspace(2, 20, 10))
assert_array_almost_equal(train_scores.mean(axis=1),
np.linspace(1.9, 1.0, 10))
assert_array_almost_equal(test_scores.mean(axis=1),
np.linspace(0.1, 1.0, 10))
def test_learning_curve_with_shuffle():
# Following test case was designed this way to verify the code
# changes made in pull request: #7506.
X = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [11, 12], [13, 14], [15, 16],
[17, 18], [19, 20], [7, 8], [9, 10], [11, 12], [13, 14],
[15, 16], [17, 18]])
y = np.array([1, 1, 1, 2, 3, 4, 1, 1, 2, 3, 4, 1, 2, 3, 4])
groups = np.array([1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 4, 4, 4, 4])
# Splits on these groups fail without shuffle as the first iteration
# of the learning curve doesn't contain label 4 in the training set.
estimator = PassiveAggressiveClassifier(shuffle=False)
cv = GroupKFold(n_splits=2)
train_sizes_batch, train_scores_batch, test_scores_batch = learning_curve(
estimator, X, y, cv=cv, n_jobs=1, train_sizes=np.linspace(0.3, 1.0, 3),
groups=groups, shuffle=True, random_state=2)
assert_array_almost_equal(train_scores_batch.mean(axis=1),
np.array([0.75, 0.3, 0.36111111]))
assert_array_almost_equal(test_scores_batch.mean(axis=1),
np.array([0.36111111, 0.25, 0.25]))
assert_raises(ValueError, learning_curve, estimator, X, y, cv=cv, n_jobs=1,
train_sizes=np.linspace(0.3, 1.0, 3), groups=groups)
train_sizes_inc, train_scores_inc, test_scores_inc = learning_curve(
estimator, X, y, cv=cv, n_jobs=1, train_sizes=np.linspace(0.3, 1.0, 3),
groups=groups, shuffle=True, random_state=2,
exploit_incremental_learning=True)
assert_array_almost_equal(train_scores_inc.mean(axis=1),
train_scores_batch.mean(axis=1))
assert_array_almost_equal(test_scores_inc.mean(axis=1),
test_scores_batch.mean(axis=1))
def test_validation_curve():
X, y = make_classification(n_samples=2, n_features=1, n_informative=1,
n_redundant=0, n_classes=2,
n_clusters_per_class=1, random_state=0)
param_range = np.linspace(0, 1, 10)
with warnings.catch_warnings(record=True) as w:
train_scores, test_scores = validation_curve(
MockEstimatorWithParameter(), X, y, param_name="param",
param_range=param_range, cv=2
)
if len(w) > 0:
raise RuntimeError("Unexpected warning: %r" % w[0].message)
assert_array_almost_equal(train_scores.mean(axis=1), param_range)
assert_array_almost_equal(test_scores.mean(axis=1), 1 - param_range)
def test_validation_curve_cv_splits_consistency():
n_samples = 100
n_splits = 5
X, y = make_classification(n_samples=100, random_state=0)
scores1 = validation_curve(SVC(kernel='linear', random_state=0), X, y,
'C', [0.1, 0.1, 0.2, 0.2],
cv=OneTimeSplitter(n_splits=n_splits,
n_samples=n_samples))
# The OneTimeSplitter is a non-re-entrant cv splitter. Unless, the
# `split` is called for each parameter, the following should produce
# identical results for param setting 1 and param setting 2 as both have
# the same C value.
assert_array_almost_equal(*np.vsplit(np.hstack(scores1)[(0, 2, 1, 3), :],
2))
scores2 = validation_curve(SVC(kernel='linear', random_state=0), X, y,
'C', [0.1, 0.1, 0.2, 0.2],
cv=KFold(n_splits=n_splits, shuffle=True))
# For scores2, compare the 1st and 2nd parameter's scores
# (Since the C value for 1st two param setting is 0.1, they must be
# consistent unless the train test folds differ between the param settings)
assert_array_almost_equal(*np.vsplit(np.hstack(scores2)[(0, 2, 1, 3), :],
2))
scores3 = validation_curve(SVC(kernel='linear', random_state=0), X, y,
'C', [0.1, 0.1, 0.2, 0.2],
cv=KFold(n_splits=n_splits))
# OneTimeSplitter is basically unshuffled KFold(n_splits=5). Sanity check.
assert_array_almost_equal(np.array(scores3), np.array(scores1))
def test_check_is_permutation():
rng = np.random.RandomState(0)
p = np.arange(100)
rng.shuffle(p)
assert_true(_check_is_permutation(p, 100))
assert_false(_check_is_permutation(np.delete(p, 23), 100))
p[0] = 23
assert_false(_check_is_permutation(p, 100))
# Check if the additional duplicate indices are caught
assert_false(_check_is_permutation(np.hstack((p, 0)), 100))
def test_cross_val_predict_sparse_prediction():
# check that cross_val_predict gives same result for sparse and dense input
X, y = make_multilabel_classification(n_classes=2, n_labels=1,
allow_unlabeled=False,
return_indicator=True,
random_state=1)
X_sparse = csr_matrix(X)
y_sparse = csr_matrix(y)
classif = OneVsRestClassifier(SVC(kernel='linear'))
preds = cross_val_predict(classif, X, y, cv=10)
preds_sparse = cross_val_predict(classif, X_sparse, y_sparse, cv=10)
preds_sparse = preds_sparse.toarray()
assert_array_almost_equal(preds_sparse, preds)
def test_cross_val_predict_with_method():
iris = load_iris()
X, y = iris.data, iris.target
X, y = shuffle(X, y, random_state=0)
classes = len(set(y))
kfold = KFold(len(iris.target))
methods = ['decision_function', 'predict_proba', 'predict_log_proba']
for method in methods:
est = LogisticRegression()
predictions = cross_val_predict(est, X, y, method=method)
assert_equal(len(predictions), len(y))
expected_predictions = np.zeros([len(y), classes])
func = getattr(est, method)
# Naive loop (should be same as cross_val_predict):
for train, test in kfold.split(X, y):
est.fit(X[train], y[train])
expected_predictions[test] = func(X[test])
predictions = cross_val_predict(est, X, y, method=method,
cv=kfold)
assert_array_almost_equal(expected_predictions, predictions)
# Test alternative representations of y
predictions_y1 = cross_val_predict(est, X, y + 1, method=method,
cv=kfold)
assert_array_equal(predictions, predictions_y1)
predictions_y2 = cross_val_predict(est, X, y - 2, method=method,
cv=kfold)
assert_array_equal(predictions, predictions_y2)
predictions_ystr = cross_val_predict(est, X, y.astype('str'),
method=method, cv=kfold)
assert_array_equal(predictions, predictions_ystr)
def get_expected_predictions(X, y, cv, classes, est, method):
expected_predictions = np.zeros([len(y), classes])
func = getattr(est, method)
for train, test in cv.split(X, y):
est.fit(X[train], y[train])
expected_predictions_ = func(X[test])
# To avoid 2 dimensional indexing
exp_pred_test = np.zeros((len(test), classes))
if method is 'decision_function' and len(est.classes_) == 2:
exp_pred_test[:, est.classes_[-1]] = expected_predictions_
else:
exp_pred_test[:, est.classes_] = expected_predictions_
expected_predictions[test] = exp_pred_test
return expected_predictions
def test_cross_val_predict_class_subset():
X = np.arange(8).reshape(4, 2)
y = np.array([0, 0, 1, 2])
classes = 3
kfold3 = KFold(n_splits=3)
kfold4 = KFold(n_splits=4)
le = LabelEncoder()
methods = ['decision_function', 'predict_proba', 'predict_log_proba']
for method in methods:
est = LogisticRegression()
# Test with n_splits=3
predictions = cross_val_predict(est, X, y, method=method,
cv=kfold3)
# Runs a naive loop (should be same as cross_val_predict):
expected_predictions = get_expected_predictions(X, y, kfold3, classes,
est, method)
assert_array_almost_equal(expected_predictions, predictions)
# Test with n_splits=4
predictions = cross_val_predict(est, X, y, method=method,
cv=kfold4)
expected_predictions = get_expected_predictions(X, y, kfold4, classes,
est, method)
assert_array_almost_equal(expected_predictions, predictions)
# Testing unordered labels
y = [1, 1, -4, 6]
predictions = cross_val_predict(est, X, y, method=method,
cv=kfold3)
y = le.fit_transform(y)
expected_predictions = get_expected_predictions(X, y, kfold3, classes,
est, method)
assert_array_almost_equal(expected_predictions, predictions)
def test_score_memmap():
# Ensure a scalar score of memmap type is accepted
iris = load_iris()
X, y = iris.data, iris.target
clf = MockClassifier()
tf = tempfile.NamedTemporaryFile(mode='wb', delete=False)
tf.write(b'Hello world!!!!!')
tf.close()
scores = np.memmap(tf.name, dtype=np.float64)
score = np.memmap(tf.name, shape=(), mode='r', dtype=np.float64)
try:
cross_val_score(clf, X, y, scoring=lambda est, X, y: score)
# non-scalar should still fail
assert_raises(ValueError, cross_val_score, clf, X, y,
scoring=lambda est, X, y: scores)
finally:
# Best effort to release the mmap file handles before deleting the
# backing file under Windows
scores, score = None, None
for _ in range(3):
try:
os.unlink(tf.name)
break
except WindowsError:
sleep(1.)
def test_permutation_test_score_pandas():
# check permutation_test_score doesn't destroy pandas dataframe
types = [(MockDataFrame, MockDataFrame)]
try:
from pandas import Series, DataFrame
types.append((Series, DataFrame))
except ImportError:
pass
for TargetType, InputFeatureType in types:
# X dataframe, y series
iris = load_iris()
X, y = iris.data, iris.target
X_df, y_ser = InputFeatureType(X), TargetType(y)
check_df = lambda x: isinstance(x, InputFeatureType)
check_series = lambda x: isinstance(x, TargetType)
clf = CheckingClassifier(check_X=check_df, check_y=check_series)
permutation_test_score(clf, X_df, y_ser)
|
bsd-3-clause
|
henridwyer/scikit-learn
|
benchmarks/bench_random_projections.py
|
397
|
8900
|
"""
===========================
Random projection benchmark
===========================
Benchmarks for random projections.
"""
from __future__ import division
from __future__ import print_function
import gc
import sys
import optparse
from datetime import datetime
import collections
import numpy as np
import scipy.sparse as sp
from sklearn import clone
from sklearn.externals.six.moves import xrange
from sklearn.random_projection import (SparseRandomProjection,
GaussianRandomProjection,
johnson_lindenstrauss_min_dim)
def type_auto_or_float(val):
if val == "auto":
return "auto"
else:
return float(val)
def type_auto_or_int(val):
if val == "auto":
return "auto"
else:
return int(val)
def compute_time(t_start, delta):
mu_second = 0.0 + 10 ** 6 # number of microseconds in a second
return delta.seconds + delta.microseconds / mu_second
def bench_scikit_transformer(X, transfomer):
gc.collect()
clf = clone(transfomer)
# start time
t_start = datetime.now()
clf.fit(X)
delta = (datetime.now() - t_start)
# stop time
time_to_fit = compute_time(t_start, delta)
# start time
t_start = datetime.now()
clf.transform(X)
delta = (datetime.now() - t_start)
# stop time
time_to_transform = compute_time(t_start, delta)
return time_to_fit, time_to_transform
# Make some random data with uniformly located non zero entries with
# Gaussian distributed values
def make_sparse_random_data(n_samples, n_features, n_nonzeros,
random_state=None):
rng = np.random.RandomState(random_state)
data_coo = sp.coo_matrix(
(rng.randn(n_nonzeros),
(rng.randint(n_samples, size=n_nonzeros),
rng.randint(n_features, size=n_nonzeros))),
shape=(n_samples, n_features))
return data_coo.toarray(), data_coo.tocsr()
def print_row(clf_type, time_fit, time_transform):
print("%s | %s | %s" % (clf_type.ljust(30),
("%.4fs" % time_fit).center(12),
("%.4fs" % time_transform).center(12)))
if __name__ == "__main__":
###########################################################################
# Option parser
###########################################################################
op = optparse.OptionParser()
op.add_option("--n-times",
dest="n_times", default=5, type=int,
help="Benchmark results are average over n_times experiments")
op.add_option("--n-features",
dest="n_features", default=10 ** 4, type=int,
help="Number of features in the benchmarks")
op.add_option("--n-components",
dest="n_components", default="auto",
help="Size of the random subspace."
" ('auto' or int > 0)")
op.add_option("--ratio-nonzeros",
dest="ratio_nonzeros", default=10 ** -3, type=float,
help="Number of features in the benchmarks")
op.add_option("--n-samples",
dest="n_samples", default=500, type=int,
help="Number of samples in the benchmarks")
op.add_option("--random-seed",
dest="random_seed", default=13, type=int,
help="Seed used by the random number generators.")
op.add_option("--density",
dest="density", default=1 / 3,
help="Density used by the sparse random projection."
" ('auto' or float (0.0, 1.0]")
op.add_option("--eps",
dest="eps", default=0.5, type=float,
help="See the documentation of the underlying transformers.")
op.add_option("--transformers",
dest="selected_transformers",
default='GaussianRandomProjection,SparseRandomProjection',
type=str,
help="Comma-separated list of transformer to benchmark. "
"Default: %default. Available: "
"GaussianRandomProjection,SparseRandomProjection")
op.add_option("--dense",
dest="dense",
default=False,
action="store_true",
help="Set input space as a dense matrix.")
(opts, args) = op.parse_args()
if len(args) > 0:
op.error("this script takes no arguments.")
sys.exit(1)
opts.n_components = type_auto_or_int(opts.n_components)
opts.density = type_auto_or_float(opts.density)
selected_transformers = opts.selected_transformers.split(',')
###########################################################################
# Generate dataset
###########################################################################
n_nonzeros = int(opts.ratio_nonzeros * opts.n_features)
print('Dataset statics')
print("===========================")
print('n_samples \t= %s' % opts.n_samples)
print('n_features \t= %s' % opts.n_features)
if opts.n_components == "auto":
print('n_components \t= %s (auto)' %
johnson_lindenstrauss_min_dim(n_samples=opts.n_samples,
eps=opts.eps))
else:
print('n_components \t= %s' % opts.n_components)
print('n_elements \t= %s' % (opts.n_features * opts.n_samples))
print('n_nonzeros \t= %s per feature' % n_nonzeros)
print('ratio_nonzeros \t= %s' % opts.ratio_nonzeros)
print('')
###########################################################################
# Set transformer input
###########################################################################
transformers = {}
###########################################################################
# Set GaussianRandomProjection input
gaussian_matrix_params = {
"n_components": opts.n_components,
"random_state": opts.random_seed
}
transformers["GaussianRandomProjection"] = \
GaussianRandomProjection(**gaussian_matrix_params)
###########################################################################
# Set SparseRandomProjection input
sparse_matrix_params = {
"n_components": opts.n_components,
"random_state": opts.random_seed,
"density": opts.density,
"eps": opts.eps,
}
transformers["SparseRandomProjection"] = \
SparseRandomProjection(**sparse_matrix_params)
###########################################################################
# Perform benchmark
###########################################################################
time_fit = collections.defaultdict(list)
time_transform = collections.defaultdict(list)
print('Benchmarks')
print("===========================")
print("Generate dataset benchmarks... ", end="")
X_dense, X_sparse = make_sparse_random_data(opts.n_samples,
opts.n_features,
n_nonzeros,
random_state=opts.random_seed)
X = X_dense if opts.dense else X_sparse
print("done")
for name in selected_transformers:
print("Perform benchmarks for %s..." % name)
for iteration in xrange(opts.n_times):
print("\titer %s..." % iteration, end="")
time_to_fit, time_to_transform = bench_scikit_transformer(X_dense,
transformers[name])
time_fit[name].append(time_to_fit)
time_transform[name].append(time_to_transform)
print("done")
print("")
###########################################################################
# Print results
###########################################################################
print("Script arguments")
print("===========================")
arguments = vars(opts)
print("%s \t | %s " % ("Arguments".ljust(16),
"Value".center(12),))
print(25 * "-" + ("|" + "-" * 14) * 1)
for key, value in arguments.items():
print("%s \t | %s " % (str(key).ljust(16),
str(value).strip().center(12)))
print("")
print("Transformer performance:")
print("===========================")
print("Results are averaged over %s repetition(s)." % opts.n_times)
print("")
print("%s | %s | %s" % ("Transformer".ljust(30),
"fit".center(12),
"transform".center(12)))
print(31 * "-" + ("|" + "-" * 14) * 2)
for name in sorted(selected_transformers):
print_row(name,
np.mean(time_fit[name]),
np.mean(time_transform[name]))
print("")
print("")
|
bsd-3-clause
|
wangsharp/trading-with-python
|
lib/widgets.py
|
78
|
3012
|
# -*- coding: utf-8 -*-
"""
A collection of widgets for gui building
Copyright: Jev Kuznetsov
License: BSD
"""
from __future__ import division
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import numpy as np
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
class MatplotlibWidget(QWidget):
def __init__(self,parent=None,grid=True):
QWidget.__init__(self,parent)
self.grid = grid
self.fig = Figure()
self.canvas =FigureCanvas(self.fig)
self.canvas.setParent(self)
self.canvas.mpl_connect('button_press_event', self.onPick) # bind pick event
#self.axes = self.fig.add_subplot(111)
margins = [0.05,0.1,0.9,0.8]
self.axes = self.fig.add_axes(margins)
self.toolbar = NavigationToolbar(self.canvas,self)
#self.initFigure()
layout = QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
self.setLayout(layout)
def onPick(self,event):
print 'Pick event'
print 'you pressed', event.button, event.xdata, event.ydata
def update(self):
self.canvas.draw()
def plot(self,*args,**kwargs):
self.axes.plot(*args,**kwargs)
self.axes.grid(self.grid)
self.update()
def clear(self):
self.axes.clear()
def initFigure(self):
self.axes.grid(True)
x = np.linspace(-1,1)
y = x**2
self.axes.plot(x,y,'o-')
class PlotWindow(QMainWindow):
''' a stand-alone window with embedded matplotlib widget '''
def __init__(self,parent=None):
super(PlotWindow,self).__init__(parent)
self.setAttribute(Qt.WA_DeleteOnClose)
self.mplWidget = MatplotlibWidget()
self.setCentralWidget(self.mplWidget)
def plot(self,dataFrame):
''' plot dataframe '''
dataFrame.plot(ax=self.mplWidget.axes)
def getAxes(self):
return self.mplWidget.axes
def getFigure(self):
return self.mplWidget.fig
def update(self):
self.mplWidget.update()
class MainForm(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.setWindowTitle('Demo: PyQt with matplotlib')
self.plot = MatplotlibWidget()
self.setCentralWidget(self.plot)
self.plot.clear()
self.plot.plot(np.random.rand(10),'x-')
#---------------------
if __name__=='__main__':
app = QApplication(sys.argv)
form = MainForm()
form.show()
app.exec_()
|
bsd-3-clause
|
CVML/hyperopt
|
hyperopt/plotting.py
|
3
|
19940
|
"""
Functions to visualize an Experiment.
"""
__authors__ = "James Bergstra"
__license__ = "3-clause BSD License"
__contact__ = "James Bergstra <[email protected]>"
import math
import sys
# -- don't import this here because it locks in the backend
# and we want the unittests to be able to set the backend
##import matplotlib.pyplot as plt
import numpy as np
from . import base
from .base import miscs_to_idxs_vals
default_status_colors = {
base.STATUS_NEW: 'k',
base.STATUS_RUNNING: 'g',
base.STATUS_OK:'b',
base.STATUS_FAIL:'r'}
def algo_as_str(algo):
if isinstance(algo, basestring):
return algo
return str(algo)
def main_plot_history(trials, bandit=None, algo=None, do_show=True,
status_colors=None):
# -- import here because file-level import is too early
import matplotlib.pyplot as plt
# self is an Experiment
if status_colors is None:
status_colors = default_status_colors
Xs = trials.specs
# XXX: show the un-finished or error trials
Ys, colors = zip(*[(y, status_colors[s])
for y, s in zip(trials.losses(bandit), trials.statuses(bandit))
if y is not None])
plt.scatter(range(len(Ys)), Ys, c=colors)
plt.xlabel('time')
plt.ylabel('loss')
if bandit is not None and bandit.loss_target is not None:
plt.axhline(bandit.loss_target)
ymin = min(np.min(Ys), bandit.loss_target)
ymax = max(np.max(Ys), bandit.loss_target)
yrange = ymax - ymin
ymean = (ymax + ymin) / 2.0
plt.ylim(
ymean - 0.53 * yrange,
ymean + 0.53 * yrange,
)
best_err = trials.average_best_error(bandit)
print "avg best error:", best_err
plt.axhline(best_err, c='g')
plt.title('bandit: %s algo: %s' % (
bandit.short_str() if bandit else '-',
algo_as_str(algo)))
if do_show:
plt.show()
def main_plot_histogram(trials, bandit=None, algo=None, do_show=True):
# -- import here because file-level import is too early
import matplotlib.pyplot as plt
status_colors = default_status_colors
Xs, Ys, Ss, Cs= zip(*[(x, y, s, status_colors[s])
for (x, y, s) in zip(trials.specs, trials.losses(bandit),
trials.statuses(bandit))
if y is not None ])
# XXX: deal with ok vs. un-finished vs. error trials
print 'Showing Histogram of %i jobs' % len(Ys)
plt.hist(Ys)
plt.xlabel('loss')
plt.ylabel('frequency')
plt.title('bandit: %s algo: %s' % (
bandit.short_str() if bandit else '-',
algo_as_str(algo)))
if do_show:
plt.show()
def main_plot_vars(trials, bandit=None, do_show=True, fontsize=10,
colorize_best=None,
columns=5,
):
# -- import here because file-level import is too early
import matplotlib.pyplot as plt
idxs, vals = miscs_to_idxs_vals(trials.miscs)
losses = trials.losses()
finite_losses = [y for y in losses if y not in (None, float('inf'))]
asrt = np.argsort(finite_losses)
if colorize_best != None:
colorize_thresh = finite_losses[asrt[colorize_best + 1]]
else:
# -- set to lower than best (disabled)
colorize_thresh = finite_losses[asrt[0]] - 1
loss_min = min(finite_losses)
loss_max = max(finite_losses)
print 'finite loss range', loss_min, loss_max, colorize_thresh
loss_by_tid = dict(zip(trials.tids, losses))
def color_fn(lossval):
if lossval is None:
return (1, 1, 1)
else:
t = 4 * (lossval - loss_min) / (loss_max - loss_min + .0001)
if t < 1:
return t, 0, 0
if t < 2:
return 2-t, t-1, 0
if t < 3:
return 0, 3-t, t-2
return 0, 0, 4-t
def color_fn_bw(lossval):
if lossval in (None, float('inf')):
return (1, 1, 1)
else:
t = (lossval - loss_min) / (loss_max - loss_min + .0001)
if lossval < colorize_thresh:
return (0., 1. - t, 0.) # -- red best black worst
else:
return (t, t, t) # -- white=worst, black=best
all_labels = list(idxs.keys())
titles = ['%s (%s)' % (label, bandit.params[label].name)
for label in all_labels]
order = np.argsort(titles)
C = columns
R = int(np.ceil(len(all_labels) / float(C)))
for plotnum, varnum in enumerate(order):
#print varnum, titles[varnum]
label = all_labels[varnum]
plt.subplot(R, C, plotnum + 1)
#print '-' * 80
#print 'Node', label
# hide x ticks
ticks_num, ticks_txt = plt.xticks()
plt.xticks(ticks_num, ['' for i in xrange(len(ticks_num))])
dist_name = bandit.params[label].name
x = idxs[label]
if 'log' in dist_name:
y = np.log(vals[label])
else:
y = vals[label]
plt.title(titles[varnum], fontsize=fontsize)
c = map(color_fn_bw, [loss_by_tid[ii] for ii in idxs[label]])
if len(y):
plt.scatter(x, y, c=c)
if 'log' in dist_name:
nums, texts = plt.yticks()
plt.yticks(nums, ['%.2e' % np.exp(t) for t in nums])
if do_show:
plt.show()
if 0:
def erf(x):
"""Erf impl that doesn't require scipy.
"""
# from http://www.math.sfu.ca/~cbm/aands/frameindex.htm
# via
# http://stackoverflow.com/questions/457408/
# is-there-an-easily-available-implementation-of-erf-for-python
#
#
# save the sign of x
sign = 1
if x < 0:
sign = -1
x = abs(x)
# constants
a1 = 0.254829592
a2 = -0.284496736
a3 = 1.421413741
a4 = -1.453152027
a5 = 1.061405429
p = 0.3275911
# A&S formula 7.1.26
t = 1.0/(1.0 + p*x)
y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*math.exp(-x*x)
return sign*y # erf(-x) = -erf(x)
def mixed_max_erf(scores, n_valid):
scores = list(scores) # shallow copy
scores.sort() # sort the copy
scores.reverse() # reverse the order
#this is valid for classification
# where the scores are the means of Bernoulli variables.
best_mean = scores[0][0]
best_variance = best_mean * (1.0 - best_mean) / (n_valid - 1)
rval = 0.0
rval_denom = 0.0
for i, (vscore,tscore) in enumerate(scores):
mean = vscore
variance = mean * (1.0 - mean) / (n_valid - 1)
diff_mean = mean - best_mean
diff_variance = variance + best_variance
# for scores, which should approach 1, the diff here will be negative (or zero).
# so the probability of the current point being the best is the probability that
# the current gaussian puts on positive values.
assert diff_mean <= 0.0
p_current_is_best = 0.5 - 0.5 * erf(-diff_mean / math.sqrt(diff_variance))
rval += p_current_is_best * tscore
rval_denom += p_current_is_best
if p_current_is_best < 0.001:
#print 'breaking after',i, 'examples'
break
return rval / rval_denom
def mixed_max_sampled(scores, n_valid, n_samples=100, rng=None):
scores = list(scores) # shallow copy
scores.sort() # sort the copy
scores.reverse() # reverse the order
# this is valid for classification
# where the scores are the means of Bernoulli variables.
best_mean = scores[0][0]
best_variance = best_mean * (1.0 - best_mean) / (n_valid - 1)
mu = []
sigma = []
tscores = []
for i, (vscore,tscore) in enumerate(scores):
mean = vscore
variance = mean * (1.0 - mean) / (n_valid - 1)
diff_mean = mean - best_mean
diff_variance = variance + best_variance
# for scores, which should approach 1, the diff here will be negative (or zero).
# so the probability of the current point being the best is the probability that
# the current gaussian puts on positive values.
if -diff_mean / np.sqrt(diff_variance) > 3:
#print 'breaking after', len(tscores), len(scores)
break
else:
mu.append(diff_mean)
sigma.append(np.sqrt(diff_variance))
tscores.append(tscore)
if rng is None:
rng = np.random.RandomState(232342)
mu = np.asarray(mu)
sigma = np.asarray(sigma)
tscores = np.asarray(tscores)
nrml = rng.randn(n_samples, len(mu)) * sigma + mu
winners = (nrml.T == nrml.max(axis=1))
p_best_ = winners.sum(axis=0)
p_best = p_best_ / p_best_.sum()
return np.dot(p_best, t_scores), p_best
if 0:
def rexp_plot_acc(scores, n_valid, n_test, pbest_n_samples=100, rng=None):
"""
Uses the current pyplot figure to show efficiency of random experiment.
:type scores: a list of (validation accuracy, test accuracy) pairs
:param scores: results from the trials of a random experiment
:type n_valid: integer
:param n_valid: size of the validation set
:type n_test: integer
:param n_test: size of the test set
:type mixed_max: function like mixed_max_erf or mixed_max_sampled
:param mixed_max: the function to estimate the maximum of a validation sample
"""
if rng is None:
rng = np.random.RandomState(232342)
K = 1
scatter_x = []
scatter_y = []
scatter_c = []
box_x = []
log_K = 0
while K < len(scores):
n_batches_of_K = len(scores)//K
if n_batches_of_K < 2:
break
def best_score(i):
scores_i = scores[i*K:(i+1)*K]
rval= np.dot(
[tscore for (vscore,tscore) in scores_i],
pbest_sampled(
[vscore for (vscore,tscore) in scores_i],
n_valid,
n_samples=pbest_n_samples,
rng=rng))
#print rval
return rval
if n_batches_of_K < 10:
# use scatter plot
for i in xrange(n_batches_of_K):
scatter_x.append(log_K+1)
scatter_y.append(best_score(i))
scatter_c.append((0,0,0))
box_x.append([])
else:
# use box plot
box_x.append([best_score(i) for i in xrange(n_batches_of_K)])
K *= 2
log_K += 1
plt.scatter( scatter_x, scatter_y, c=scatter_c, marker='+', linewidths=0.2,
edgecolors=scatter_c)
boxplot_lines = plt.boxplot(box_x)
for key in boxplot_lines:
plt.setp(boxplot_lines[key], color='black')
#plt.setp(boxplot_lines['medians'], color=(.5,.5,.5))
# draw the spans
#
# the 'test performance of the best model' is a mixture of gaussian-distributed quantity
# with components comp_mean, and comp_var and weights w
#
# w[i] is prob. of i'th model being best in validation
w = pbest_sampled([vs for (vs,ts) in scores], n_valid, n_samples=pbest_n_samples, rng=rng)
comp_mean = np.asarray([ts for (vs,ts) in scores])
comp_var = (comp_mean * (1-comp_mean)) / (n_test-1)
# the mean of the mixture is
mean = np.dot(w, comp_mean)
#the variance of the mixture is
var = np.dot(w, comp_mean**2 + comp_var) - mean**2
# test average is distributed according to a mixture of gaussians, so we have to use the following fo
std = math.sqrt(var)
#plt.axhline(mean, color=(1.0,1.0,1.0), linestyle='--', linewidth=0.1)
#plt.axhspan(mean-1.96*std, mean+1.96*std, color=(0.5,0.5,0.5))
plt.axhline(mean-1.96*std, color=(0.0,0.0,0.0))
plt.axhline(mean+1.96*std, color=(0.0,0.0,0.0))
# get margin:
if 0:
margin = 1.0 - mean
plt.ylim(0.5-margin, 1.0 )
# set ticks
ticks_num, ticks_txt = plt.xticks()
plt.xticks(ticks_num, ['%i'%(2**i) for i in xrange(len(ticks_num))])
def rexp_pairs_raw(x, y, vscores):
if len(x) != len(y): raise ValueError()
if len(x) != len(vscores): raise ValueError()
vxy = zip(vscores, x, y)
vxy.sort()
vscores, x, y = zip(*vxy)
vscores = np.asarray(vscores)
max_score = vscores.max()
min_score = vscores.min()
colors = np.outer(0.9 - 0.89*(vscores - min_score)/(max_score- min_score), [1,1,1])
plt.scatter( x, y, c=colors, marker='o', linewidths=0.1)
#remove ticks labels
nums, texts = plt.xticks()
plt.xticks(nums, ['']*len(nums))
nums, texts = plt.yticks()
plt.yticks(nums, ['']*len(nums))
class CoordType(object):pass
class RealCoord(CoordType):
@staticmethod
def preimage(x): return np.asarray(x)
class LogCoord(CoordType):
@staticmethod
def preimage(x): return np.log(x)
class Log0Coord(CoordType):
@staticmethod
def preimage(x):
x = np.asarray(x)
return np.log(x+(x==0)*x.min()/2)
IntCoord = RealCoord
LogIntCoord = LogCoord
class CategoryCoord(CoordType):
def __init__(self, categories=None):
self.categories = categories
def preimage(self, x):
if self.categories:
return np.asarray([self.categories.index(xi) for xi in x])
else:
return x
def rexp_pairs(x, y, vscores, xtype, ytype):
return rexp_pairs_raw(xtype.preimage(x), ytype.preimage(y), vscores)
class MultiHistory(object):
"""
Show the history of multiple optimization algorithms.
"""
def __init__(self):
self.histories = []
def add_experiment(self, mj, y_fn, start=0, stop=sys.maxint,
color=None,
label=None):
trials = [(job['book_time'], job, y_fn(job))
for job in mj if ('book_time' in job
and y_fn(job) is not None
and np.isfinite(y_fn(job)))]
trials.sort()
trials = trials[start:stop]
if trials:
self.histories.append((
[t[1] for t in trials],
[t[2] for t in trials],
color, label))
else:
print 'NO TRIALS'
def add_scatters(self):
for t, y, c, l in self.histories:
print 'setting label', l
plt.scatter(
np.arange(len(y)),
y,
c=c,
label=l,
s=12)
def main_show(self, title=None):
self.add_scatters()
if title:
plt.title(title)
#plt.axvline(25) # make a parameter
#plt.axhline(.2)
#plt.axhline(.3)
plt.show()
def main_plot_histories(cls):
import plotting
conn_str_template = sys.argv[2]
algos = sys.argv[3].split(',')
dataset_name = sys.argv[4]
start = int(sys.argv[5]) if len(sys.argv)>5 else 0
stop = int(sys.argv[6]) if len(sys.argv)>6 else sys.maxint
mh = plotting.MultiHistory()
colors = ['r', 'y', 'b', 'g', 'c', 'k']
def custom_err_fn(trial):
if 2 == trial['status']:
rval = 1.0 - trial['result']['best_epoch_valid']
if rval > dict(
convex=.4,
mnist_rotated_background_images=2)[dataset_name]:
return None
else:
return rval
for c, algo in zip(colors, algos):
conn_str = conn_str_template % (algo, dataset_name)
print 'algo', algo
mh.add_experiment(
mj=MongoJobs.new_from_connection_str(conn_str),
y_fn=custom_err_fn,
color=c,
label=algo,
start=start,
stop=stop)
plt = plotting.plt
plt.axhline(
1.0 - icml07.dbn3_scores[dataset_name],
c='k',label='manual+grid')#, dashes=[0,1])
mh.add_scatters()
plt.legend()
plt.title(dataset_name)
plt.show()
class ScatterByConf(object):
trial_color_dict = {0:'k', 1:'g', 2:'b', 3:'r'}
def __init__(self, conf_template, confs, status, y):
self.conf_template = conf_template
self.confs = confs
self.y = np.asarray(y)
assert self.y.ndim == 1
self.status = status
self.colors = np.asarray(
[self.trial_color_dict.get(s, None) for s in self.status])
self.a_choices = np.array([[e['choice']
for e in t.flatten()]
for t in confs])
self.nones = np.array([[None
for e in t.flatten()]
for t in confs])
self.a_names = conf_template.flatten_names()
self.a_vars = [not np.all(self.a_choices[:,i]==self.nones[:,i])
for i,name in enumerate(self.a_names)]
assert len(self.y) == len(self.a_choices)
assert len(self.y) == len(self.colors)
def trial_color(self, t):
return self.trial_color_dict.get(t['status'], None)
def scatter_one(self, column):
assert self.a_vars[column]
non_missing = self.a_choices[:,column] != self.nones[:,column]
x = self.a_choices[non_missing, column]
y = self.y[non_missing]
c = self.colors[non_missing]
plt.xlabel(self.a_names[column])
plt.scatter(x, y, c=c)
def main_show_one(self, column):
# show all conf effects in a grid of scatter-plots
self.scatter_one(column)
plt.show()
def main_show_all(self, columns=None):
if columns == None:
columns = range(len(self.a_vars))
columns = [c for c in columns if c < len(self.a_vars)]
n_vars = np.sum(self.a_vars[c] for c in columns)
print n_vars
n_rows = 1
n_cols = 10000
n_vars -= 1
while n_cols > 5 and n_cols > 3 * n_rows: # while "is ugly"
n_vars += 1 # leave one more space at the end...
n_rows = int(np.sqrt(n_vars))
while n_vars % n_rows:
n_rows -= 1
n_cols = n_vars / n_rows
print n_rows, n_cols
subplot_idx = 0
for var_idx in columns:
if self.a_vars[var_idx]:
plt.subplot(n_rows, n_cols, subplot_idx+1)
self.scatter_one(var_idx)
subplot_idx += 1
plt.show()
def main_plot_scatter(self, argv):
low_col = int(argv[0])
high_col = int(argv[1])
# upgrade jobs in db to ht_dist2-compatible things
scatter_by_conf = ScatterByConf(
self.bandit.template,
self.trials,
status = self.statuses(),
y = self.losses())
return scatter_by_conf.main_show_all(range(low_col, high_col))
|
bsd-3-clause
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.