INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Will error if filename is not appropriate but it s checked elsewhere. | def save_json_dict(filename, json_dict):
"""Will error if filename is not appropriate, but it's checked elsewhere.
"""
if isinstance(json_dict, dict):
with open(filename, "w") as f:
f.write(json.dumps(json_dict, indent=4))
else:
raise TypeError("json_dict was not a dictionay. couldn't save.") |
Returns a dictionary with the schema for a QuantFigure | def _get_schema(self):
"""
Returns a dictionary with the schema for a QuantFigure
"""
d={}
layout_kwargs=dict((_,'') for _ in get_layout_kwargs())
for _ in ('data','layout','theme','panels'):
d[_]={}
for __ in eval('__QUANT_FIGURE_{0}'.format(_.upper())):
layout_kwargs.pop(__,None)
d[_][__]=N... |
Returns a sliced DataFrame | def _get_sliced(self,slice,df=None):
"""
Returns a sliced DataFrame
Parameters
----------
slice : tuple(from,to)
from : str
to : str
States the 'from' and 'to' values which
will get rendered as df.ix[from:to]
df : DataFrame
If omitted then the QuantFigure.DataFrame is resampled.
... |
Returns a resampled DataFrame | def _get_resampled(self,rule,how={'ohlc':'last','volume':'sum'},df=None,**kwargs):
"""
Returns a resampled DataFrame
Parameters
----------
rule : str
the offset string or object representing target conversion
for all aliases available see http://pandas.pydata.org/pandas-docs/stable/timeseries.html#o... |
Updates the values for a QuantFigure The key - values are automatically assigned to the correct section of the QuantFigure | def update(self,**kwargs):
"""
Updates the values for a QuantFigure
The key-values are automatically assigned to the correct
section of the QuantFigure
"""
if 'columns' in kwargs:
self._d=ta._ohlc_dict(self.df,columns=kwargs.pop('columns',None))
schema=self._get_schema()
annotations=kwargs.pop('anno... |
Deletes the values for a QuantFigure The key - values are automatically deleted from the correct section of the QuantFigure | def delete(self,*args):
"""
Deletes the values for a QuantFigure
The key-values are automatically deleted from the correct
section of the QuantFigure
"""
if args:
args=args[0] if utils.is_list(args[0]) else args
path=utils.dict_path(self.__dict__)
for _ in args:
if _ in self.__dict__.keys():
... |
Returns the panel domains for each axis | def _panel_domains(self,n=2,min_panel_size=.15,spacing=0.08,top_margin=1,bottom_margin=0):
"""
Returns the panel domains for each axis
"""
d={}
for _ in range(n+1,1,-1):
lower=round(bottom_margin+(min_panel_size+spacing)*(n+1-_),2)
d['yaxis{0}'.format(_)]=dict(domain=(lower,lower+min_panel_size))
... |
Returns a trendline ( line ) support or resistance | def _get_trendline(self,date0=None,date1=None,on=None,kind='trend',to_strfmt='%Y-%m-%d',from_strfmt='%d%b%y',**kwargs):
"""
Returns a trendline (line), support or resistance
Parameters:
date0 : string
Trendline starting date
date1 : string
Trendline end date
on : string
Indicate the data... |
Adds a trendline to the QuantFigure. Given 2 dates the trendline is connected on the data points that correspond to those dates. | def add_trendline(self,date0,date1,on='close',text=None,**kwargs):
"""
Adds a trendline to the QuantFigure.
Given 2 dates, the trendline is connected on the data points
that correspond to those dates.
Parameters:
date0 : string
Trendline starting date
date1 : string
Trendline end date
on ... |
Adds a support line to the QuantFigure | def add_support(self,date,on='low',mode='starttoend',text=None,**kwargs):
"""
Adds a support line to the QuantFigure
Parameters:
date0 : string
The support line will be drawn at the 'y' level
value that corresponds to this date.
on : string
Indicate the data series in which the
support l... |
Add an annotation to the QuantFigure. | def add_annotations(self,annotations,**kwargs):
"""
Add an annotation to the QuantFigure.
Parameters:
annotations : dict or list(dict,)
Annotations can be on the form form of
{'date' : 'text'}
and the text will automatically be placed at the
right level on the chart
or
A Plotly... |
Add a shape to the QuantFigure. | def add_shapes(self,**kwargs):
"""
Add a shape to the QuantFigure.
kwargs :
hline : int, list or dict
Draws a horizontal line at the
indicated y position(s)
Extra parameters can be passed in
the form of a dictionary (see shapes)
vline : int, list or dict
Draws a vertical line at the
... |
Adds a study to QuantFigure. studies | def _add_study(self,study):
"""
Adds a study to QuantFigure.studies
Parameters:
study : dict
{'kind':study_kind,
'params':study_parameters,
'display':display_parameters}
"""
str='{study} {name}({period})' if study['params'].get('str',None)==None else study['params']['str']
study['params'][... |
Add volume study to QuantFigure. studies | def add_volume(self,colorchange=True,column=None,name='',str='{name}',**kwargs):
"""
Add 'volume' study to QuantFigure.studies
Parameters:
colorchange : bool
If True then each volume bar will have a fill color
depending on if 'base' had a positive or negative
change compared to the previous value... |
Add Moving Average Convergence Divergence ( MACD ) study to QuantFigure. studies | def add_macd(self,fast_period=12,slow_period=26,signal_period=9,column=None,
name='',str=None,**kwargs):
"""
Add Moving Average Convergence Divergence (MACD) study to QuantFigure.studies
Parameters:
fast_period : int
MACD Fast Period
slow_period : int
MACD Slow Period
signal_period : int
... |
Add Simple Moving Average ( SMA ) study to QuantFigure. studies | def add_sma(self,periods=20,column=None,name='',
str=None,**kwargs):
"""
Add Simple Moving Average (SMA) study to QuantFigure.studies
Parameters:
periods : int or list(int)
Number of periods
column :string
Defines the data column name that contains the
data over which the study will be ap... |
Add Relative Strength Indicator ( RSI ) study to QuantFigure. studies | def add_rsi(self,periods=20,rsi_upper=70,rsi_lower=30,showbands=True,column=None,
name='',str=None,**kwargs):
"""
Add Relative Strength Indicator (RSI) study to QuantFigure.studies
Parameters:
periods : int or list(int)
Number of periods
rsi_upper : int
bounds [0,100]
Upper (overbough... |
Add Bollinger Bands ( BOLL ) study to QuantFigure. studies | def add_bollinger_bands(self,periods=20,boll_std=2,fill=True,column=None,name='',
str='{name}({column},{period})',**kwargs):
"""
Add Bollinger Bands (BOLL) study to QuantFigure.studies
Parameters:
periods : int or list(int)
Number of periods
boll_std : int
Number of standard deviations for... |
Commodity Channel Indicator study to QuantFigure. studies | def add_cci(self,periods=14,cci_upper=100,cci_lower=-100,
showbands=True,str=None,name='',**kwargs):
"""
Commodity Channel Indicator study to QuantFigure.studies
Parameters:
periods : int or list(int)
Number of periods
cci_upper : int
Upper bands level
default : 100
cci_lower : int
... |
Add Parabolic SAR ( PTPS ) study to QuantFigure. studies | def add_ptps(self,periods=14,af=0.2,initial='long',str=None,name='',**kwargs):
"""
Add Parabolic SAR (PTPS) study to QuantFigure.studies
Parameters:
periods : int or list(int)
Number of periods
af : float
acceleration factor
initial : 'long' or 'short'
Iniital position
default: long
n... |
Add Average True Range ( ATR ) study to QuantFigure. studies | def add_atr(self,periods=14,str=None,name='',**kwargs):
"""
Add Average True Range (ATR) study to QuantFigure.studies
Parameters:
periods : int or list(int)
Number of periods
name : string
Name given to the study
str : string
Label factory for studies
The following wildcards can be used:... |
connected: bool If True the plotly. js library will be loaded from an online CDN. If False the plotly. js library will be loaded locally from the plotly python package | def go_offline(connected=None):
"""
connected : bool
If True, the plotly.js library will be loaded
from an online CDN. If False, the plotly.js library will be loaded locally
from the plotly python package
"""
from .auth import get_config_file
if connected is None:
try... |
Filters a DataFrame for columns that contain the given strings. Parameters: ----------- include: bool If False then it will exclude items that match the given filters. This is the same as passing a regex ^keyword kwargs: Key value pairs that indicate the column and value to screen for | def _screen(self,include=True,**kwargs):
"""
Filters a DataFrame for columns that contain the given strings.
Parameters:
-----------
include : bool
If False then it will exclude items that match
the given filters.
This is the same as passing a regex ^keyword
kwargs :
Key value pairs that indicate... |
Returns a series with the bestfit values. Example: Series. bestfit () | def bestfit(self):
"""
Returns a series with the bestfit values.
Example:
Series.bestfit()
Returns: series
The returned series contains a parameter
called 'formula' which includes the string representation
of the bestfit line.
"""
# statsmodel cannot be included on requirements.txt
# see https://g... |
Returns a normalized series or DataFrame Example: Series. normalize () | def normalize(self,asOf=None,multiplier=100):
"""
Returns a normalized series or DataFrame
Example:
Series.normalize()
Returns: series of DataFrame
Parameters:
-----------
asOf : string
Date format
'2015-02-29'
multiplier : int
Factor by which the results will be adjusted
"""
if not asOf:
... |
d1 < -- d2 | def merge_dict(d1,d2):
"""
d1 <-- d2
"""
d=copy.deepcopy(d2)
for k,v in list(d1.items()):
if k not in d:
d[k]=v
else:
if isinstance(v,dict):
d[k]=merge_dict(d1[k],d[k])
return d |
Returns a dictionary with the path in which each of the keys is found | def dict_path(from_d,to_d={},l=[]):
"""
Returns a dictionary with the path in which each of the keys is found
Parameters:
from_d : dict
Dictionary that contains all the keys, values
to_d : dict
Dictionary to which the results will be appended
Example:
dict_path({'level1':{'level2':{'level3':'value'}}... |
Formats ( prettyprint ) a concatenated dictionary | def pp(el,preString=''):
"""
Formats (prettyprint) a concatenated dictionary
"""
tab=' '*4
if isinstance(el,dict):
keys=list(el.keys())
keys.sort()
for key in keys:
val=el[key]
if isinstance(val,dict) or isinstance(val,list):
print('%s%s :' % (preString,key))
pp(val,preString+tab)
else:
... |
Returns a dictionay indexed by values { value_k: key_k } Parameters: ----------- d: dictionary | def inverseDict(d):
"""
Returns a dictionay indexed by values {value_k:key_k}
Parameters:
-----------
d : dictionary
"""
dt={}
for k,v in list(d.items()):
if type(v) in (list,tuple):
for i in v:
dt[i]=k
else:
dt[v]=k
return dt |
Looks for keys of the format keyword_value. And return a dictionary with { keyword: value } format | def kwargs_from_keyword(from_kwargs,to_kwargs,keyword,clean_origin=True):
"""
Looks for keys of the format keyword_value.
And return a dictionary with {keyword:value} format
Parameters:
-----------
from_kwargs : dict
Original dictionary
to_kwargs : dict
Dictionary where the items will be appended
key... |
Updates the values ( deep form ) of a given dictionary | def deep_update(d,d_update):
"""
Updates the values (deep form) of a given dictionary
Parameters:
-----------
d : dict
dictionary that contains the values to update
d_update : dict
dictionary to be updated
"""
for k,v in list(d_update.items()):
if isinstance(v,dict):
if k in d:
deep_update(d[k... |
Reads a google sheet | def read_google(self,url,**kwargs):
"""
Reads a google sheet
"""
if url[-1]!='/':
url+='/'
return self.read_csv(url+'export?gid=0&format=csv',**kwargs) |
Returns a string that represents a date n numbers of days from today. Parameters: ----------- delta: int number of days strfmt: string format in which the date will be represented | def getDateFromToday(delta,strfmt='%Y%m%d'):
""" Returns a string that represents a date n numbers of days from today.
Parameters:
-----------
delta : int
number of days
strfmt : string
format in which the date will be represented
"""
return (dt.date.today() + dt.timedelta(delta)).strftime(strfmt) |
Returns a dictionary with the actual column names that correspond to each of the OHLCV values. | def _ohlc_dict(df_or_figure,open='',high='',low='',close='',volume='',
validate='',**kwargs):
"""
Returns a dictionary with the actual column names that
correspond to each of the OHLCV values.
df_or_figure : DataFrame or Figure
open : string
Column name to be used for OPEN values
high : string
Column... |
how: string value pct_chg diff | def correl(df,periods=21,columns=None,include=True,str=None,detail=False,how='value',**correl_kwargs):
"""
how : string
value
pct_chg
diff
"""
def _correl(df,periods=21,columns=None,include=True,str=None,detail=False,**correl_kwargs):
study='CORREL'
df,_df,columns=validate(df,columns)
_df['CORREL']... |
Returns | def scattergeo():
"""
Returns
"""
path=os.path.join(os.path.dirname(__file__), '../data/scattergeo.csv')
df=pd.read_csv(path)
del df['Unnamed: 0']
df['text'] = df['airport'] + ' ' + df['city'] + ', ' + df['state'] + ' ' + 'Arrivals: ' + df['cnt'].astype(str)
df=df.rename(columns={'cnt':'z','long':'lon'})
retu... |
Returns | def choropleth():
"""
Returns
"""
path=os.path.join(os.path.dirname(__file__), '../data/choropleth.csv')
df=pd.read_csv(path)
del df['Unnamed: 0']
df['z']=[np.random.randint(0,100) for _ in range(len(df))]
return df |
Returns a DataFrame with the required format for a pie plot | def pie(n_labels=5,mode=None):
"""
Returns a DataFrame with the required format for
a pie plot
Parameters:
-----------
n_labels : int
Number of labels
mode : string
Format for each item
'abc' for alphabet columns
'stocks' for random stock names
"""
return pd.DataFrame({'values':np.random.ra... |
Returns a DataFrame with the required format for a scatter plot | def scatter(n_categories=5,n=10,prefix='category',mode=None):
"""
Returns a DataFrame with the required format for
a scatter plot
Parameters:
-----------
n_categories : int
Number of categories
n : int
Number of points for each category
prefix : string
Name for each category
mode : string
Fo... |
Returns a DataFrame with the required format for a heatmap plot | def heatmap(n_x=5,n_y=10):
"""
Returns a DataFrame with the required format for
a heatmap plot
Parameters:
-----------
n_x : int
Number of x categories
n_y : int
Number of y categories
"""
x=['x_'+str(_) for _ in range(n_x)]
y=['y_'+str(_) for _ in range(n_y)]
return pd.DataFrame(surface(n_x-1,n_y... |
Returns a DataFrame with the required format for a scatter ( lines ) plot | def lines(n_traces=5,n=100,columns=None,dateIndex=True,mode=None):
"""
Returns a DataFrame with the required format for
a scatter (lines) plot
Parameters:
-----------
n_traces : int
Number of traces
n : int
Number of points for each trace
columns : [str]
List of column names
dateIndex : bool
... |
Returns a DataFrame with the required format for a bar plot | def bars(n=3,n_categories=3,prefix='category',columns=None,mode='abc'):
"""
Returns a DataFrame with the required format for
a bar plot
Parameters:
-----------
n : int
Number of points for each trace
n_categories : int
Number of categories for each point
prefix : string
Name for each category
co... |
Returns a DataFrame with the required format for a candlestick or ohlc plot df [[ open high low close ]] | def ohlc(n=100):
"""
Returns a DataFrame with the required format for
a candlestick or ohlc plot
df[['open','high','low','close']]
Parameters:
-----------
n : int
Number of ohlc points
"""
index=pd.date_range('1/1/15',periods=n*288,freq='5min',tz='utc')
data=np.random.randn(n*288)
data[0]=np.array(... |
Returns a DataFrame with the required format for a candlestick or ohlc plot df [[ open high low close volume ] | def ohlcv(n=100):
"""
Returns a DataFrame with the required format for
a candlestick or ohlc plot
df[['open','high','low','close','volume']
Parameters:
-----------
n : int
Number of ohlc points
"""
df=ohlc()
df['volume']=[np.random.randint(1000,10000) for _ in range(len(df))]
return df |
Returns a DataFrame with the required format for a box plot | def box(n_traces=5,n=100,mode=None):
"""
Returns a DataFrame with the required format for
a box plot
Parameters:
-----------
n_traces : int
Number of traces
n : int
Number of points for each trace
mode : string
Format for each item
'abc' for alphabet columns
'stocks' for random stock name... |
Returns a DataFrame with the required format for a histogram plot | def histogram(n_traces=1,n=500,dispersion=2,mode=None):
"""
Returns a DataFrame with the required format for
a histogram plot
Parameters:
-----------
n_traces : int
Number of traces
n : int
Number of points for each trace
mode : string
Format for each item
'abc' for alphabet columns
'stoc... |
Returns a DataFrame with the required format for a distribution plot ( distplot ) | def distplot(n_traces=1,n=500,dispersion=3,mode=None):
"""
Returns a DataFrame with the required format for
a distribution plot (distplot)
Parameters:
-----------
n_traces : int
Number of traces
n : int
Number of points for each trace
mode : string
Format for each item
'abc' for alphabet colu... |
Returns a DataFrame with the required format for a distribution plot ( distplot ) | def violin(n=500,dispersion=3,categories=True,n_categories=5):
"""
Returns a DataFrame with the required format for
a distribution plot (distplot)
Parameters:
-----------
n : int
Number of points
categories : bool or int
If True, then a column with categories is added
n_categories : int
Number of... |
Returns a DataFrame with the required format for a surface plot | def surface(n_x=20,n_y=20):
"""
Returns a DataFrame with the required format for
a surface plot
Parameters:
-----------
n_x : int
Number of points along the X axis
n_y : int
Number of points along the Y axis
"""
x=[float(np.random.randint(0,100))]
for i in range(n_x):
x.append(x[:1][0]+np.random.... |
Returns a DataFrame with the required format for a surface ( sine wave ) plot | def sinwave(n=4,inc=.25):
"""
Returns a DataFrame with the required format for
a surface (sine wave) plot
Parameters:
-----------
n : int
Ranges for X and Y axis (-n,n)
n_y : int
Size of increment along the axis
"""
x=np.arange(-n,n,inc)
y=np.arange(-n,n,inc)
X,Y=np.meshgrid(x,y)
R = np.sqrt(X**2... |
Returns a theme definition. | def getTheme(theme=None):
"""
Returns a theme definition.
To see the colors translated (hex) use
cufflinks.getLayout(theme) instead.
"""
if not theme:
theme = auth.get_config_file()['theme']
if theme in THEMES:
return updateColors(copy.deepcopy(THEMES[theme]))
else:
raise Exception("Invalid Theme: {0}".... |
Generates a plotly Layout | def getLayout(kind=None,theme=None,title='',xTitle='',yTitle='',zTitle='',barmode='',bargap=None,bargroupgap=None,
margin=None, dimensions=None, width=None, height=None,
annotations=None,is3d=False,**kwargs):
"""
Generates a plotly Layout
Parameters:
-----------
theme : string
Layout Theme
solar... |
Generates an annotations object | def get_annotations(df,annotations,kind='lines',theme=None,**kwargs):
"""
Generates an annotations object
Parameters:
-----------
df : DataFrame
Original DataFrame of values
annotations : dict or list
Dictionary of annotations
{x_point : text}
or
List of Plotly annotations
"""
for key in ... |
Strips a figure into multiple figures with a trace on each of them | def strip_figures(figure):
"""
Strips a figure into multiple figures with a trace on each of them
Parameters:
-----------
figure : Figure
Plotly Figure
"""
fig=[]
for trace in figure['data']:
fig.append(dict(data=[trace],layout=figure['layout']))
return fig |
Generates a layout with the union of all properties of multiple figures layouts | def get_base_layout(figs):
"""
Generates a layout with the union of all properties of multiple
figures' layouts
Parameters:
-----------
fig : list(Figures)
List of Plotly Figures
"""
layout={}
for fig in figs:
if not isinstance(fig,dict):
fig=fig.to_dict()
for k,v in list(fig['layout'].items()):
... |
Generates multiple Plotly figures for a given DataFrame | def figures(df,specs,asList=False):
"""
Generates multiple Plotly figures for a given DataFrame
Parameters:
-----------
df : DataFrame
Pandas DataFrame
specs : list(dict)
List of dictionaries with the properties
of each figure.
All properties avaialbe can be seen with
help(cufflinks.pd.DataFrame... |
Generates a single Figure from a list of figures | def merge_figures(figures):
"""
Generates a single Figure from a list of figures
Parameters:
-----------
figures : list(Figures)
List of figures to be merged.
"""
figure={}
data=[]
for fig in figures:
for trace in fig['data']:
data.append(trace)
layout=get_base_layout(figures)
figure['data']=data
... |
Generates a subplot view for a set of figures This is a wrapper for plotly. tools. make_subplots | def subplots(figures,shape=None,
shared_xaxes=False, shared_yaxes=False,
start_cell='top-left', theme=None,base_layout=None,
**kwargs):
"""
Generates a subplot view for a set of figures
This is a wrapper for plotly.tools.make_subplots
Parameters:
-----------
figures : [Figures]
List of Plot... |
Generates a subplot view for a set of figures | def get_subplots(rows=1,cols=1,
shared_xaxes=False, shared_yaxes=False,
start_cell='top-left', theme=None,base_layout=None,
**kwargs):
"""
Generates a subplot view for a set of figures
Parameters:
-----------
rows : int
Number of rows
cols : int
Number of cols
shared_xaxes : bool
... |
Displays a matrix with scatter plot for each pair of Series in the DataFrame. The diagonal shows a histogram for each of the Series | def scatter_matrix(df,theme=None,bins=10,color='grey',size=2):
"""
Displays a matrix with scatter plot for each pair of
Series in the DataFrame.
The diagonal shows a histogram for each of the Series
Parameters:
-----------
df : DataFrame
Pandas DataFrame
theme : string
Theme to be used (if not the defa... |
Sets the axis in which each trace should appear If the axis doesn t exist then a new axis is created | def _set_axis(self,traces,on=None,side='right',title=''):
"""
Sets the axis in which each trace should appear
If the axis doesn't exist then a new axis is created
Parameters:
-----------
traces : list(str)
List of trace names
on : string
The axis in which the traces should be placed.
If this is not i... |
Returns a plotly shape | def get_shape(kind='line',x=None,y=None,x0=None,y0=None,x1=None,y1=None,span=0,color='red',dash='solid',width=1,
fillcolor=None,fill=False,opacity=1,xref='x',yref='y'):
"""
Returns a plotly shape
Parameters:
-----------
kind : string
Shape kind
line
rect
circle
x : float
x values for the ... |
Returns a range selector Reference: https:// plot. ly/ python/ reference/ #layout - xaxis - rangeselector | def get_range_selector(steps=['1m','1y'],bgcolor='rgba(150, 200, 250, 0.4)',x=0,y=0.9,
visible=True,**kwargs):
"""
Returns a range selector
Reference: https://plot.ly/python/reference/#layout-xaxis-rangeselector
Parameters:
-----------
steps : string or list(string)
Steps for the range
Examples:
... |
Display an [ n m ] matrix of labels | def view_label_matrix(L, colorbar=True):
"""Display an [n, m] matrix of labels"""
L = L.todense() if sparse.issparse(L) else L
plt.imshow(L, aspect="auto")
plt.title("Label Matrix")
if colorbar:
labels = sorted(np.unique(np.asarray(L).reshape(-1, 1).squeeze()))
boundaries = np.array(... |
Display an [ m m ] matrix of overlaps | def view_overlaps(L, self_overlaps=False, normalize=True, colorbar=True):
"""Display an [m, m] matrix of overlaps"""
L = L.todense() if sparse.issparse(L) else L
G = _get_overlaps_matrix(L, normalize=normalize)
if not self_overlaps:
np.fill_diagonal(G, 0) # Zero out self-overlaps
plt.imshow... |
Display an [ m m ] matrix of conflicts | def view_conflicts(L, normalize=True, colorbar=True):
"""Display an [m, m] matrix of conflicts"""
L = L.todense() if sparse.issparse(L) else L
C = _get_conflicts_matrix(L, normalize=normalize)
plt.imshow(C, aspect="auto")
plt.title("Conflicts")
if colorbar:
plt.colorbar()
plt.show() |
Plot a histogram from a numpy array of probabilities | def plot_probabilities_histogram(Y_p, title=None):
"""Plot a histogram from a numpy array of probabilities
Args:
Y_p: An [n] or [n, 1] np.ndarray of probabilities (floats in [0,1])
"""
if Y_p.ndim > 1:
msg = (
f"Arg Y_p should be a 1-dimensional np.ndarray, not of shape "
... |
Plot a histogram comparing int predictions vs true labels by class | def plot_predictions_histogram(Y_ph, Y, title=None):
"""Plot a histogram comparing int predictions vs true labels by class
Args:
Y_ph: An [n] or [n, 1] np.ndarray of predicted int labels
Y: An [n] or [n, 1] np.ndarray of gold labels
"""
labels = list(set(Y).union(set(Y_ph)))
edges =... |
Given a set of int nodes i and edges ( i j ) returns an nx. Graph object G which is a clique tree where: - G. node [ i ] [ members ] contains the set of original nodes in the ith maximal clique - G [ i ] [ j ] [ members ] contains the set of original nodes in the seperator set between maximal cliques i and j | def get_clique_tree(nodes, edges):
"""Given a set of int nodes i and edges (i,j), returns an nx.Graph object G
which is a clique tree, where:
- G.node[i]['members'] contains the set of original nodes in the ith
maximal clique
- G[i][j]['members'] contains the set of original nodes in... |
Returns True if the logging frequency has been met. | def check(self, batch_size):
"""Returns True if the logging frequency has been met."""
self.increment(batch_size)
return self.unit_count >= self.config["log_train_every"] |
Update the total and relative unit counts | def increment(self, batch_size):
"""Update the total and relative unit counts"""
self.example_count += batch_size
self.example_total += batch_size
if self.log_unit == "seconds":
self.unit_count = int(self.timer.elapsed())
self.unit_total = int(self.timer.total_ela... |
Add standard and custom metrics to metrics_dict | def calculate_metrics(self, model, train_loader, valid_loader, metrics_dict):
"""Add standard and custom metrics to metrics_dict"""
# Check whether or not it's time for validation as well
self.log_count += 1
log_valid = (
valid_loader is not None
and self.valid_ev... |
Print calculated metrics and optionally write to file ( json/ tb ) | def log(self, metrics_dict):
"""Print calculated metrics and optionally write to file (json/tb)"""
if self.writer:
self.write_to_file(metrics_dict)
if self.verbose:
self.print_to_screen(metrics_dict)
self.reset() |
Print all metrics in metrics_dict to screen | def print_to_screen(self, metrics_dict):
"""Print all metrics in metrics_dict to screen"""
score_strings = defaultdict(list)
for split_metric, value in metrics_dict.items():
split, metric = split_metric.split("/", 1)
if isinstance(value, float):
score_str... |
Reduces the output of an LSTM step | def _reduce_output(self, outputs, seq_lengths):
"""Reduces the output of an LSTM step
Args:
outputs: (torch.FloatTensor) the hidden state outputs from the
lstm, with shape [batch_size, max_seq_length, hidden_size]
"""
batch_size = outputs.shape[0]
red... |
Applies one step of an lstm ( plus reduction ) to the input X which is handled by self. encoder | def forward(self, X):
"""Applies one step of an lstm (plus reduction) to the input X, which
is handled by self.encoder"""
# Identify the first non-zero integer from the right (i.e., the length
# of the sequence before padding starts).
batch_size, max_seq = X.shape[0], X.shape[1]
... |
Given a cardinality k and true label y return random value in { 1... k } \ { y }. | def choose_other_label(k, y):
"""Given a cardinality k and true label y, return random value in
{1,...,k} \ {y}."""
return choice(list(set(range(1, k + 1)) - set([y]))) |
Generate Gaussian bags of words based on label assignments | def gaussian_bags_of_words(Y, vocab=vocab1k, sigma=1, bag_size=[25, 50], **kwargs):
"""
Generate Gaussian bags of words based on label assignments
Args:
Y: np.array of true labels
sigma: (float) the standard deviation of the Gaussian distributions
bag_size: (list) the min and max le... |
Generate a random tree - structured dependency graph based on a specified edge probability. | def _generate_edges(self, edge_prob):
"""Generate a random tree-structured dependency graph based on a
specified edge probability.
Also create helper data struct mapping child -> parent.
"""
self.E, self.parent = [], {}
for i in range(self.m):
if random() < e... |
Compute the conditional probability P_ \ theta ( li | lj y ) = Z^ { - 1 } exp ( theta_ { i|y } \ indpm { \ lambda_i = Y } + \ theta_ { i j } \ indpm { \ lambda_i = \ lambda_j } ) In other words compute the conditional probability that LF i outputs li given that LF j output lj and Y = y parameterized by - a class - cond... | def P_conditional(self, i, li, j, lj, y):
"""Compute the conditional probability
P_\theta(li | lj, y)
=
Z^{-1} exp(
theta_{i|y} \indpm{ \lambda_i = Y }
+ \theta_{i,j} \indpm{ \lambda_i = \lambda_j }
)
In other words, compute... |
Generate an [ n m ] label matrix with entries in { 0... k } | def _generate_label_matrix(self):
"""Generate an [n,m] label matrix with entries in {0,...,k}"""
self.L = np.zeros((self.n, self.m))
self.Y = np.zeros(self.n, dtype=np.int64)
for i in range(self.n):
y = choice(self.k, p=self.p) + 1 # Note that y \in {1,...,k}
sel... |
Compute the true clique conditional probabilities P ( \ lC | Y ) by counting given L Y ; we ll use this as ground truth to compare to. | def _get_conditional_probs(self):
"""Compute the true clique conditional probabilities P(\lC | Y) by
counting given L, Y; we'll use this as ground truth to compare to.
Note that this generates an attribute, self.c_probs, that has the same
definition as returned by `LabelModel.get_condit... |
Execute fit and transform in sequence. | def fit_transform(self, input, **fit_kwargs):
"""Execute fit and transform in sequence."""
self.fit(input, **fit_kwargs)
X = self.transform(input)
return X |
Builds a vocabulary object based on the tokens in the input. | def fit(self, sents, **kwargs):
"""Builds a vocabulary object based on the tokens in the input.
Args:
sents: A list of lists of tokens (representing sentences)
Vocab kwargs include:
max_size
min_freq
specials
unk_init
"""
... |
Converts lists of tokens into a Tensor of embedding indices. | def transform(self, sents):
"""Converts lists of tokens into a Tensor of embedding indices.
Args:
sents: A list of lists of tokens (representing sentences)
NOTE: These sentences should already be marked using the
mark_entities() helper.
Returns:
... |
Argmax with random tie - breaking | def rargmax(x, eps=1e-8):
"""Argmax with random tie-breaking
Args:
x: a 1-dim numpy array
Returns:
the argmax index
"""
idxs = np.where(abs(x - np.max(x, axis=0)) < eps)[0]
return np.random.choice(idxs) |
Converts a 1D tensor of predicted labels into a 2D tensor of probabilistic labels | def pred_to_prob(Y_h, k):
"""Converts a 1D tensor of predicted labels into a 2D tensor of probabilistic labels
Args:
Y_h: an [n], or [n,1] tensor of predicted (int) labels in {1,...,k}
k: the largest possible label in Y_h
Returns:
Y_s: a torch.FloatTensor of shape [n, k] where Y_s[i... |
Convert a 1d array - like ( e. g. list tensor etc. ) to an np. ndarray | def arraylike_to_numpy(array_like):
"""Convert a 1d array-like (e.g,. list, tensor, etc.) to an np.ndarray"""
orig_type = type(array_like)
# Convert to np.ndarray
if isinstance(array_like, np.ndarray):
pass
elif isinstance(array_like, list):
array_like = np.array(array_like)
el... |
Convert a matrix from one label type to another | def convert_labels(Y, source, dest):
"""Convert a matrix from one label type to another
Args:
Y: A np.ndarray or torch.Tensor of labels (ints)
source: The convention the labels are currently expressed in
dest: The convention to convert the labels to
Conventions:
'categorica... |
Converts a 2D [ n m ] label matrix into an [ n m k ] one hot 3D tensor | def label_matrix_to_one_hot(L, k=None):
"""Converts a 2D [n,m] label matrix into an [n,m,k] one hot 3D tensor
Note that in the returned 3D matrix, abstain votes continue to be
represented by 0s, not 1s.
Args:
L: a [n,m] label matrix with categorical labels (0 = abstain)
k: the number o... |
Merge dictionary y into a copy of x overwriting elements of x when there is a conflict except if the element is a dictionary in which case recurse. | def recursive_merge_dicts(x, y, misses="report", verbose=None):
"""
Merge dictionary y into a copy of x, overwriting elements of x when there
is a conflict, except if the element is a dictionary, in which case recurse.
misses: what to do if a key in y is not in x
'insert' -> set x[key] = val... |
Splits inputs into multiple splits of defined sizes | def split_data(
*inputs,
splits=[0.5, 0.5],
shuffle=True,
stratify_by=None,
index_only=False,
seed=None,
):
"""Splits inputs into multiple splits of defined sizes
Args:
inputs: correlated tuples/lists/arrays/matrices/tensors to split
splits: list containing split sizes (... |
Utility to place data on GPU where data could be a torch. Tensor a tuple or list of Tensors or a tuple or list of tuple or lists of Tensors | def place_on_gpu(data):
"""Utility to place data on GPU, where data could be a torch.Tensor, a tuple
or list of Tensors, or a tuple or list of tuple or lists of Tensors"""
data_type = type(data)
if data_type in (list, tuple):
data = [place_on_gpu(data[i]) for i in range(len(data))]
data ... |
TBD | def _build(self, input_modules, middle_modules, head_modules):
"""
TBD
"""
self.input_layer = self._build_input_layer(input_modules)
self.middle_layers = self._build_middle_layers(middle_modules)
self.heads = self._build_task_heads(head_modules)
# Construct loss ... |
Creates and attaches task_heads to the appropriate network layers | def _build_task_heads(self, head_modules):
"""Creates and attaches task_heads to the appropriate network layers"""
# Make task head layer assignments
num_layers = len(self.config["layer_out_dims"])
task_head_layers = self._set_task_head_layers(num_layers)
# task_head_layers stor... |
Returns a list of outputs for tasks 0... t - 1 | def forward(self, x):
"""Returns a list of outputs for tasks 0,...t-1
Args:
x: a [batch_size, ...] batch from X
"""
head_outputs = [None] * self.t
# Execute input layer
if isinstance(self.input_layer, list): # One input_module per task
input_out... |
Convert Y to t - length list of probabilistic labels if necessary | def _preprocess_Y(self, Y, k=None):
"""Convert Y to t-length list of probabilistic labels if necessary"""
# If not a list, convert to a singleton list
if not isinstance(Y, list):
if self.t != 1:
msg = "For t > 1, Y must be a list of n-dim or [n, K_t] tensors"
... |
Returns the loss function to use in the train_model routine | def _get_loss_fn(self):
"""Returns the loss function to use in the train_model routine"""
criteria = self.criteria.to(self.config["device"])
loss_fn = lambda X, Y: sum(
criteria(Y_tp, Y_t) for Y_tp, Y_t in zip(self.forward(X), Y)
)
return loss_fn |
Convert T label matrices with labels in 0... K_t to a one - hot format | def _create_L_ind(self, L):
"""Convert T label matrices with labels in 0...K_t to a one-hot format
Here we can view e.g. the $(i,j)$ entries of the $T$ label matrices as
a _label vector_ emitted by LF j for data point i.
Args:
L: a T-length list of [n,m] scipy.sparse label ... |
Returns the task marginals estimated by the model: a t - length list of [ n k_t ] matrices where the ( i j ) entry of the sth matrix represents the estimated P (( Y_i ) _s | \ lambda_j ( x_i )) | def predict_proba(self, L):
"""Returns the task marginals estimated by the model: a t-length list of
[n,k_t] matrices where the (i,j) entry of the sth matrix represents the
estimated P((Y_i)_s | \lambda_j(x_i))
Args:
L: A t-length list of [n,m] scipy.sparse label matrices wi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.