repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
Neurosim-lab/netpyne | doc/source/code/HHCellFile.py | Cell.createNetcon | def createNetcon(self, thresh=10):
""" created netcon to record spikes """
nc = h.NetCon(self.soma(0.5)._ref_v, None, sec = self.soma)
nc.threshold = thresh
return nc | python | def createNetcon(self, thresh=10):
""" created netcon to record spikes """
nc = h.NetCon(self.soma(0.5)._ref_v, None, sec = self.soma)
nc.threshold = thresh
return nc | [
"def",
"createNetcon",
"(",
"self",
",",
"thresh",
"=",
"10",
")",
":",
"nc",
"=",
"h",
".",
"NetCon",
"(",
"self",
".",
"soma",
"(",
"0.5",
")",
".",
"_ref_v",
",",
"None",
",",
"sec",
"=",
"self",
".",
"soma",
")",
"nc",
".",
"threshold",
"=",
"thresh",
"return",
"nc"
] | created netcon to record spikes | [
"created",
"netcon",
"to",
"record",
"spikes"
] | edb67b5098b2e7923d55010ded59ad1bf75c0f18 | https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/doc/source/code/HHCellFile.py#L42-L46 | train | 237,600 |
Neurosim-lab/netpyne | doc/source/code/HHCellFile.py | HHCellClass.createSections | def createSections(self):
"""Create the sections of the cell."""
self.soma = h.Section(name='soma', cell=self)
self.dend = h.Section(name='dend', cell=self) | python | def createSections(self):
"""Create the sections of the cell."""
self.soma = h.Section(name='soma', cell=self)
self.dend = h.Section(name='dend', cell=self) | [
"def",
"createSections",
"(",
"self",
")",
":",
"self",
".",
"soma",
"=",
"h",
".",
"Section",
"(",
"name",
"=",
"'soma'",
",",
"cell",
"=",
"self",
")",
"self",
".",
"dend",
"=",
"h",
".",
"Section",
"(",
"name",
"=",
"'dend'",
",",
"cell",
"=",
"self",
")"
] | Create the sections of the cell. | [
"Create",
"the",
"sections",
"of",
"the",
"cell",
"."
] | edb67b5098b2e7923d55010ded59ad1bf75c0f18 | https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/doc/source/code/HHCellFile.py#L51-L54 | train | 237,601 |
Neurosim-lab/netpyne | doc/source/code/HHCellFile.py | HHCellClass.defineGeometry | def defineGeometry(self):
"""Set the 3D geometry of the cell."""
self.soma.L = 18.8
self.soma.diam = 18.8
self.soma.Ra = 123.0
self.dend.L = 200.0
self.dend.diam = 1.0
self.dend.Ra = 100.0 | python | def defineGeometry(self):
"""Set the 3D geometry of the cell."""
self.soma.L = 18.8
self.soma.diam = 18.8
self.soma.Ra = 123.0
self.dend.L = 200.0
self.dend.diam = 1.0
self.dend.Ra = 100.0 | [
"def",
"defineGeometry",
"(",
"self",
")",
":",
"self",
".",
"soma",
".",
"L",
"=",
"18.8",
"self",
".",
"soma",
".",
"diam",
"=",
"18.8",
"self",
".",
"soma",
".",
"Ra",
"=",
"123.0",
"self",
".",
"dend",
".",
"L",
"=",
"200.0",
"self",
".",
"dend",
".",
"diam",
"=",
"1.0",
"self",
".",
"dend",
".",
"Ra",
"=",
"100.0"
] | Set the 3D geometry of the cell. | [
"Set",
"the",
"3D",
"geometry",
"of",
"the",
"cell",
"."
] | edb67b5098b2e7923d55010ded59ad1bf75c0f18 | https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/doc/source/code/HHCellFile.py#L56-L64 | train | 237,602 |
Neurosim-lab/netpyne | doc/source/code/HHCellFile.py | HHCellClass.defineBiophysics | def defineBiophysics(self):
"""Assign the membrane properties across the cell."""
# Insert active Hodgkin-Huxley current in the soma
self.soma.insert('hh')
self.soma.gnabar_hh = 0.12 # Sodium conductance in S/cm2
self.soma.gkbar_hh = 0.036 # Potassium conductance in S/cm2
self.soma.gl_hh = 0.003 # Leak conductance in S/cm2
self.soma.el_hh = -70 # Reversal potential in mV
self.dend.insert('pas')
self.dend.g_pas = 0.001 # Passive conductance in S/cm2
self.dend.e_pas = -65 # Leak reversal potential mV
self.dend.nseg = 1000 | python | def defineBiophysics(self):
"""Assign the membrane properties across the cell."""
# Insert active Hodgkin-Huxley current in the soma
self.soma.insert('hh')
self.soma.gnabar_hh = 0.12 # Sodium conductance in S/cm2
self.soma.gkbar_hh = 0.036 # Potassium conductance in S/cm2
self.soma.gl_hh = 0.003 # Leak conductance in S/cm2
self.soma.el_hh = -70 # Reversal potential in mV
self.dend.insert('pas')
self.dend.g_pas = 0.001 # Passive conductance in S/cm2
self.dend.e_pas = -65 # Leak reversal potential mV
self.dend.nseg = 1000 | [
"def",
"defineBiophysics",
"(",
"self",
")",
":",
"# Insert active Hodgkin-Huxley current in the soma",
"self",
".",
"soma",
".",
"insert",
"(",
"'hh'",
")",
"self",
".",
"soma",
".",
"gnabar_hh",
"=",
"0.12",
"# Sodium conductance in S/cm2",
"self",
".",
"soma",
".",
"gkbar_hh",
"=",
"0.036",
"# Potassium conductance in S/cm2",
"self",
".",
"soma",
".",
"gl_hh",
"=",
"0.003",
"# Leak conductance in S/cm2",
"self",
".",
"soma",
".",
"el_hh",
"=",
"-",
"70",
"# Reversal potential in mV",
"self",
".",
"dend",
".",
"insert",
"(",
"'pas'",
")",
"self",
".",
"dend",
".",
"g_pas",
"=",
"0.001",
"# Passive conductance in S/cm2",
"self",
".",
"dend",
".",
"e_pas",
"=",
"-",
"65",
"# Leak reversal potential mV",
"self",
".",
"dend",
".",
"nseg",
"=",
"1000"
] | Assign the membrane properties across the cell. | [
"Assign",
"the",
"membrane",
"properties",
"across",
"the",
"cell",
"."
] | edb67b5098b2e7923d55010ded59ad1bf75c0f18 | https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/doc/source/code/HHCellFile.py#L66-L78 | train | 237,603 |
Neurosim-lab/netpyne | netpyne/support/morphology.py | shapeplot | def shapeplot(h,ax,sections=None,order='pre',cvals=None,\
clim=None,cmap=cm.YlOrBr_r, legend=True, **kwargs): # meanLineWidth=1.0, maxLineWidth=10.0,
"""
Plots a 3D shapeplot
Args:
h = hocObject to interface with neuron
ax = matplotlib axis for plotting
sections = list of h.Section() objects to be plotted
order = { None= use h.allsec() to get sections
'pre'= pre-order traversal of morphology }
cvals = list/array with values mapped to color by cmap; useful
for displaying voltage, calcium or some other state
variable across the shapeplot.
**kwargs passes on to matplotlib (e.g. color='r' for red lines)
Returns:
lines = list of line objects making up shapeplot
"""
# Default is to plot all sections.
if sections is None:
if order == 'pre':
sections = allsec_preorder(h) # Get sections in "pre-order"
else:
sections = list(h.allsec())
# Determine color limits
if cvals is not None and clim is None:
clim = [np.nanmin(cvals), np.nanmax(cvals)]
# Plot each segement as a line
lines = []
i = 0
allDiams = []
for sec in sections:
allDiams.append(get_section_diams(h,sec))
#maxDiams = max([max(d) for d in allDiams])
#meanDiams = np.mean([np.mean(d) for d in allDiams])
for isec,sec in enumerate(sections):
xyz = get_section_path(h,sec)
seg_paths = interpolate_jagged(xyz,sec.nseg)
diams = allDiams[isec] # represent diams as linewidths
linewidths = diams # linewidth is in points so can use actual diams to plot
# linewidths = [min(d/meanDiams*meanLineWidth, maxLineWidth) for d in diams] # use if want to scale size
for (j,path) in enumerate(seg_paths):
line, = plt.plot(path[:,0], path[:,1], path[:,2], '-k', **kwargs)
try:
line.set_linewidth(linewidths[j])
except:
pass
if cvals is not None:
if isinstance(cvals[i], numbers.Number):
# map number to colormap
try:
col = cmap(int((cvals[i]-clim[0])*255/(clim[1]-clim[0])))
except:
col = cmap(0)
else:
# use input directly. E.g. if user specified color with a string.
col = cvals[i]
line.set_color(col)
lines.append(line)
i += 1
return lines | python | def shapeplot(h,ax,sections=None,order='pre',cvals=None,\
clim=None,cmap=cm.YlOrBr_r, legend=True, **kwargs): # meanLineWidth=1.0, maxLineWidth=10.0,
"""
Plots a 3D shapeplot
Args:
h = hocObject to interface with neuron
ax = matplotlib axis for plotting
sections = list of h.Section() objects to be plotted
order = { None= use h.allsec() to get sections
'pre'= pre-order traversal of morphology }
cvals = list/array with values mapped to color by cmap; useful
for displaying voltage, calcium or some other state
variable across the shapeplot.
**kwargs passes on to matplotlib (e.g. color='r' for red lines)
Returns:
lines = list of line objects making up shapeplot
"""
# Default is to plot all sections.
if sections is None:
if order == 'pre':
sections = allsec_preorder(h) # Get sections in "pre-order"
else:
sections = list(h.allsec())
# Determine color limits
if cvals is not None and clim is None:
clim = [np.nanmin(cvals), np.nanmax(cvals)]
# Plot each segement as a line
lines = []
i = 0
allDiams = []
for sec in sections:
allDiams.append(get_section_diams(h,sec))
#maxDiams = max([max(d) for d in allDiams])
#meanDiams = np.mean([np.mean(d) for d in allDiams])
for isec,sec in enumerate(sections):
xyz = get_section_path(h,sec)
seg_paths = interpolate_jagged(xyz,sec.nseg)
diams = allDiams[isec] # represent diams as linewidths
linewidths = diams # linewidth is in points so can use actual diams to plot
# linewidths = [min(d/meanDiams*meanLineWidth, maxLineWidth) for d in diams] # use if want to scale size
for (j,path) in enumerate(seg_paths):
line, = plt.plot(path[:,0], path[:,1], path[:,2], '-k', **kwargs)
try:
line.set_linewidth(linewidths[j])
except:
pass
if cvals is not None:
if isinstance(cvals[i], numbers.Number):
# map number to colormap
try:
col = cmap(int((cvals[i]-clim[0])*255/(clim[1]-clim[0])))
except:
col = cmap(0)
else:
# use input directly. E.g. if user specified color with a string.
col = cvals[i]
line.set_color(col)
lines.append(line)
i += 1
return lines | [
"def",
"shapeplot",
"(",
"h",
",",
"ax",
",",
"sections",
"=",
"None",
",",
"order",
"=",
"'pre'",
",",
"cvals",
"=",
"None",
",",
"clim",
"=",
"None",
",",
"cmap",
"=",
"cm",
".",
"YlOrBr_r",
",",
"legend",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# meanLineWidth=1.0, maxLineWidth=10.0,",
"# Default is to plot all sections. ",
"if",
"sections",
"is",
"None",
":",
"if",
"order",
"==",
"'pre'",
":",
"sections",
"=",
"allsec_preorder",
"(",
"h",
")",
"# Get sections in \"pre-order\"",
"else",
":",
"sections",
"=",
"list",
"(",
"h",
".",
"allsec",
"(",
")",
")",
"# Determine color limits",
"if",
"cvals",
"is",
"not",
"None",
"and",
"clim",
"is",
"None",
":",
"clim",
"=",
"[",
"np",
".",
"nanmin",
"(",
"cvals",
")",
",",
"np",
".",
"nanmax",
"(",
"cvals",
")",
"]",
"# Plot each segement as a line",
"lines",
"=",
"[",
"]",
"i",
"=",
"0",
"allDiams",
"=",
"[",
"]",
"for",
"sec",
"in",
"sections",
":",
"allDiams",
".",
"append",
"(",
"get_section_diams",
"(",
"h",
",",
"sec",
")",
")",
"#maxDiams = max([max(d) for d in allDiams])",
"#meanDiams = np.mean([np.mean(d) for d in allDiams])",
"for",
"isec",
",",
"sec",
"in",
"enumerate",
"(",
"sections",
")",
":",
"xyz",
"=",
"get_section_path",
"(",
"h",
",",
"sec",
")",
"seg_paths",
"=",
"interpolate_jagged",
"(",
"xyz",
",",
"sec",
".",
"nseg",
")",
"diams",
"=",
"allDiams",
"[",
"isec",
"]",
"# represent diams as linewidths",
"linewidths",
"=",
"diams",
"# linewidth is in points so can use actual diams to plot",
"# linewidths = [min(d/meanDiams*meanLineWidth, maxLineWidth) for d in diams] # use if want to scale size ",
"for",
"(",
"j",
",",
"path",
")",
"in",
"enumerate",
"(",
"seg_paths",
")",
":",
"line",
",",
"=",
"plt",
".",
"plot",
"(",
"path",
"[",
":",
",",
"0",
"]",
",",
"path",
"[",
":",
",",
"1",
"]",
",",
"path",
"[",
":",
",",
"2",
"]",
",",
"'-k'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"line",
".",
"set_linewidth",
"(",
"linewidths",
"[",
"j",
"]",
")",
"except",
":",
"pass",
"if",
"cvals",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"cvals",
"[",
"i",
"]",
",",
"numbers",
".",
"Number",
")",
":",
"# map number to colormap",
"try",
":",
"col",
"=",
"cmap",
"(",
"int",
"(",
"(",
"cvals",
"[",
"i",
"]",
"-",
"clim",
"[",
"0",
"]",
")",
"*",
"255",
"/",
"(",
"clim",
"[",
"1",
"]",
"-",
"clim",
"[",
"0",
"]",
")",
")",
")",
"except",
":",
"col",
"=",
"cmap",
"(",
"0",
")",
"else",
":",
"# use input directly. E.g. if user specified color with a string.",
"col",
"=",
"cvals",
"[",
"i",
"]",
"line",
".",
"set_color",
"(",
"col",
")",
"lines",
".",
"append",
"(",
"line",
")",
"i",
"+=",
"1",
"return",
"lines"
] | Plots a 3D shapeplot
Args:
h = hocObject to interface with neuron
ax = matplotlib axis for plotting
sections = list of h.Section() objects to be plotted
order = { None= use h.allsec() to get sections
'pre'= pre-order traversal of morphology }
cvals = list/array with values mapped to color by cmap; useful
for displaying voltage, calcium or some other state
variable across the shapeplot.
**kwargs passes on to matplotlib (e.g. color='r' for red lines)
Returns:
lines = list of line objects making up shapeplot | [
"Plots",
"a",
"3D",
"shapeplot"
] | edb67b5098b2e7923d55010ded59ad1bf75c0f18 | https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/support/morphology.py#L279-L346 | train | 237,604 |
Neurosim-lab/netpyne | netpyne/support/morphology.py | shapeplot_animate | def shapeplot_animate(v,lines,nframes=None,tscale='linear',\
clim=[-80,50],cmap=cm.YlOrBr_r):
""" Returns animate function which updates color of shapeplot """
if nframes is None:
nframes = v.shape[0]
if tscale == 'linear':
def animate(i):
i_t = int((i/nframes)*v.shape[0])
for i_seg in range(v.shape[1]):
lines[i_seg].set_color(cmap(int((v[i_t,i_seg]-clim[0])*255/(clim[1]-clim[0]))))
return []
elif tscale == 'log':
def animate(i):
i_t = int(np.round((v.shape[0] ** (1.0/(nframes-1))) ** i - 1))
for i_seg in range(v.shape[1]):
lines[i_seg].set_color(cmap(int((v[i_t,i_seg]-clim[0])*255/(clim[1]-clim[0]))))
return []
else:
raise ValueError("Unrecognized option '%s' for tscale" % tscale)
return animate | python | def shapeplot_animate(v,lines,nframes=None,tscale='linear',\
clim=[-80,50],cmap=cm.YlOrBr_r):
""" Returns animate function which updates color of shapeplot """
if nframes is None:
nframes = v.shape[0]
if tscale == 'linear':
def animate(i):
i_t = int((i/nframes)*v.shape[0])
for i_seg in range(v.shape[1]):
lines[i_seg].set_color(cmap(int((v[i_t,i_seg]-clim[0])*255/(clim[1]-clim[0]))))
return []
elif tscale == 'log':
def animate(i):
i_t = int(np.round((v.shape[0] ** (1.0/(nframes-1))) ** i - 1))
for i_seg in range(v.shape[1]):
lines[i_seg].set_color(cmap(int((v[i_t,i_seg]-clim[0])*255/(clim[1]-clim[0]))))
return []
else:
raise ValueError("Unrecognized option '%s' for tscale" % tscale)
return animate | [
"def",
"shapeplot_animate",
"(",
"v",
",",
"lines",
",",
"nframes",
"=",
"None",
",",
"tscale",
"=",
"'linear'",
",",
"clim",
"=",
"[",
"-",
"80",
",",
"50",
"]",
",",
"cmap",
"=",
"cm",
".",
"YlOrBr_r",
")",
":",
"if",
"nframes",
"is",
"None",
":",
"nframes",
"=",
"v",
".",
"shape",
"[",
"0",
"]",
"if",
"tscale",
"==",
"'linear'",
":",
"def",
"animate",
"(",
"i",
")",
":",
"i_t",
"=",
"int",
"(",
"(",
"i",
"/",
"nframes",
")",
"*",
"v",
".",
"shape",
"[",
"0",
"]",
")",
"for",
"i_seg",
"in",
"range",
"(",
"v",
".",
"shape",
"[",
"1",
"]",
")",
":",
"lines",
"[",
"i_seg",
"]",
".",
"set_color",
"(",
"cmap",
"(",
"int",
"(",
"(",
"v",
"[",
"i_t",
",",
"i_seg",
"]",
"-",
"clim",
"[",
"0",
"]",
")",
"*",
"255",
"/",
"(",
"clim",
"[",
"1",
"]",
"-",
"clim",
"[",
"0",
"]",
")",
")",
")",
")",
"return",
"[",
"]",
"elif",
"tscale",
"==",
"'log'",
":",
"def",
"animate",
"(",
"i",
")",
":",
"i_t",
"=",
"int",
"(",
"np",
".",
"round",
"(",
"(",
"v",
".",
"shape",
"[",
"0",
"]",
"**",
"(",
"1.0",
"/",
"(",
"nframes",
"-",
"1",
")",
")",
")",
"**",
"i",
"-",
"1",
")",
")",
"for",
"i_seg",
"in",
"range",
"(",
"v",
".",
"shape",
"[",
"1",
"]",
")",
":",
"lines",
"[",
"i_seg",
"]",
".",
"set_color",
"(",
"cmap",
"(",
"int",
"(",
"(",
"v",
"[",
"i_t",
",",
"i_seg",
"]",
"-",
"clim",
"[",
"0",
"]",
")",
"*",
"255",
"/",
"(",
"clim",
"[",
"1",
"]",
"-",
"clim",
"[",
"0",
"]",
")",
")",
")",
")",
"return",
"[",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unrecognized option '%s' for tscale\"",
"%",
"tscale",
")",
"return",
"animate"
] | Returns animate function which updates color of shapeplot | [
"Returns",
"animate",
"function",
"which",
"updates",
"color",
"of",
"shapeplot"
] | edb67b5098b2e7923d55010ded59ad1bf75c0f18 | https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/support/morphology.py#L348-L368 | train | 237,605 |
Neurosim-lab/netpyne | netpyne/support/morphology.py | mark_locations | def mark_locations(h,section,locs,markspec='or',**kwargs):
"""
Marks one or more locations on along a section. Could be used to
mark the location of a recording or electrical stimulation.
Args:
h = hocObject to interface with neuron
section = reference to section
locs = float between 0 and 1, or array of floats
optional arguments specify details of marker
Returns:
line = reference to plotted markers
"""
# get list of cartesian coordinates specifying section path
xyz = get_section_path(h,section)
(r,theta,phi) = sequential_spherical(xyz)
rcum = np.append(0,np.cumsum(r))
# convert locs into lengths from the beginning of the path
if type(locs) is float or type(locs) is np.float64:
locs = np.array([locs])
if type(locs) is list:
locs = np.array(locs)
lengths = locs*rcum[-1]
# find cartesian coordinates for markers
xyz_marks = []
for targ_length in lengths:
xyz_marks.append(find_coord(targ_length,xyz,rcum,theta,phi))
xyz_marks = np.array(xyz_marks)
# plot markers
line, = plt.plot(xyz_marks[:,0], xyz_marks[:,1], \
xyz_marks[:,2], markspec, **kwargs)
return line | python | def mark_locations(h,section,locs,markspec='or',**kwargs):
"""
Marks one or more locations on along a section. Could be used to
mark the location of a recording or electrical stimulation.
Args:
h = hocObject to interface with neuron
section = reference to section
locs = float between 0 and 1, or array of floats
optional arguments specify details of marker
Returns:
line = reference to plotted markers
"""
# get list of cartesian coordinates specifying section path
xyz = get_section_path(h,section)
(r,theta,phi) = sequential_spherical(xyz)
rcum = np.append(0,np.cumsum(r))
# convert locs into lengths from the beginning of the path
if type(locs) is float or type(locs) is np.float64:
locs = np.array([locs])
if type(locs) is list:
locs = np.array(locs)
lengths = locs*rcum[-1]
# find cartesian coordinates for markers
xyz_marks = []
for targ_length in lengths:
xyz_marks.append(find_coord(targ_length,xyz,rcum,theta,phi))
xyz_marks = np.array(xyz_marks)
# plot markers
line, = plt.plot(xyz_marks[:,0], xyz_marks[:,1], \
xyz_marks[:,2], markspec, **kwargs)
return line | [
"def",
"mark_locations",
"(",
"h",
",",
"section",
",",
"locs",
",",
"markspec",
"=",
"'or'",
",",
"*",
"*",
"kwargs",
")",
":",
"# get list of cartesian coordinates specifying section path",
"xyz",
"=",
"get_section_path",
"(",
"h",
",",
"section",
")",
"(",
"r",
",",
"theta",
",",
"phi",
")",
"=",
"sequential_spherical",
"(",
"xyz",
")",
"rcum",
"=",
"np",
".",
"append",
"(",
"0",
",",
"np",
".",
"cumsum",
"(",
"r",
")",
")",
"# convert locs into lengths from the beginning of the path",
"if",
"type",
"(",
"locs",
")",
"is",
"float",
"or",
"type",
"(",
"locs",
")",
"is",
"np",
".",
"float64",
":",
"locs",
"=",
"np",
".",
"array",
"(",
"[",
"locs",
"]",
")",
"if",
"type",
"(",
"locs",
")",
"is",
"list",
":",
"locs",
"=",
"np",
".",
"array",
"(",
"locs",
")",
"lengths",
"=",
"locs",
"*",
"rcum",
"[",
"-",
"1",
"]",
"# find cartesian coordinates for markers",
"xyz_marks",
"=",
"[",
"]",
"for",
"targ_length",
"in",
"lengths",
":",
"xyz_marks",
".",
"append",
"(",
"find_coord",
"(",
"targ_length",
",",
"xyz",
",",
"rcum",
",",
"theta",
",",
"phi",
")",
")",
"xyz_marks",
"=",
"np",
".",
"array",
"(",
"xyz_marks",
")",
"# plot markers",
"line",
",",
"=",
"plt",
".",
"plot",
"(",
"xyz_marks",
"[",
":",
",",
"0",
"]",
",",
"xyz_marks",
"[",
":",
",",
"1",
"]",
",",
"xyz_marks",
"[",
":",
",",
"2",
"]",
",",
"markspec",
",",
"*",
"*",
"kwargs",
")",
"return",
"line"
] | Marks one or more locations on along a section. Could be used to
mark the location of a recording or electrical stimulation.
Args:
h = hocObject to interface with neuron
section = reference to section
locs = float between 0 and 1, or array of floats
optional arguments specify details of marker
Returns:
line = reference to plotted markers | [
"Marks",
"one",
"or",
"more",
"locations",
"on",
"along",
"a",
"section",
".",
"Could",
"be",
"used",
"to",
"mark",
"the",
"location",
"of",
"a",
"recording",
"or",
"electrical",
"stimulation",
"."
] | edb67b5098b2e7923d55010ded59ad1bf75c0f18 | https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/support/morphology.py#L370-L406 | train | 237,606 |
Neurosim-lab/netpyne | netpyne/support/morphology.py | root_sections | def root_sections(h):
"""
Returns a list of all sections that have no parent.
"""
roots = []
for section in h.allsec():
sref = h.SectionRef(sec=section)
# has_parent returns a float... cast to bool
if sref.has_parent() < 0.9:
roots.append(section)
return roots | python | def root_sections(h):
"""
Returns a list of all sections that have no parent.
"""
roots = []
for section in h.allsec():
sref = h.SectionRef(sec=section)
# has_parent returns a float... cast to bool
if sref.has_parent() < 0.9:
roots.append(section)
return roots | [
"def",
"root_sections",
"(",
"h",
")",
":",
"roots",
"=",
"[",
"]",
"for",
"section",
"in",
"h",
".",
"allsec",
"(",
")",
":",
"sref",
"=",
"h",
".",
"SectionRef",
"(",
"sec",
"=",
"section",
")",
"# has_parent returns a float... cast to bool",
"if",
"sref",
".",
"has_parent",
"(",
")",
"<",
"0.9",
":",
"roots",
".",
"append",
"(",
"section",
")",
"return",
"roots"
] | Returns a list of all sections that have no parent. | [
"Returns",
"a",
"list",
"of",
"all",
"sections",
"that",
"have",
"no",
"parent",
"."
] | edb67b5098b2e7923d55010ded59ad1bf75c0f18 | https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/support/morphology.py#L408-L418 | train | 237,607 |
Neurosim-lab/netpyne | netpyne/support/morphology.py | leaf_sections | def leaf_sections(h):
"""
Returns a list of all sections that have no children.
"""
leaves = []
for section in h.allsec():
sref = h.SectionRef(sec=section)
# nchild returns a float... cast to bool
if sref.nchild() < 0.9:
leaves.append(section)
return leaves | python | def leaf_sections(h):
"""
Returns a list of all sections that have no children.
"""
leaves = []
for section in h.allsec():
sref = h.SectionRef(sec=section)
# nchild returns a float... cast to bool
if sref.nchild() < 0.9:
leaves.append(section)
return leaves | [
"def",
"leaf_sections",
"(",
"h",
")",
":",
"leaves",
"=",
"[",
"]",
"for",
"section",
"in",
"h",
".",
"allsec",
"(",
")",
":",
"sref",
"=",
"h",
".",
"SectionRef",
"(",
"sec",
"=",
"section",
")",
"# nchild returns a float... cast to bool",
"if",
"sref",
".",
"nchild",
"(",
")",
"<",
"0.9",
":",
"leaves",
".",
"append",
"(",
"section",
")",
"return",
"leaves"
] | Returns a list of all sections that have no children. | [
"Returns",
"a",
"list",
"of",
"all",
"sections",
"that",
"have",
"no",
"children",
"."
] | edb67b5098b2e7923d55010ded59ad1bf75c0f18 | https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/support/morphology.py#L420-L430 | train | 237,608 |
Neurosim-lab/netpyne | netpyne/support/morphology.py | root_indices | def root_indices(sec_list):
"""
Returns the index of all sections without a parent.
"""
roots = []
for i,section in enumerate(sec_list):
sref = h.SectionRef(sec=section)
# has_parent returns a float... cast to bool
if sref.has_parent() < 0.9:
roots.append(i)
return roots | python | def root_indices(sec_list):
"""
Returns the index of all sections without a parent.
"""
roots = []
for i,section in enumerate(sec_list):
sref = h.SectionRef(sec=section)
# has_parent returns a float... cast to bool
if sref.has_parent() < 0.9:
roots.append(i)
return roots | [
"def",
"root_indices",
"(",
"sec_list",
")",
":",
"roots",
"=",
"[",
"]",
"for",
"i",
",",
"section",
"in",
"enumerate",
"(",
"sec_list",
")",
":",
"sref",
"=",
"h",
".",
"SectionRef",
"(",
"sec",
"=",
"section",
")",
"# has_parent returns a float... cast to bool",
"if",
"sref",
".",
"has_parent",
"(",
")",
"<",
"0.9",
":",
"roots",
".",
"append",
"(",
"i",
")",
"return",
"roots"
] | Returns the index of all sections without a parent. | [
"Returns",
"the",
"index",
"of",
"all",
"sections",
"without",
"a",
"parent",
"."
] | edb67b5098b2e7923d55010ded59ad1bf75c0f18 | https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/support/morphology.py#L432-L442 | train | 237,609 |
Neurosim-lab/netpyne | netpyne/support/morphology.py | branch_order | def branch_order(h,section, path=[]):
"""
Returns the branch order of a section
"""
path.append(section)
sref = h.SectionRef(sec=section)
# has_parent returns a float... cast to bool
if sref.has_parent() < 0.9:
return 0 # section is a root
else:
nchild = len(list(h.SectionRef(sec=sref.parent).child))
if nchild <= 1.1:
return branch_order(h,sref.parent,path)
else:
return 1+branch_order(h,sref.parent,path) | python | def branch_order(h,section, path=[]):
"""
Returns the branch order of a section
"""
path.append(section)
sref = h.SectionRef(sec=section)
# has_parent returns a float... cast to bool
if sref.has_parent() < 0.9:
return 0 # section is a root
else:
nchild = len(list(h.SectionRef(sec=sref.parent).child))
if nchild <= 1.1:
return branch_order(h,sref.parent,path)
else:
return 1+branch_order(h,sref.parent,path) | [
"def",
"branch_order",
"(",
"h",
",",
"section",
",",
"path",
"=",
"[",
"]",
")",
":",
"path",
".",
"append",
"(",
"section",
")",
"sref",
"=",
"h",
".",
"SectionRef",
"(",
"sec",
"=",
"section",
")",
"# has_parent returns a float... cast to bool",
"if",
"sref",
".",
"has_parent",
"(",
")",
"<",
"0.9",
":",
"return",
"0",
"# section is a root",
"else",
":",
"nchild",
"=",
"len",
"(",
"list",
"(",
"h",
".",
"SectionRef",
"(",
"sec",
"=",
"sref",
".",
"parent",
")",
".",
"child",
")",
")",
"if",
"nchild",
"<=",
"1.1",
":",
"return",
"branch_order",
"(",
"h",
",",
"sref",
".",
"parent",
",",
"path",
")",
"else",
":",
"return",
"1",
"+",
"branch_order",
"(",
"h",
",",
"sref",
".",
"parent",
",",
"path",
")"
] | Returns the branch order of a section | [
"Returns",
"the",
"branch",
"order",
"of",
"a",
"section"
] | edb67b5098b2e7923d55010ded59ad1bf75c0f18 | https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/support/morphology.py#L504-L518 | train | 237,610 |
Neurosim-lab/netpyne | netpyne/network/pop.py | Pop.createCells | def createCells(self):
'''Function to instantiate Cell objects based on the characteristics of this population'''
# add individual cells
if 'cellsList' in self.tags:
cells = self.createCellsList()
# create cells based on fixed number of cells
elif 'numCells' in self.tags:
cells = self.createCellsFixedNum()
# create cells based on density (optional ynorm-dep)
elif 'density' in self.tags:
cells = self.createCellsDensity()
# create cells based on density (optional ynorm-dep)
elif 'gridSpacing' in self.tags:
cells = self.createCellsGrid()
# not enough tags to create cells
else:
self.tags['numCells'] = 1
print('Warninig: number or density of cells not specified for population %s; defaulting to numCells = 1' % (self.tags['pop']))
cells = self.createCellsFixedNum()
return cells | python | def createCells(self):
'''Function to instantiate Cell objects based on the characteristics of this population'''
# add individual cells
if 'cellsList' in self.tags:
cells = self.createCellsList()
# create cells based on fixed number of cells
elif 'numCells' in self.tags:
cells = self.createCellsFixedNum()
# create cells based on density (optional ynorm-dep)
elif 'density' in self.tags:
cells = self.createCellsDensity()
# create cells based on density (optional ynorm-dep)
elif 'gridSpacing' in self.tags:
cells = self.createCellsGrid()
# not enough tags to create cells
else:
self.tags['numCells'] = 1
print('Warninig: number or density of cells not specified for population %s; defaulting to numCells = 1' % (self.tags['pop']))
cells = self.createCellsFixedNum()
return cells | [
"def",
"createCells",
"(",
"self",
")",
":",
"# add individual cells",
"if",
"'cellsList'",
"in",
"self",
".",
"tags",
":",
"cells",
"=",
"self",
".",
"createCellsList",
"(",
")",
"# create cells based on fixed number of cells",
"elif",
"'numCells'",
"in",
"self",
".",
"tags",
":",
"cells",
"=",
"self",
".",
"createCellsFixedNum",
"(",
")",
"# create cells based on density (optional ynorm-dep)",
"elif",
"'density'",
"in",
"self",
".",
"tags",
":",
"cells",
"=",
"self",
".",
"createCellsDensity",
"(",
")",
"# create cells based on density (optional ynorm-dep)",
"elif",
"'gridSpacing'",
"in",
"self",
".",
"tags",
":",
"cells",
"=",
"self",
".",
"createCellsGrid",
"(",
")",
"# not enough tags to create cells",
"else",
":",
"self",
".",
"tags",
"[",
"'numCells'",
"]",
"=",
"1",
"print",
"(",
"'Warninig: number or density of cells not specified for population %s; defaulting to numCells = 1'",
"%",
"(",
"self",
".",
"tags",
"[",
"'pop'",
"]",
")",
")",
"cells",
"=",
"self",
".",
"createCellsFixedNum",
"(",
")",
"return",
"cells"
] | Function to instantiate Cell objects based on the characteristics of this population | [
"Function",
"to",
"instantiate",
"Cell",
"objects",
"based",
"on",
"the",
"characteristics",
"of",
"this",
"population"
] | edb67b5098b2e7923d55010ded59ad1bf75c0f18 | https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/network/pop.py#L64-L88 | train | 237,611 |
Neurosim-lab/netpyne | netpyne/network/pop.py | Pop.createCellsList | def createCellsList (self):
''' Create population cells based on list of individual cells'''
from .. import sim
cells = []
self.tags['numCells'] = len(self.tags['cellsList'])
for i in self._distributeCells(len(self.tags['cellsList']))[sim.rank]:
#if 'cellModel' in self.tags['cellsList'][i]:
# self.cellModelClass = getattr(f, self.tags['cellsList'][i]['cellModel']) # select cell class to instantiate cells based on the cellModel tags
gid = sim.net.lastGid+i
self.cellGids.append(gid) # add gid list of cells belonging to this population - not needed?
cellTags = {k: v for (k, v) in self.tags.items() if k in sim.net.params.popTagsCopiedToCells} # copy all pop tags to cell tags, except those that are pop-specific
cellTags['pop'] = self.tags['pop']
cellTags.update(self.tags['cellsList'][i]) # add tags specific to this cells
for coord in ['x','y','z']:
if coord in cellTags: # if absolute coord exists
cellTags[coord+'norm'] = cellTags[coord]/getattr(sim.net.params, 'size'+coord.upper()) # calculate norm coord
elif coord+'norm' in cellTags: # elif norm coord exists
cellTags[coord] = cellTags[coord+'norm']*getattr(sim.net.params, 'size'+coord.upper()) # calculate norm coord
else:
cellTags[coord+'norm'] = cellTags[coord] = 0
if 'cellModel' in self.tags.keys() and self.tags['cellModel'] == 'Vecstim': # if VecStim, copy spike times to params
cellTags['params']['spkTimes'] = self.tags['cellsList'][i]['spkTimes']
cells.append(self.cellModelClass(gid, cellTags)) # instantiate Cell object
if sim.cfg.verbose: print(('Cell %d/%d (gid=%d) of pop %d, on node %d, '%(i, self.tags['numCells']-1, gid, i, sim.rank)))
sim.net.lastGid = sim.net.lastGid + len(self.tags['cellsList'])
return cells | python | def createCellsList (self):
''' Create population cells based on list of individual cells'''
from .. import sim
cells = []
self.tags['numCells'] = len(self.tags['cellsList'])
for i in self._distributeCells(len(self.tags['cellsList']))[sim.rank]:
#if 'cellModel' in self.tags['cellsList'][i]:
# self.cellModelClass = getattr(f, self.tags['cellsList'][i]['cellModel']) # select cell class to instantiate cells based on the cellModel tags
gid = sim.net.lastGid+i
self.cellGids.append(gid) # add gid list of cells belonging to this population - not needed?
cellTags = {k: v for (k, v) in self.tags.items() if k in sim.net.params.popTagsCopiedToCells} # copy all pop tags to cell tags, except those that are pop-specific
cellTags['pop'] = self.tags['pop']
cellTags.update(self.tags['cellsList'][i]) # add tags specific to this cells
for coord in ['x','y','z']:
if coord in cellTags: # if absolute coord exists
cellTags[coord+'norm'] = cellTags[coord]/getattr(sim.net.params, 'size'+coord.upper()) # calculate norm coord
elif coord+'norm' in cellTags: # elif norm coord exists
cellTags[coord] = cellTags[coord+'norm']*getattr(sim.net.params, 'size'+coord.upper()) # calculate norm coord
else:
cellTags[coord+'norm'] = cellTags[coord] = 0
if 'cellModel' in self.tags.keys() and self.tags['cellModel'] == 'Vecstim': # if VecStim, copy spike times to params
cellTags['params']['spkTimes'] = self.tags['cellsList'][i]['spkTimes']
cells.append(self.cellModelClass(gid, cellTags)) # instantiate Cell object
if sim.cfg.verbose: print(('Cell %d/%d (gid=%d) of pop %d, on node %d, '%(i, self.tags['numCells']-1, gid, i, sim.rank)))
sim.net.lastGid = sim.net.lastGid + len(self.tags['cellsList'])
return cells | [
"def",
"createCellsList",
"(",
"self",
")",
":",
"from",
".",
".",
"import",
"sim",
"cells",
"=",
"[",
"]",
"self",
".",
"tags",
"[",
"'numCells'",
"]",
"=",
"len",
"(",
"self",
".",
"tags",
"[",
"'cellsList'",
"]",
")",
"for",
"i",
"in",
"self",
".",
"_distributeCells",
"(",
"len",
"(",
"self",
".",
"tags",
"[",
"'cellsList'",
"]",
")",
")",
"[",
"sim",
".",
"rank",
"]",
":",
"#if 'cellModel' in self.tags['cellsList'][i]:",
"# self.cellModelClass = getattr(f, self.tags['cellsList'][i]['cellModel']) # select cell class to instantiate cells based on the cellModel tags",
"gid",
"=",
"sim",
".",
"net",
".",
"lastGid",
"+",
"i",
"self",
".",
"cellGids",
".",
"append",
"(",
"gid",
")",
"# add gid list of cells belonging to this population - not needed?",
"cellTags",
"=",
"{",
"k",
":",
"v",
"for",
"(",
"k",
",",
"v",
")",
"in",
"self",
".",
"tags",
".",
"items",
"(",
")",
"if",
"k",
"in",
"sim",
".",
"net",
".",
"params",
".",
"popTagsCopiedToCells",
"}",
"# copy all pop tags to cell tags, except those that are pop-specific",
"cellTags",
"[",
"'pop'",
"]",
"=",
"self",
".",
"tags",
"[",
"'pop'",
"]",
"cellTags",
".",
"update",
"(",
"self",
".",
"tags",
"[",
"'cellsList'",
"]",
"[",
"i",
"]",
")",
"# add tags specific to this cells",
"for",
"coord",
"in",
"[",
"'x'",
",",
"'y'",
",",
"'z'",
"]",
":",
"if",
"coord",
"in",
"cellTags",
":",
"# if absolute coord exists",
"cellTags",
"[",
"coord",
"+",
"'norm'",
"]",
"=",
"cellTags",
"[",
"coord",
"]",
"/",
"getattr",
"(",
"sim",
".",
"net",
".",
"params",
",",
"'size'",
"+",
"coord",
".",
"upper",
"(",
")",
")",
"# calculate norm coord",
"elif",
"coord",
"+",
"'norm'",
"in",
"cellTags",
":",
"# elif norm coord exists",
"cellTags",
"[",
"coord",
"]",
"=",
"cellTags",
"[",
"coord",
"+",
"'norm'",
"]",
"*",
"getattr",
"(",
"sim",
".",
"net",
".",
"params",
",",
"'size'",
"+",
"coord",
".",
"upper",
"(",
")",
")",
"# calculate norm coord",
"else",
":",
"cellTags",
"[",
"coord",
"+",
"'norm'",
"]",
"=",
"cellTags",
"[",
"coord",
"]",
"=",
"0",
"if",
"'cellModel'",
"in",
"self",
".",
"tags",
".",
"keys",
"(",
")",
"and",
"self",
".",
"tags",
"[",
"'cellModel'",
"]",
"==",
"'Vecstim'",
":",
"# if VecStim, copy spike times to params",
"cellTags",
"[",
"'params'",
"]",
"[",
"'spkTimes'",
"]",
"=",
"self",
".",
"tags",
"[",
"'cellsList'",
"]",
"[",
"i",
"]",
"[",
"'spkTimes'",
"]",
"cells",
".",
"append",
"(",
"self",
".",
"cellModelClass",
"(",
"gid",
",",
"cellTags",
")",
")",
"# instantiate Cell object",
"if",
"sim",
".",
"cfg",
".",
"verbose",
":",
"print",
"(",
"(",
"'Cell %d/%d (gid=%d) of pop %d, on node %d, '",
"%",
"(",
"i",
",",
"self",
".",
"tags",
"[",
"'numCells'",
"]",
"-",
"1",
",",
"gid",
",",
"i",
",",
"sim",
".",
"rank",
")",
")",
")",
"sim",
".",
"net",
".",
"lastGid",
"=",
"sim",
".",
"net",
".",
"lastGid",
"+",
"len",
"(",
"self",
".",
"tags",
"[",
"'cellsList'",
"]",
")",
"return",
"cells"
] | Create population cells based on list of individual cells | [
"Create",
"population",
"cells",
"based",
"on",
"list",
"of",
"individual",
"cells"
] | edb67b5098b2e7923d55010ded59ad1bf75c0f18 | https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/network/pop.py#L275-L301 | train | 237,612 |
Neurosim-lab/netpyne | netpyne/sim/wrappers.py | create | def create (netParams=None, simConfig=None, output=False):
''' Sequence of commands to create network '''
from .. import sim
import __main__ as top
if not netParams: netParams = top.netParams
if not simConfig: simConfig = top.simConfig
sim.initialize(netParams, simConfig) # create network object and set cfg and net params
pops = sim.net.createPops() # instantiate network populations
cells = sim.net.createCells() # instantiate network cells based on defined populations
conns = sim.net.connectCells() # create connections between cells based on params
stims = sim.net.addStims() # add external stimulation to cells (IClamps etc)
rxd = sim.net.addRxD() # add reaction-diffusion (RxD)
simData = sim.setupRecording() # setup variables to record for each cell (spikes, V traces, etc)
if output: return (pops, cells, conns, rxd, stims, simData) | python | def create (netParams=None, simConfig=None, output=False):
''' Sequence of commands to create network '''
from .. import sim
import __main__ as top
if not netParams: netParams = top.netParams
if not simConfig: simConfig = top.simConfig
sim.initialize(netParams, simConfig) # create network object and set cfg and net params
pops = sim.net.createPops() # instantiate network populations
cells = sim.net.createCells() # instantiate network cells based on defined populations
conns = sim.net.connectCells() # create connections between cells based on params
stims = sim.net.addStims() # add external stimulation to cells (IClamps etc)
rxd = sim.net.addRxD() # add reaction-diffusion (RxD)
simData = sim.setupRecording() # setup variables to record for each cell (spikes, V traces, etc)
if output: return (pops, cells, conns, rxd, stims, simData) | [
"def",
"create",
"(",
"netParams",
"=",
"None",
",",
"simConfig",
"=",
"None",
",",
"output",
"=",
"False",
")",
":",
"from",
".",
".",
"import",
"sim",
"import",
"__main__",
"as",
"top",
"if",
"not",
"netParams",
":",
"netParams",
"=",
"top",
".",
"netParams",
"if",
"not",
"simConfig",
":",
"simConfig",
"=",
"top",
".",
"simConfig",
"sim",
".",
"initialize",
"(",
"netParams",
",",
"simConfig",
")",
"# create network object and set cfg and net params",
"pops",
"=",
"sim",
".",
"net",
".",
"createPops",
"(",
")",
"# instantiate network populations",
"cells",
"=",
"sim",
".",
"net",
".",
"createCells",
"(",
")",
"# instantiate network cells based on defined populations",
"conns",
"=",
"sim",
".",
"net",
".",
"connectCells",
"(",
")",
"# create connections between cells based on params",
"stims",
"=",
"sim",
".",
"net",
".",
"addStims",
"(",
")",
"# add external stimulation to cells (IClamps etc)",
"rxd",
"=",
"sim",
".",
"net",
".",
"addRxD",
"(",
")",
"# add reaction-diffusion (RxD)",
"simData",
"=",
"sim",
".",
"setupRecording",
"(",
")",
"# setup variables to record for each cell (spikes, V traces, etc)",
"if",
"output",
":",
"return",
"(",
"pops",
",",
"cells",
",",
"conns",
",",
"rxd",
",",
"stims",
",",
"simData",
")"
] | Sequence of commands to create network | [
"Sequence",
"of",
"commands",
"to",
"create",
"network"
] | edb67b5098b2e7923d55010ded59ad1bf75c0f18 | https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/sim/wrappers.py#L19-L34 | train | 237,613 |
Neurosim-lab/netpyne | netpyne/sim/wrappers.py | intervalSimulate | def intervalSimulate (interval):
''' Sequence of commands to simulate network '''
from .. import sim
sim.runSimWithIntervalFunc(interval, sim.intervalSave) # run parallel Neuron simulation
#this gather is justa merging of files
sim.fileGather() | python | def intervalSimulate (interval):
''' Sequence of commands to simulate network '''
from .. import sim
sim.runSimWithIntervalFunc(interval, sim.intervalSave) # run parallel Neuron simulation
#this gather is justa merging of files
sim.fileGather() | [
"def",
"intervalSimulate",
"(",
"interval",
")",
":",
"from",
".",
".",
"import",
"sim",
"sim",
".",
"runSimWithIntervalFunc",
"(",
"interval",
",",
"sim",
".",
"intervalSave",
")",
"# run parallel Neuron simulation ",
"#this gather is justa merging of files",
"sim",
".",
"fileGather",
"(",
")"
] | Sequence of commands to simulate network | [
"Sequence",
"of",
"commands",
"to",
"simulate",
"network"
] | edb67b5098b2e7923d55010ded59ad1bf75c0f18 | https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/sim/wrappers.py#L49-L54 | train | 237,614 |
Neurosim-lab/netpyne | netpyne/sim/wrappers.py | load | def load (filename, simConfig=None, output=False, instantiate=True, createNEURONObj=True):
''' Sequence of commands load, simulate and analyse network '''
from .. import sim
sim.initialize() # create network object and set cfg and net params
sim.cfg.createNEURONObj = createNEURONObj
sim.loadAll(filename, instantiate=instantiate, createNEURONObj=createNEURONObj)
if simConfig: sim.setSimCfg(simConfig) # set after to replace potentially loaded cfg
if len(sim.net.cells) == 0 and instantiate:
pops = sim.net.createPops() # instantiate network populations
cells = sim.net.createCells() # instantiate network cells based on defined populations
conns = sim.net.connectCells() # create connections between cells based on params
stims = sim.net.addStims() # add external stimulation to cells (IClamps etc)
rxd = sim.net.addRxD() # add reaction-diffusion (RxD)
simData = sim.setupRecording() # setup variables to record for each cell (spikes, V traces, etc)
if output:
try:
return (pops, cells, conns, stims, rxd, simData)
except:
pass | python | def load (filename, simConfig=None, output=False, instantiate=True, createNEURONObj=True):
''' Sequence of commands load, simulate and analyse network '''
from .. import sim
sim.initialize() # create network object and set cfg and net params
sim.cfg.createNEURONObj = createNEURONObj
sim.loadAll(filename, instantiate=instantiate, createNEURONObj=createNEURONObj)
if simConfig: sim.setSimCfg(simConfig) # set after to replace potentially loaded cfg
if len(sim.net.cells) == 0 and instantiate:
pops = sim.net.createPops() # instantiate network populations
cells = sim.net.createCells() # instantiate network cells based on defined populations
conns = sim.net.connectCells() # create connections between cells based on params
stims = sim.net.addStims() # add external stimulation to cells (IClamps etc)
rxd = sim.net.addRxD() # add reaction-diffusion (RxD)
simData = sim.setupRecording() # setup variables to record for each cell (spikes, V traces, etc)
if output:
try:
return (pops, cells, conns, stims, rxd, simData)
except:
pass | [
"def",
"load",
"(",
"filename",
",",
"simConfig",
"=",
"None",
",",
"output",
"=",
"False",
",",
"instantiate",
"=",
"True",
",",
"createNEURONObj",
"=",
"True",
")",
":",
"from",
".",
".",
"import",
"sim",
"sim",
".",
"initialize",
"(",
")",
"# create network object and set cfg and net params",
"sim",
".",
"cfg",
".",
"createNEURONObj",
"=",
"createNEURONObj",
"sim",
".",
"loadAll",
"(",
"filename",
",",
"instantiate",
"=",
"instantiate",
",",
"createNEURONObj",
"=",
"createNEURONObj",
")",
"if",
"simConfig",
":",
"sim",
".",
"setSimCfg",
"(",
"simConfig",
")",
"# set after to replace potentially loaded cfg",
"if",
"len",
"(",
"sim",
".",
"net",
".",
"cells",
")",
"==",
"0",
"and",
"instantiate",
":",
"pops",
"=",
"sim",
".",
"net",
".",
"createPops",
"(",
")",
"# instantiate network populations",
"cells",
"=",
"sim",
".",
"net",
".",
"createCells",
"(",
")",
"# instantiate network cells based on defined populations",
"conns",
"=",
"sim",
".",
"net",
".",
"connectCells",
"(",
")",
"# create connections between cells based on params",
"stims",
"=",
"sim",
".",
"net",
".",
"addStims",
"(",
")",
"# add external stimulation to cells (IClamps etc)",
"rxd",
"=",
"sim",
".",
"net",
".",
"addRxD",
"(",
")",
"# add reaction-diffusion (RxD)",
"simData",
"=",
"sim",
".",
"setupRecording",
"(",
")",
"# setup variables to record for each cell (spikes, V traces, etc)",
"if",
"output",
":",
"try",
":",
"return",
"(",
"pops",
",",
"cells",
",",
"conns",
",",
"stims",
",",
"rxd",
",",
"simData",
")",
"except",
":",
"pass"
] | Sequence of commands load, simulate and analyse network | [
"Sequence",
"of",
"commands",
"load",
"simulate",
"and",
"analyse",
"network"
] | edb67b5098b2e7923d55010ded59ad1bf75c0f18 | https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/sim/wrappers.py#L116-L136 | train | 237,615 |
Neurosim-lab/netpyne | netpyne/sim/wrappers.py | createExportNeuroML2 | def createExportNeuroML2 (netParams=None, simConfig=None, reference=None, connections=True, stimulations=True, output=False, format='xml'):
''' Sequence of commands to create and export network to NeuroML2 '''
from .. import sim
import __main__ as top
if not netParams: netParams = top.netParams
if not simConfig: simConfig = top.simConfig
sim.initialize(netParams, simConfig) # create network object and set cfg and net params
pops = sim.net.createPops() # instantiate network populations
cells = sim.net.createCells() # instantiate network cells based on defined populations
conns = sim.net.connectCells() # create connections between cells based on params
stims = sim.net.addStims() # add external stimulation to cells (IClamps etc)
rxd = sim.net.addRxD() # add reaction-diffusion (RxD)
simData = sim.setupRecording() # setup variables to record for each cell (spikes, V traces, etc)
sim.exportNeuroML2(reference,connections,stimulations,format) # export cells and connectivity to NeuroML 2 format
if output: return (pops, cells, conns, stims, rxd, simData) | python | def createExportNeuroML2 (netParams=None, simConfig=None, reference=None, connections=True, stimulations=True, output=False, format='xml'):
''' Sequence of commands to create and export network to NeuroML2 '''
from .. import sim
import __main__ as top
if not netParams: netParams = top.netParams
if not simConfig: simConfig = top.simConfig
sim.initialize(netParams, simConfig) # create network object and set cfg and net params
pops = sim.net.createPops() # instantiate network populations
cells = sim.net.createCells() # instantiate network cells based on defined populations
conns = sim.net.connectCells() # create connections between cells based on params
stims = sim.net.addStims() # add external stimulation to cells (IClamps etc)
rxd = sim.net.addRxD() # add reaction-diffusion (RxD)
simData = sim.setupRecording() # setup variables to record for each cell (spikes, V traces, etc)
sim.exportNeuroML2(reference,connections,stimulations,format) # export cells and connectivity to NeuroML 2 format
if output: return (pops, cells, conns, stims, rxd, simData) | [
"def",
"createExportNeuroML2",
"(",
"netParams",
"=",
"None",
",",
"simConfig",
"=",
"None",
",",
"reference",
"=",
"None",
",",
"connections",
"=",
"True",
",",
"stimulations",
"=",
"True",
",",
"output",
"=",
"False",
",",
"format",
"=",
"'xml'",
")",
":",
"from",
".",
".",
"import",
"sim",
"import",
"__main__",
"as",
"top",
"if",
"not",
"netParams",
":",
"netParams",
"=",
"top",
".",
"netParams",
"if",
"not",
"simConfig",
":",
"simConfig",
"=",
"top",
".",
"simConfig",
"sim",
".",
"initialize",
"(",
"netParams",
",",
"simConfig",
")",
"# create network object and set cfg and net params",
"pops",
"=",
"sim",
".",
"net",
".",
"createPops",
"(",
")",
"# instantiate network populations",
"cells",
"=",
"sim",
".",
"net",
".",
"createCells",
"(",
")",
"# instantiate network cells based on defined populations",
"conns",
"=",
"sim",
".",
"net",
".",
"connectCells",
"(",
")",
"# create connections between cells based on params",
"stims",
"=",
"sim",
".",
"net",
".",
"addStims",
"(",
")",
"# add external stimulation to cells (IClamps etc)",
"rxd",
"=",
"sim",
".",
"net",
".",
"addRxD",
"(",
")",
"# add reaction-diffusion (RxD)",
"simData",
"=",
"sim",
".",
"setupRecording",
"(",
")",
"# setup variables to record for each cell (spikes, V traces, etc)",
"sim",
".",
"exportNeuroML2",
"(",
"reference",
",",
"connections",
",",
"stimulations",
",",
"format",
")",
"# export cells and connectivity to NeuroML 2 format",
"if",
"output",
":",
"return",
"(",
"pops",
",",
"cells",
",",
"conns",
",",
"stims",
",",
"rxd",
",",
"simData",
")"
] | Sequence of commands to create and export network to NeuroML2 | [
"Sequence",
"of",
"commands",
"to",
"create",
"and",
"export",
"network",
"to",
"NeuroML2"
] | edb67b5098b2e7923d55010ded59ad1bf75c0f18 | https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/sim/wrappers.py#L164-L180 | train | 237,616 |
Neurosim-lab/netpyne | netpyne/analysis/utils.py | exception | def exception(function):
"""
A decorator that wraps the passed in function and prints exception should one occur
"""
@functools.wraps(function)
def wrapper(*args, **kwargs):
try:
return function(*args, **kwargs)
except Exception as e:
# print
err = "There was an exception in %s():"%(function.__name__)
print(("%s \n %s \n%s"%(err,e,sys.exc_info())))
return -1
return wrapper | python | def exception(function):
"""
A decorator that wraps the passed in function and prints exception should one occur
"""
@functools.wraps(function)
def wrapper(*args, **kwargs):
try:
return function(*args, **kwargs)
except Exception as e:
# print
err = "There was an exception in %s():"%(function.__name__)
print(("%s \n %s \n%s"%(err,e,sys.exc_info())))
return -1
return wrapper | [
"def",
"exception",
"(",
"function",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"function",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
"as",
"e",
":",
"# print ",
"err",
"=",
"\"There was an exception in %s():\"",
"%",
"(",
"function",
".",
"__name__",
")",
"print",
"(",
"(",
"\"%s \\n %s \\n%s\"",
"%",
"(",
"err",
",",
"e",
",",
"sys",
".",
"exc_info",
"(",
")",
")",
")",
")",
"return",
"-",
"1",
"return",
"wrapper"
] | A decorator that wraps the passed in function and prints exception should one occur | [
"A",
"decorator",
"that",
"wraps",
"the",
"passed",
"in",
"function",
"and",
"prints",
"exception",
"should",
"one",
"occur"
] | edb67b5098b2e7923d55010ded59ad1bf75c0f18 | https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/analysis/utils.py#L54-L68 | train | 237,617 |
Neurosim-lab/netpyne | netpyne/analysis/utils.py | getSpktSpkid | def getSpktSpkid(cellGids=[], timeRange=None, allCells=False):
'''return spike ids and times; with allCells=True just need to identify slice of time so can omit cellGids'''
from .. import sim
import pandas as pd
try: # Pandas 0.24 and later
from pandas import _lib as pandaslib
except: # Pandas 0.23 and earlier
from pandas import lib as pandaslib
df = pd.DataFrame(pandaslib.to_object_array([sim.allSimData['spkt'], sim.allSimData['spkid']]).transpose(), columns=['spkt', 'spkid'])
#df = pd.DataFrame(pd.lib.to_object_array([sim.allSimData['spkt'], sim.allSimData['spkid']]).transpose(), columns=['spkt', 'spkid'])
if timeRange:
min, max = [int(df['spkt'].searchsorted(timeRange[i])) for i in range(2)] # binary search faster than query
else: # timeRange None or empty list means all times
min, max = 0, len(df)
if len(cellGids)==0 or allCells: # get all by either using flag or giving empty list -- can get rid of the flag
sel = df[min:max]
else:
sel = df[min:max].query('spkid in @cellGids')
return sel, sel['spkt'].tolist(), sel['spkid'].tolist() | python | def getSpktSpkid(cellGids=[], timeRange=None, allCells=False):
'''return spike ids and times; with allCells=True just need to identify slice of time so can omit cellGids'''
from .. import sim
import pandas as pd
try: # Pandas 0.24 and later
from pandas import _lib as pandaslib
except: # Pandas 0.23 and earlier
from pandas import lib as pandaslib
df = pd.DataFrame(pandaslib.to_object_array([sim.allSimData['spkt'], sim.allSimData['spkid']]).transpose(), columns=['spkt', 'spkid'])
#df = pd.DataFrame(pd.lib.to_object_array([sim.allSimData['spkt'], sim.allSimData['spkid']]).transpose(), columns=['spkt', 'spkid'])
if timeRange:
min, max = [int(df['spkt'].searchsorted(timeRange[i])) for i in range(2)] # binary search faster than query
else: # timeRange None or empty list means all times
min, max = 0, len(df)
if len(cellGids)==0 or allCells: # get all by either using flag or giving empty list -- can get rid of the flag
sel = df[min:max]
else:
sel = df[min:max].query('spkid in @cellGids')
return sel, sel['spkt'].tolist(), sel['spkid'].tolist() | [
"def",
"getSpktSpkid",
"(",
"cellGids",
"=",
"[",
"]",
",",
"timeRange",
"=",
"None",
",",
"allCells",
"=",
"False",
")",
":",
"from",
".",
".",
"import",
"sim",
"import",
"pandas",
"as",
"pd",
"try",
":",
"# Pandas 0.24 and later",
"from",
"pandas",
"import",
"_lib",
"as",
"pandaslib",
"except",
":",
"# Pandas 0.23 and earlier",
"from",
"pandas",
"import",
"lib",
"as",
"pandaslib",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"pandaslib",
".",
"to_object_array",
"(",
"[",
"sim",
".",
"allSimData",
"[",
"'spkt'",
"]",
",",
"sim",
".",
"allSimData",
"[",
"'spkid'",
"]",
"]",
")",
".",
"transpose",
"(",
")",
",",
"columns",
"=",
"[",
"'spkt'",
",",
"'spkid'",
"]",
")",
"#df = pd.DataFrame(pd.lib.to_object_array([sim.allSimData['spkt'], sim.allSimData['spkid']]).transpose(), columns=['spkt', 'spkid'])",
"if",
"timeRange",
":",
"min",
",",
"max",
"=",
"[",
"int",
"(",
"df",
"[",
"'spkt'",
"]",
".",
"searchsorted",
"(",
"timeRange",
"[",
"i",
"]",
")",
")",
"for",
"i",
"in",
"range",
"(",
"2",
")",
"]",
"# binary search faster than query",
"else",
":",
"# timeRange None or empty list means all times",
"min",
",",
"max",
"=",
"0",
",",
"len",
"(",
"df",
")",
"if",
"len",
"(",
"cellGids",
")",
"==",
"0",
"or",
"allCells",
":",
"# get all by either using flag or giving empty list -- can get rid of the flag",
"sel",
"=",
"df",
"[",
"min",
":",
"max",
"]",
"else",
":",
"sel",
"=",
"df",
"[",
"min",
":",
"max",
"]",
".",
"query",
"(",
"'spkid in @cellGids'",
")",
"return",
"sel",
",",
"sel",
"[",
"'spkt'",
"]",
".",
"tolist",
"(",
")",
",",
"sel",
"[",
"'spkid'",
"]",
".",
"tolist",
"(",
")"
] | return spike ids and times; with allCells=True just need to identify slice of time so can omit cellGids | [
"return",
"spike",
"ids",
"and",
"times",
";",
"with",
"allCells",
"=",
"True",
"just",
"need",
"to",
"identify",
"slice",
"of",
"time",
"so",
"can",
"omit",
"cellGids"
] | edb67b5098b2e7923d55010ded59ad1bf75c0f18 | https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/analysis/utils.py#L321-L341 | train | 237,618 |
Neurosim-lab/netpyne | netpyne/support/recxelectrode.py | RecXElectrode.calcTransferResistance | def calcTransferResistance(self, gid, seg_coords):
"""Precompute mapping from segment to electrode locations"""
sigma = 0.3 # mS/mm
# Value used in NEURON extracellular recording example ("extracellular_stim_and_rec")
# rho = 35.4 # ohm cm, squid axon cytoplasm = 2.8249e-2 S/cm = 0.028 S/cm = 0.0028 S/mm = 2.8 mS/mm
# rho_um = 35.4 * 0.01 = 35.4 / 1e6 * 1e4 = 0.354 Mohm um ~= 3 uS / um = 3000 uS / mm = 3 mS /mm
# equivalent sigma value (~3) is 10x larger than Allen (0.3)
# if use same sigma value, results are consistent
r05 = (seg_coords['p0'] + seg_coords['p1'])/2
dl = seg_coords['p1'] - seg_coords['p0']
nseg = r05.shape[1]
tr = np.zeros((self.nsites,nseg))
# tr_NEURON = np.zeros((self.nsites,nseg)) # used to compare with NEURON extracellular example
for j in range(self.nsites): # calculate mapping for each site on the electrode
rel = np.expand_dims(self.pos[:, j], axis=1) # coordinates of a j-th site on the electrode
rel_05 = rel - r05 # distance between electrode and segment centers
r2 = np.einsum('ij,ij->j', rel_05, rel_05) # compute dot product column-wise, the resulting array has as many columns as original
rlldl = np.einsum('ij,ij->j', rel_05, dl) # compute dot product column-wise, the resulting array has as many columns as original
dlmag = np.linalg.norm(dl, axis=0) # length of each segment
rll = abs(rlldl/dlmag) # component of r parallel to the segment axis it must be always positive
rT2 = r2 - rll**2 # square of perpendicular component
up = rll + dlmag/2
low = rll - dlmag/2
num = up + np.sqrt(up**2 + rT2)
den = low + np.sqrt(low**2 + rT2)
tr[j, :] = np.log(num/den)/dlmag # units of (1/um) use with imemb_ (total seg current)
# Consistent with NEURON extracellular recording example
# r = np.sqrt(rel_05[0,:]**2 + rel_05[1,:]**2 + rel_05[2,:]**2)
# tr_NEURON[j, :] = (rho / 4 / math.pi)*(1/r)*0.01
tr *= 1/(4*math.pi*sigma) # units: 1/um / (mS/mm) = mm/um / mS = 1e3 * kOhm = MOhm
self.transferResistances[gid] = tr | python | def calcTransferResistance(self, gid, seg_coords):
"""Precompute mapping from segment to electrode locations"""
sigma = 0.3 # mS/mm
# Value used in NEURON extracellular recording example ("extracellular_stim_and_rec")
# rho = 35.4 # ohm cm, squid axon cytoplasm = 2.8249e-2 S/cm = 0.028 S/cm = 0.0028 S/mm = 2.8 mS/mm
# rho_um = 35.4 * 0.01 = 35.4 / 1e6 * 1e4 = 0.354 Mohm um ~= 3 uS / um = 3000 uS / mm = 3 mS /mm
# equivalent sigma value (~3) is 10x larger than Allen (0.3)
# if use same sigma value, results are consistent
r05 = (seg_coords['p0'] + seg_coords['p1'])/2
dl = seg_coords['p1'] - seg_coords['p0']
nseg = r05.shape[1]
tr = np.zeros((self.nsites,nseg))
# tr_NEURON = np.zeros((self.nsites,nseg)) # used to compare with NEURON extracellular example
for j in range(self.nsites): # calculate mapping for each site on the electrode
rel = np.expand_dims(self.pos[:, j], axis=1) # coordinates of a j-th site on the electrode
rel_05 = rel - r05 # distance between electrode and segment centers
r2 = np.einsum('ij,ij->j', rel_05, rel_05) # compute dot product column-wise, the resulting array has as many columns as original
rlldl = np.einsum('ij,ij->j', rel_05, dl) # compute dot product column-wise, the resulting array has as many columns as original
dlmag = np.linalg.norm(dl, axis=0) # length of each segment
rll = abs(rlldl/dlmag) # component of r parallel to the segment axis it must be always positive
rT2 = r2 - rll**2 # square of perpendicular component
up = rll + dlmag/2
low = rll - dlmag/2
num = up + np.sqrt(up**2 + rT2)
den = low + np.sqrt(low**2 + rT2)
tr[j, :] = np.log(num/den)/dlmag # units of (1/um) use with imemb_ (total seg current)
# Consistent with NEURON extracellular recording example
# r = np.sqrt(rel_05[0,:]**2 + rel_05[1,:]**2 + rel_05[2,:]**2)
# tr_NEURON[j, :] = (rho / 4 / math.pi)*(1/r)*0.01
tr *= 1/(4*math.pi*sigma) # units: 1/um / (mS/mm) = mm/um / mS = 1e3 * kOhm = MOhm
self.transferResistances[gid] = tr | [
"def",
"calcTransferResistance",
"(",
"self",
",",
"gid",
",",
"seg_coords",
")",
":",
"sigma",
"=",
"0.3",
"# mS/mm ",
"# Value used in NEURON extracellular recording example (\"extracellular_stim_and_rec\")",
"# rho = 35.4 # ohm cm, squid axon cytoplasm = 2.8249e-2 S/cm = 0.028 S/cm = 0.0028 S/mm = 2.8 mS/mm ",
"# rho_um = 35.4 * 0.01 = 35.4 / 1e6 * 1e4 = 0.354 Mohm um ~= 3 uS / um = 3000 uS / mm = 3 mS /mm",
"# equivalent sigma value (~3) is 10x larger than Allen (0.3) ",
"# if use same sigma value, results are consistent",
"r05",
"=",
"(",
"seg_coords",
"[",
"'p0'",
"]",
"+",
"seg_coords",
"[",
"'p1'",
"]",
")",
"/",
"2",
"dl",
"=",
"seg_coords",
"[",
"'p1'",
"]",
"-",
"seg_coords",
"[",
"'p0'",
"]",
"nseg",
"=",
"r05",
".",
"shape",
"[",
"1",
"]",
"tr",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"nsites",
",",
"nseg",
")",
")",
"# tr_NEURON = np.zeros((self.nsites,nseg)) # used to compare with NEURON extracellular example",
"for",
"j",
"in",
"range",
"(",
"self",
".",
"nsites",
")",
":",
"# calculate mapping for each site on the electrode",
"rel",
"=",
"np",
".",
"expand_dims",
"(",
"self",
".",
"pos",
"[",
":",
",",
"j",
"]",
",",
"axis",
"=",
"1",
")",
"# coordinates of a j-th site on the electrode",
"rel_05",
"=",
"rel",
"-",
"r05",
"# distance between electrode and segment centers",
"r2",
"=",
"np",
".",
"einsum",
"(",
"'ij,ij->j'",
",",
"rel_05",
",",
"rel_05",
")",
"# compute dot product column-wise, the resulting array has as many columns as original",
"rlldl",
"=",
"np",
".",
"einsum",
"(",
"'ij,ij->j'",
",",
"rel_05",
",",
"dl",
")",
"# compute dot product column-wise, the resulting array has as many columns as original",
"dlmag",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"dl",
",",
"axis",
"=",
"0",
")",
"# length of each segment",
"rll",
"=",
"abs",
"(",
"rlldl",
"/",
"dlmag",
")",
"# component of r parallel to the segment axis it must be always positive",
"rT2",
"=",
"r2",
"-",
"rll",
"**",
"2",
"# square of perpendicular component",
"up",
"=",
"rll",
"+",
"dlmag",
"/",
"2",
"low",
"=",
"rll",
"-",
"dlmag",
"/",
"2",
"num",
"=",
"up",
"+",
"np",
".",
"sqrt",
"(",
"up",
"**",
"2",
"+",
"rT2",
")",
"den",
"=",
"low",
"+",
"np",
".",
"sqrt",
"(",
"low",
"**",
"2",
"+",
"rT2",
")",
"tr",
"[",
"j",
",",
":",
"]",
"=",
"np",
".",
"log",
"(",
"num",
"/",
"den",
")",
"/",
"dlmag",
"# units of (1/um) use with imemb_ (total seg current)",
"# Consistent with NEURON extracellular recording example",
"# r = np.sqrt(rel_05[0,:]**2 + rel_05[1,:]**2 + rel_05[2,:]**2)",
"# tr_NEURON[j, :] = (rho / 4 / math.pi)*(1/r)*0.01",
"tr",
"*=",
"1",
"/",
"(",
"4",
"*",
"math",
".",
"pi",
"*",
"sigma",
")",
"# units: 1/um / (mS/mm) = mm/um / mS = 1e3 * kOhm = MOhm",
"self",
".",
"transferResistances",
"[",
"gid",
"]",
"=",
"tr"
] | Precompute mapping from segment to electrode locations | [
"Precompute",
"mapping",
"from",
"segment",
"to",
"electrode",
"locations"
] | edb67b5098b2e7923d55010ded59ad1bf75c0f18 | https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/support/recxelectrode.py#L67-L105 | train | 237,619 |
Neurosim-lab/netpyne | netpyne/conversion/excel.py | importConnFromExcel | def importConnFromExcel (fileName, sheetName):
''' Import connectivity rules from Excel sheet'''
import openpyxl as xl
# set columns
colPreTags = 0 # 'A'
colPostTags = 1 # 'B'
colConnFunc = 2 # 'C'
colSyn = 3 # 'D'
colProb = 5 # 'F'
colWeight = 6 # 'G'
colAnnot = 8 # 'I'
outFileName = fileName[:-5]+'_'+sheetName+'.py' # set output file name
connText = """## Generated using importConnFromExcel() function in params/utils.py \n\nnetParams['connParams'] = [] \n\n"""
# open excel file and sheet
wb = xl.load_workbook(fileName)
sheet = wb.get_sheet_by_name(sheetName)
numRows = sheet.get_highest_row()
with open(outFileName, 'w') as f:
f.write(connText) # write starting text
for row in range(1,numRows+1):
if sheet.cell(row=row, column=colProb).value: # if not empty row
print('Creating conn rule for row ' + str(row))
# read row values
pre = sheet.cell(row=row, column=colPreTags).value
post = sheet.cell(row=row, column=colPostTags).value
func = sheet.cell(row=row, column=colConnFunc).value
syn = sheet.cell(row=row, column=colSyn).value
prob = sheet.cell(row=row, column=colProb).value
weight = sheet.cell(row=row, column=colWeight).value
# write preTags
line = "netParams['connParams'].append({'preConds': {"
for i,cond in enumerate(pre.split(';')): # split into different conditions
if i>0: line = line + ", "
cond2 = cond.split('=') # split into key and value
line = line + "'" + cond2[0].replace(' ','') + "': " + cond2[1].replace(' ','') # generate line
line = line + "}" # end of preTags
# write postTags
line = line + ",\n'postConds': {"
for i,cond in enumerate(post.split(';')): # split into different conditions
if i>0: line = line + ", "
cond2 = cond.split('=') # split into key and value
line = line + "'" + cond2[0].replace(' ','') + "': " + cond2[1].replace(' ','') # generate line
line = line + "}" # end of postTags
line = line + ",\n'connFunc': '" + func + "'" # write connFunc
line = line + ",\n'synMech': '" + syn + "'" # write synReceptor
line = line + ",\n'probability': " + str(prob) # write prob
line = line + ",\n'weight': " + str(weight) # write prob
line = line + "})" # add closing brackets
line = line + '\n\n' # new line after each conn rule
f.write(line) | python | def importConnFromExcel (fileName, sheetName):
''' Import connectivity rules from Excel sheet'''
import openpyxl as xl
# set columns
colPreTags = 0 # 'A'
colPostTags = 1 # 'B'
colConnFunc = 2 # 'C'
colSyn = 3 # 'D'
colProb = 5 # 'F'
colWeight = 6 # 'G'
colAnnot = 8 # 'I'
outFileName = fileName[:-5]+'_'+sheetName+'.py' # set output file name
connText = """## Generated using importConnFromExcel() function in params/utils.py \n\nnetParams['connParams'] = [] \n\n"""
# open excel file and sheet
wb = xl.load_workbook(fileName)
sheet = wb.get_sheet_by_name(sheetName)
numRows = sheet.get_highest_row()
with open(outFileName, 'w') as f:
f.write(connText) # write starting text
for row in range(1,numRows+1):
if sheet.cell(row=row, column=colProb).value: # if not empty row
print('Creating conn rule for row ' + str(row))
# read row values
pre = sheet.cell(row=row, column=colPreTags).value
post = sheet.cell(row=row, column=colPostTags).value
func = sheet.cell(row=row, column=colConnFunc).value
syn = sheet.cell(row=row, column=colSyn).value
prob = sheet.cell(row=row, column=colProb).value
weight = sheet.cell(row=row, column=colWeight).value
# write preTags
line = "netParams['connParams'].append({'preConds': {"
for i,cond in enumerate(pre.split(';')): # split into different conditions
if i>0: line = line + ", "
cond2 = cond.split('=') # split into key and value
line = line + "'" + cond2[0].replace(' ','') + "': " + cond2[1].replace(' ','') # generate line
line = line + "}" # end of preTags
# write postTags
line = line + ",\n'postConds': {"
for i,cond in enumerate(post.split(';')): # split into different conditions
if i>0: line = line + ", "
cond2 = cond.split('=') # split into key and value
line = line + "'" + cond2[0].replace(' ','') + "': " + cond2[1].replace(' ','') # generate line
line = line + "}" # end of postTags
line = line + ",\n'connFunc': '" + func + "'" # write connFunc
line = line + ",\n'synMech': '" + syn + "'" # write synReceptor
line = line + ",\n'probability': " + str(prob) # write prob
line = line + ",\n'weight': " + str(weight) # write prob
line = line + "})" # add closing brackets
line = line + '\n\n' # new line after each conn rule
f.write(line) | [
"def",
"importConnFromExcel",
"(",
"fileName",
",",
"sheetName",
")",
":",
"import",
"openpyxl",
"as",
"xl",
"# set columns",
"colPreTags",
"=",
"0",
"# 'A'",
"colPostTags",
"=",
"1",
"# 'B'",
"colConnFunc",
"=",
"2",
"# 'C'",
"colSyn",
"=",
"3",
"# 'D'",
"colProb",
"=",
"5",
"# 'F'",
"colWeight",
"=",
"6",
"# 'G'",
"colAnnot",
"=",
"8",
"# 'I' ",
"outFileName",
"=",
"fileName",
"[",
":",
"-",
"5",
"]",
"+",
"'_'",
"+",
"sheetName",
"+",
"'.py'",
"# set output file name",
"connText",
"=",
"\"\"\"## Generated using importConnFromExcel() function in params/utils.py \\n\\nnetParams['connParams'] = [] \\n\\n\"\"\"",
"# open excel file and sheet",
"wb",
"=",
"xl",
".",
"load_workbook",
"(",
"fileName",
")",
"sheet",
"=",
"wb",
".",
"get_sheet_by_name",
"(",
"sheetName",
")",
"numRows",
"=",
"sheet",
".",
"get_highest_row",
"(",
")",
"with",
"open",
"(",
"outFileName",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"connText",
")",
"# write starting text",
"for",
"row",
"in",
"range",
"(",
"1",
",",
"numRows",
"+",
"1",
")",
":",
"if",
"sheet",
".",
"cell",
"(",
"row",
"=",
"row",
",",
"column",
"=",
"colProb",
")",
".",
"value",
":",
"# if not empty row",
"print",
"(",
"'Creating conn rule for row '",
"+",
"str",
"(",
"row",
")",
")",
"# read row values",
"pre",
"=",
"sheet",
".",
"cell",
"(",
"row",
"=",
"row",
",",
"column",
"=",
"colPreTags",
")",
".",
"value",
"post",
"=",
"sheet",
".",
"cell",
"(",
"row",
"=",
"row",
",",
"column",
"=",
"colPostTags",
")",
".",
"value",
"func",
"=",
"sheet",
".",
"cell",
"(",
"row",
"=",
"row",
",",
"column",
"=",
"colConnFunc",
")",
".",
"value",
"syn",
"=",
"sheet",
".",
"cell",
"(",
"row",
"=",
"row",
",",
"column",
"=",
"colSyn",
")",
".",
"value",
"prob",
"=",
"sheet",
".",
"cell",
"(",
"row",
"=",
"row",
",",
"column",
"=",
"colProb",
")",
".",
"value",
"weight",
"=",
"sheet",
".",
"cell",
"(",
"row",
"=",
"row",
",",
"column",
"=",
"colWeight",
")",
".",
"value",
"# write preTags",
"line",
"=",
"\"netParams['connParams'].append({'preConds': {\"",
"for",
"i",
",",
"cond",
"in",
"enumerate",
"(",
"pre",
".",
"split",
"(",
"';'",
")",
")",
":",
"# split into different conditions",
"if",
"i",
">",
"0",
":",
"line",
"=",
"line",
"+",
"\", \"",
"cond2",
"=",
"cond",
".",
"split",
"(",
"'='",
")",
"# split into key and value",
"line",
"=",
"line",
"+",
"\"'\"",
"+",
"cond2",
"[",
"0",
"]",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"+",
"\"': \"",
"+",
"cond2",
"[",
"1",
"]",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"# generate line",
"line",
"=",
"line",
"+",
"\"}\"",
"# end of preTags ",
"# write postTags",
"line",
"=",
"line",
"+",
"\",\\n'postConds': {\"",
"for",
"i",
",",
"cond",
"in",
"enumerate",
"(",
"post",
".",
"split",
"(",
"';'",
")",
")",
":",
"# split into different conditions",
"if",
"i",
">",
"0",
":",
"line",
"=",
"line",
"+",
"\", \"",
"cond2",
"=",
"cond",
".",
"split",
"(",
"'='",
")",
"# split into key and value",
"line",
"=",
"line",
"+",
"\"'\"",
"+",
"cond2",
"[",
"0",
"]",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"+",
"\"': \"",
"+",
"cond2",
"[",
"1",
"]",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"# generate line",
"line",
"=",
"line",
"+",
"\"}\"",
"# end of postTags ",
"line",
"=",
"line",
"+",
"\",\\n'connFunc': '\"",
"+",
"func",
"+",
"\"'\"",
"# write connFunc",
"line",
"=",
"line",
"+",
"\",\\n'synMech': '\"",
"+",
"syn",
"+",
"\"'\"",
"# write synReceptor",
"line",
"=",
"line",
"+",
"\",\\n'probability': \"",
"+",
"str",
"(",
"prob",
")",
"# write prob",
"line",
"=",
"line",
"+",
"\",\\n'weight': \"",
"+",
"str",
"(",
"weight",
")",
"# write prob",
"line",
"=",
"line",
"+",
"\"})\"",
"# add closing brackets",
"line",
"=",
"line",
"+",
"'\\n\\n'",
"# new line after each conn rule",
"f",
".",
"write",
"(",
"line",
")"
] | Import connectivity rules from Excel sheet | [
"Import",
"connectivity",
"rules",
"from",
"Excel",
"sheet"
] | edb67b5098b2e7923d55010ded59ad1bf75c0f18 | https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/conversion/excel.py#L19-L75 | train | 237,620 |
zerwes/hiyapyco | hiyapyco/odyldo.py | safe_dump | def safe_dump(data, stream=None, **kwds):
"""implementation of safe dumper using Ordered Dict Yaml Dumper"""
return yaml.dump(data, stream=stream, Dumper=ODYD, **kwds) | python | def safe_dump(data, stream=None, **kwds):
"""implementation of safe dumper using Ordered Dict Yaml Dumper"""
return yaml.dump(data, stream=stream, Dumper=ODYD, **kwds) | [
"def",
"safe_dump",
"(",
"data",
",",
"stream",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"return",
"yaml",
".",
"dump",
"(",
"data",
",",
"stream",
"=",
"stream",
",",
"Dumper",
"=",
"ODYD",
",",
"*",
"*",
"kwds",
")"
] | implementation of safe dumper using Ordered Dict Yaml Dumper | [
"implementation",
"of",
"safe",
"dumper",
"using",
"Ordered",
"Dict",
"Yaml",
"Dumper"
] | b0b42724cc13b1412f5bb5d92fd4c637d6615edb | https://github.com/zerwes/hiyapyco/blob/b0b42724cc13b1412f5bb5d92fd4c637d6615edb/hiyapyco/odyldo.py#L76-L78 | train | 237,621 |
zerwes/hiyapyco | hiyapyco/__init__.py | dump | def dump(data, **kwds):
"""dump the data as YAML"""
if _usedefaultyamlloader:
return yaml.safe_dump(data, **kwds)
else:
return odyldo.safe_dump(data, **kwds) | python | def dump(data, **kwds):
"""dump the data as YAML"""
if _usedefaultyamlloader:
return yaml.safe_dump(data, **kwds)
else:
return odyldo.safe_dump(data, **kwds) | [
"def",
"dump",
"(",
"data",
",",
"*",
"*",
"kwds",
")",
":",
"if",
"_usedefaultyamlloader",
":",
"return",
"yaml",
".",
"safe_dump",
"(",
"data",
",",
"*",
"*",
"kwds",
")",
"else",
":",
"return",
"odyldo",
".",
"safe_dump",
"(",
"data",
",",
"*",
"*",
"kwds",
")"
] | dump the data as YAML | [
"dump",
"the",
"data",
"as",
"YAML"
] | b0b42724cc13b1412f5bb5d92fd4c637d6615edb | https://github.com/zerwes/hiyapyco/blob/b0b42724cc13b1412f5bb5d92fd4c637d6615edb/hiyapyco/__init__.py#L413-L418 | train | 237,622 |
andycasey/ads | ads/search.py | Article.bibtex | def bibtex(self):
"""Return a BiBTeX entry for the current article."""
warnings.warn("bibtex should be queried with ads.ExportQuery(); You will "
"hit API ratelimits very quickly otherwise.", UserWarning)
return ExportQuery(bibcodes=self.bibcode, format="bibtex").execute() | python | def bibtex(self):
"""Return a BiBTeX entry for the current article."""
warnings.warn("bibtex should be queried with ads.ExportQuery(); You will "
"hit API ratelimits very quickly otherwise.", UserWarning)
return ExportQuery(bibcodes=self.bibcode, format="bibtex").execute() | [
"def",
"bibtex",
"(",
"self",
")",
":",
"warnings",
".",
"warn",
"(",
"\"bibtex should be queried with ads.ExportQuery(); You will \"",
"\"hit API ratelimits very quickly otherwise.\"",
",",
"UserWarning",
")",
"return",
"ExportQuery",
"(",
"bibcodes",
"=",
"self",
".",
"bibcode",
",",
"format",
"=",
"\"bibtex\"",
")",
".",
"execute",
"(",
")"
] | Return a BiBTeX entry for the current article. | [
"Return",
"a",
"BiBTeX",
"entry",
"for",
"the",
"current",
"article",
"."
] | 928415e202db80658cd8532fa4c3a00d0296b5c5 | https://github.com/andycasey/ads/blob/928415e202db80658cd8532fa4c3a00d0296b5c5/ads/search.py#L292-L296 | train | 237,623 |
andycasey/ads | examples/monthly-institute-publications/stromlo.py | get_pdf | def get_pdf(article, debug=False):
"""
Download an article PDF from arXiv.
:param article:
The ADS article to retrieve.
:type article:
:class:`ads.search.Article`
:returns:
The binary content of the requested PDF.
"""
print('Retrieving {0}'.format(article))
identifier = [_ for _ in article.identifier if 'arXiv' in _]
if identifier:
url = 'http://arXiv.org/pdf/{0}.{1}'.format(identifier[0][9:13],
''.join(_ for _ in identifier[0][14:] if _.isdigit()))
else:
# No arXiv version. Ask ADS to redirect us to the journal article.
params = {
'bibcode': article.bibcode,
'link_type': 'ARTICLE',
'db_key': 'AST'
}
url = requests.get('http://adsabs.harvard.edu/cgi-bin/nph-data_query',
params=params).url
q = requests.get(url)
if not q.ok:
print('Error retrieving {0}: {1} for {2}'.format(
article, q.status_code, url))
if debug: q.raise_for_status()
else: return None
# Check if the journal has given back forbidden HTML.
if q.content.endswith('</html>'):
print('Error retrieving {0}: 200 (access denied?) for {1}'.format(
article, url))
return None
return q.content | python | def get_pdf(article, debug=False):
"""
Download an article PDF from arXiv.
:param article:
The ADS article to retrieve.
:type article:
:class:`ads.search.Article`
:returns:
The binary content of the requested PDF.
"""
print('Retrieving {0}'.format(article))
identifier = [_ for _ in article.identifier if 'arXiv' in _]
if identifier:
url = 'http://arXiv.org/pdf/{0}.{1}'.format(identifier[0][9:13],
''.join(_ for _ in identifier[0][14:] if _.isdigit()))
else:
# No arXiv version. Ask ADS to redirect us to the journal article.
params = {
'bibcode': article.bibcode,
'link_type': 'ARTICLE',
'db_key': 'AST'
}
url = requests.get('http://adsabs.harvard.edu/cgi-bin/nph-data_query',
params=params).url
q = requests.get(url)
if not q.ok:
print('Error retrieving {0}: {1} for {2}'.format(
article, q.status_code, url))
if debug: q.raise_for_status()
else: return None
# Check if the journal has given back forbidden HTML.
if q.content.endswith('</html>'):
print('Error retrieving {0}: 200 (access denied?) for {1}'.format(
article, url))
return None
return q.content | [
"def",
"get_pdf",
"(",
"article",
",",
"debug",
"=",
"False",
")",
":",
"print",
"(",
"'Retrieving {0}'",
".",
"format",
"(",
"article",
")",
")",
"identifier",
"=",
"[",
"_",
"for",
"_",
"in",
"article",
".",
"identifier",
"if",
"'arXiv'",
"in",
"_",
"]",
"if",
"identifier",
":",
"url",
"=",
"'http://arXiv.org/pdf/{0}.{1}'",
".",
"format",
"(",
"identifier",
"[",
"0",
"]",
"[",
"9",
":",
"13",
"]",
",",
"''",
".",
"join",
"(",
"_",
"for",
"_",
"in",
"identifier",
"[",
"0",
"]",
"[",
"14",
":",
"]",
"if",
"_",
".",
"isdigit",
"(",
")",
")",
")",
"else",
":",
"# No arXiv version. Ask ADS to redirect us to the journal article.",
"params",
"=",
"{",
"'bibcode'",
":",
"article",
".",
"bibcode",
",",
"'link_type'",
":",
"'ARTICLE'",
",",
"'db_key'",
":",
"'AST'",
"}",
"url",
"=",
"requests",
".",
"get",
"(",
"'http://adsabs.harvard.edu/cgi-bin/nph-data_query'",
",",
"params",
"=",
"params",
")",
".",
"url",
"q",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"if",
"not",
"q",
".",
"ok",
":",
"print",
"(",
"'Error retrieving {0}: {1} for {2}'",
".",
"format",
"(",
"article",
",",
"q",
".",
"status_code",
",",
"url",
")",
")",
"if",
"debug",
":",
"q",
".",
"raise_for_status",
"(",
")",
"else",
":",
"return",
"None",
"# Check if the journal has given back forbidden HTML.",
"if",
"q",
".",
"content",
".",
"endswith",
"(",
"'</html>'",
")",
":",
"print",
"(",
"'Error retrieving {0}: 200 (access denied?) for {1}'",
".",
"format",
"(",
"article",
",",
"url",
")",
")",
"return",
"None",
"return",
"q",
".",
"content"
] | Download an article PDF from arXiv.
:param article:
The ADS article to retrieve.
:type article:
:class:`ads.search.Article`
:returns:
The binary content of the requested PDF. | [
"Download",
"an",
"article",
"PDF",
"from",
"arXiv",
"."
] | 928415e202db80658cd8532fa4c3a00d0296b5c5 | https://github.com/andycasey/ads/blob/928415e202db80658cd8532fa4c3a00d0296b5c5/examples/monthly-institute-publications/stromlo.py#L22-L64 | train | 237,624 |
andycasey/ads | examples/monthly-institute-publications/stromlo.py | summarise_pdfs | def summarise_pdfs(pdfs):
"""
Collate the first page from each of the PDFs provided into a single PDF.
:param pdfs:
The contents of several PDF files.
:type pdfs:
list of str
:returns:
The contents of single PDF, which can be written directly to disk.
"""
# Ignore None.
print('Summarising {0} articles ({1} had errors)'.format(
len(pdfs), pdfs.count(None)))
pdfs = [_ for _ in pdfs if _ is not None]
summary = PdfFileWriter()
for pdf in pdfs:
summary.addPage(PdfFileReader(StringIO(pdf)).getPage(0))
return summary | python | def summarise_pdfs(pdfs):
"""
Collate the first page from each of the PDFs provided into a single PDF.
:param pdfs:
The contents of several PDF files.
:type pdfs:
list of str
:returns:
The contents of single PDF, which can be written directly to disk.
"""
# Ignore None.
print('Summarising {0} articles ({1} had errors)'.format(
len(pdfs), pdfs.count(None)))
pdfs = [_ for _ in pdfs if _ is not None]
summary = PdfFileWriter()
for pdf in pdfs:
summary.addPage(PdfFileReader(StringIO(pdf)).getPage(0))
return summary | [
"def",
"summarise_pdfs",
"(",
"pdfs",
")",
":",
"# Ignore None.",
"print",
"(",
"'Summarising {0} articles ({1} had errors)'",
".",
"format",
"(",
"len",
"(",
"pdfs",
")",
",",
"pdfs",
".",
"count",
"(",
"None",
")",
")",
")",
"pdfs",
"=",
"[",
"_",
"for",
"_",
"in",
"pdfs",
"if",
"_",
"is",
"not",
"None",
"]",
"summary",
"=",
"PdfFileWriter",
"(",
")",
"for",
"pdf",
"in",
"pdfs",
":",
"summary",
".",
"addPage",
"(",
"PdfFileReader",
"(",
"StringIO",
"(",
"pdf",
")",
")",
".",
"getPage",
"(",
"0",
")",
")",
"return",
"summary"
] | Collate the first page from each of the PDFs provided into a single PDF.
:param pdfs:
The contents of several PDF files.
:type pdfs:
list of str
:returns:
The contents of single PDF, which can be written directly to disk. | [
"Collate",
"the",
"first",
"page",
"from",
"each",
"of",
"the",
"PDFs",
"provided",
"into",
"a",
"single",
"PDF",
"."
] | 928415e202db80658cd8532fa4c3a00d0296b5c5 | https://github.com/andycasey/ads/blob/928415e202db80658cd8532fa4c3a00d0296b5c5/examples/monthly-institute-publications/stromlo.py#L67-L89 | train | 237,625 |
andycasey/ads | ads/metrics.py | MetricsQuery.execute | def execute(self):
"""
Execute the http request to the metrics service
"""
self.response = MetricsResponse.load_http_response(
self.session.post(self.HTTP_ENDPOINT, data=self.json_payload)
)
return self.response.metrics | python | def execute(self):
"""
Execute the http request to the metrics service
"""
self.response = MetricsResponse.load_http_response(
self.session.post(self.HTTP_ENDPOINT, data=self.json_payload)
)
return self.response.metrics | [
"def",
"execute",
"(",
"self",
")",
":",
"self",
".",
"response",
"=",
"MetricsResponse",
".",
"load_http_response",
"(",
"self",
".",
"session",
".",
"post",
"(",
"self",
".",
"HTTP_ENDPOINT",
",",
"data",
"=",
"self",
".",
"json_payload",
")",
")",
"return",
"self",
".",
"response",
".",
"metrics"
] | Execute the http request to the metrics service | [
"Execute",
"the",
"http",
"request",
"to",
"the",
"metrics",
"service"
] | 928415e202db80658cd8532fa4c3a00d0296b5c5 | https://github.com/andycasey/ads/blob/928415e202db80658cd8532fa4c3a00d0296b5c5/ads/metrics.py#L47-L54 | train | 237,626 |
andycasey/ads | ads/base.py | _Singleton.get_info | def get_info(cls):
"""
Print all of the instantiated Singletons
"""
return '\n'.join(
[str(cls._instances[key]) for key in cls._instances]
) | python | def get_info(cls):
"""
Print all of the instantiated Singletons
"""
return '\n'.join(
[str(cls._instances[key]) for key in cls._instances]
) | [
"def",
"get_info",
"(",
"cls",
")",
":",
"return",
"'\\n'",
".",
"join",
"(",
"[",
"str",
"(",
"cls",
".",
"_instances",
"[",
"key",
"]",
")",
"for",
"key",
"in",
"cls",
".",
"_instances",
"]",
")"
] | Print all of the instantiated Singletons | [
"Print",
"all",
"of",
"the",
"instantiated",
"Singletons"
] | 928415e202db80658cd8532fa4c3a00d0296b5c5 | https://github.com/andycasey/ads/blob/928415e202db80658cd8532fa4c3a00d0296b5c5/ads/base.py#L25-L31 | train | 237,627 |
andycasey/ads | ads/base.py | APIResponse.load_http_response | def load_http_response(cls, http_response):
"""
This method should return an instantiated class and set its response
to the requests.Response object.
"""
if not http_response.ok:
raise APIResponseError(http_response.text)
c = cls(http_response)
c.response = http_response
RateLimits.getRateLimits(cls.__name__).set(c.response.headers)
return c | python | def load_http_response(cls, http_response):
"""
This method should return an instantiated class and set its response
to the requests.Response object.
"""
if not http_response.ok:
raise APIResponseError(http_response.text)
c = cls(http_response)
c.response = http_response
RateLimits.getRateLimits(cls.__name__).set(c.response.headers)
return c | [
"def",
"load_http_response",
"(",
"cls",
",",
"http_response",
")",
":",
"if",
"not",
"http_response",
".",
"ok",
":",
"raise",
"APIResponseError",
"(",
"http_response",
".",
"text",
")",
"c",
"=",
"cls",
"(",
"http_response",
")",
"c",
".",
"response",
"=",
"http_response",
"RateLimits",
".",
"getRateLimits",
"(",
"cls",
".",
"__name__",
")",
".",
"set",
"(",
"c",
".",
"response",
".",
"headers",
")",
"return",
"c"
] | This method should return an instantiated class and set its response
to the requests.Response object. | [
"This",
"method",
"should",
"return",
"an",
"instantiated",
"class",
"and",
"set",
"its",
"response",
"to",
"the",
"requests",
".",
"Response",
"object",
"."
] | 928415e202db80658cd8532fa4c3a00d0296b5c5 | https://github.com/andycasey/ads/blob/928415e202db80658cd8532fa4c3a00d0296b5c5/ads/base.py#L88-L100 | train | 237,628 |
andycasey/ads | ads/base.py | BaseQuery.token | def token(self):
"""
set the instance attribute `token` following the following logic,
stopping whenever a token is found. Raises NoTokenFound is no token
is found
- environment variables TOKEN_ENVIRON_VARS
- file containing plaintext as the contents in TOKEN_FILES
- ads.config.token
"""
if self._token is None:
for v in map(os.environ.get, TOKEN_ENVIRON_VARS):
if v is not None:
self._token = v
return self._token
for f in TOKEN_FILES:
try:
with open(f) as fp:
self._token = fp.read().strip()
return self._token
except IOError:
pass
if ads.config.token is not None:
self._token = ads.config.token
return self._token
warnings.warn("No token found", RuntimeWarning)
return self._token | python | def token(self):
"""
set the instance attribute `token` following the following logic,
stopping whenever a token is found. Raises NoTokenFound is no token
is found
- environment variables TOKEN_ENVIRON_VARS
- file containing plaintext as the contents in TOKEN_FILES
- ads.config.token
"""
if self._token is None:
for v in map(os.environ.get, TOKEN_ENVIRON_VARS):
if v is not None:
self._token = v
return self._token
for f in TOKEN_FILES:
try:
with open(f) as fp:
self._token = fp.read().strip()
return self._token
except IOError:
pass
if ads.config.token is not None:
self._token = ads.config.token
return self._token
warnings.warn("No token found", RuntimeWarning)
return self._token | [
"def",
"token",
"(",
"self",
")",
":",
"if",
"self",
".",
"_token",
"is",
"None",
":",
"for",
"v",
"in",
"map",
"(",
"os",
".",
"environ",
".",
"get",
",",
"TOKEN_ENVIRON_VARS",
")",
":",
"if",
"v",
"is",
"not",
"None",
":",
"self",
".",
"_token",
"=",
"v",
"return",
"self",
".",
"_token",
"for",
"f",
"in",
"TOKEN_FILES",
":",
"try",
":",
"with",
"open",
"(",
"f",
")",
"as",
"fp",
":",
"self",
".",
"_token",
"=",
"fp",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
"return",
"self",
".",
"_token",
"except",
"IOError",
":",
"pass",
"if",
"ads",
".",
"config",
".",
"token",
"is",
"not",
"None",
":",
"self",
".",
"_token",
"=",
"ads",
".",
"config",
".",
"token",
"return",
"self",
".",
"_token",
"warnings",
".",
"warn",
"(",
"\"No token found\"",
",",
"RuntimeWarning",
")",
"return",
"self",
".",
"_token"
] | set the instance attribute `token` following the following logic,
stopping whenever a token is found. Raises NoTokenFound is no token
is found
- environment variables TOKEN_ENVIRON_VARS
- file containing plaintext as the contents in TOKEN_FILES
- ads.config.token | [
"set",
"the",
"instance",
"attribute",
"token",
"following",
"the",
"following",
"logic",
"stopping",
"whenever",
"a",
"token",
"is",
"found",
".",
"Raises",
"NoTokenFound",
"is",
"no",
"token",
"is",
"found",
"-",
"environment",
"variables",
"TOKEN_ENVIRON_VARS",
"-",
"file",
"containing",
"plaintext",
"as",
"the",
"contents",
"in",
"TOKEN_FILES",
"-",
"ads",
".",
"config",
".",
"token"
] | 928415e202db80658cd8532fa4c3a00d0296b5c5 | https://github.com/andycasey/ads/blob/928415e202db80658cd8532fa4c3a00d0296b5c5/ads/base.py#L111-L136 | train | 237,629 |
andycasey/ads | ads/base.py | BaseQuery.session | def session(self):
"""
http session interface, transparent proxy to requests.session
"""
if self._session is None:
self._session = requests.session()
self._session.headers.update(
{
"Authorization": "Bearer {}".format(self.token),
"User-Agent": "ads-api-client/{}".format(__version__),
"Content-Type": "application/json",
}
)
return self._session | python | def session(self):
"""
http session interface, transparent proxy to requests.session
"""
if self._session is None:
self._session = requests.session()
self._session.headers.update(
{
"Authorization": "Bearer {}".format(self.token),
"User-Agent": "ads-api-client/{}".format(__version__),
"Content-Type": "application/json",
}
)
return self._session | [
"def",
"session",
"(",
"self",
")",
":",
"if",
"self",
".",
"_session",
"is",
"None",
":",
"self",
".",
"_session",
"=",
"requests",
".",
"session",
"(",
")",
"self",
".",
"_session",
".",
"headers",
".",
"update",
"(",
"{",
"\"Authorization\"",
":",
"\"Bearer {}\"",
".",
"format",
"(",
"self",
".",
"token",
")",
",",
"\"User-Agent\"",
":",
"\"ads-api-client/{}\"",
".",
"format",
"(",
"__version__",
")",
",",
"\"Content-Type\"",
":",
"\"application/json\"",
",",
"}",
")",
"return",
"self",
".",
"_session"
] | http session interface, transparent proxy to requests.session | [
"http",
"session",
"interface",
"transparent",
"proxy",
"to",
"requests",
".",
"session"
] | 928415e202db80658cd8532fa4c3a00d0296b5c5 | https://github.com/andycasey/ads/blob/928415e202db80658cd8532fa4c3a00d0296b5c5/ads/base.py#L143-L156 | train | 237,630 |
googledatalab/pydatalab | google/datalab/ml/_metrics.py | Metrics.from_csv | def from_csv(input_csv_pattern, headers=None, schema_file=None):
"""Create a Metrics instance from csv file pattern.
Args:
input_csv_pattern: Path to Csv file pattern (with no header). Can be local or GCS path.
headers: Csv headers.
schema_file: Path to a JSON file containing BigQuery schema. Used if "headers" is None.
Returns:
a Metrics instance.
Raises:
ValueError if both headers and schema_file are None.
"""
if headers is not None:
names = headers
elif schema_file is not None:
with _util.open_local_or_gcs(schema_file, mode='r') as f:
schema = json.load(f)
names = [x['name'] for x in schema]
else:
raise ValueError('Either headers or schema_file is needed')
metrics = Metrics(input_csv_pattern=input_csv_pattern, headers=names)
return metrics | python | def from_csv(input_csv_pattern, headers=None, schema_file=None):
"""Create a Metrics instance from csv file pattern.
Args:
input_csv_pattern: Path to Csv file pattern (with no header). Can be local or GCS path.
headers: Csv headers.
schema_file: Path to a JSON file containing BigQuery schema. Used if "headers" is None.
Returns:
a Metrics instance.
Raises:
ValueError if both headers and schema_file are None.
"""
if headers is not None:
names = headers
elif schema_file is not None:
with _util.open_local_or_gcs(schema_file, mode='r') as f:
schema = json.load(f)
names = [x['name'] for x in schema]
else:
raise ValueError('Either headers or schema_file is needed')
metrics = Metrics(input_csv_pattern=input_csv_pattern, headers=names)
return metrics | [
"def",
"from_csv",
"(",
"input_csv_pattern",
",",
"headers",
"=",
"None",
",",
"schema_file",
"=",
"None",
")",
":",
"if",
"headers",
"is",
"not",
"None",
":",
"names",
"=",
"headers",
"elif",
"schema_file",
"is",
"not",
"None",
":",
"with",
"_util",
".",
"open_local_or_gcs",
"(",
"schema_file",
",",
"mode",
"=",
"'r'",
")",
"as",
"f",
":",
"schema",
"=",
"json",
".",
"load",
"(",
"f",
")",
"names",
"=",
"[",
"x",
"[",
"'name'",
"]",
"for",
"x",
"in",
"schema",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"'Either headers or schema_file is needed'",
")",
"metrics",
"=",
"Metrics",
"(",
"input_csv_pattern",
"=",
"input_csv_pattern",
",",
"headers",
"=",
"names",
")",
"return",
"metrics"
] | Create a Metrics instance from csv file pattern.
Args:
input_csv_pattern: Path to Csv file pattern (with no header). Can be local or GCS path.
headers: Csv headers.
schema_file: Path to a JSON file containing BigQuery schema. Used if "headers" is None.
Returns:
a Metrics instance.
Raises:
ValueError if both headers and schema_file are None. | [
"Create",
"a",
"Metrics",
"instance",
"from",
"csv",
"file",
"pattern",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_metrics.py#L56-L81 | train | 237,631 |
googledatalab/pydatalab | google/datalab/ml/_metrics.py | Metrics.from_bigquery | def from_bigquery(sql):
"""Create a Metrics instance from a bigquery query or table.
Returns:
a Metrics instance.
Args:
sql: A BigQuery table name or a query.
"""
if isinstance(sql, bq.Query):
sql = sql._expanded_sql()
parts = sql.split('.')
if len(parts) == 1 or len(parts) > 3 or any(' ' in x for x in parts):
sql = '(' + sql + ')' # query, not a table name
else:
sql = '`' + sql + '`' # table name
metrics = Metrics(bigquery=sql)
return metrics | python | def from_bigquery(sql):
"""Create a Metrics instance from a bigquery query or table.
Returns:
a Metrics instance.
Args:
sql: A BigQuery table name or a query.
"""
if isinstance(sql, bq.Query):
sql = sql._expanded_sql()
parts = sql.split('.')
if len(parts) == 1 or len(parts) > 3 or any(' ' in x for x in parts):
sql = '(' + sql + ')' # query, not a table name
else:
sql = '`' + sql + '`' # table name
metrics = Metrics(bigquery=sql)
return metrics | [
"def",
"from_bigquery",
"(",
"sql",
")",
":",
"if",
"isinstance",
"(",
"sql",
",",
"bq",
".",
"Query",
")",
":",
"sql",
"=",
"sql",
".",
"_expanded_sql",
"(",
")",
"parts",
"=",
"sql",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"1",
"or",
"len",
"(",
"parts",
")",
">",
"3",
"or",
"any",
"(",
"' '",
"in",
"x",
"for",
"x",
"in",
"parts",
")",
":",
"sql",
"=",
"'('",
"+",
"sql",
"+",
"')'",
"# query, not a table name",
"else",
":",
"sql",
"=",
"'`'",
"+",
"sql",
"+",
"'`'",
"# table name",
"metrics",
"=",
"Metrics",
"(",
"bigquery",
"=",
"sql",
")",
"return",
"metrics"
] | Create a Metrics instance from a bigquery query or table.
Returns:
a Metrics instance.
Args:
sql: A BigQuery table name or a query. | [
"Create",
"a",
"Metrics",
"instance",
"from",
"a",
"bigquery",
"query",
"or",
"table",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_metrics.py#L84-L104 | train | 237,632 |
googledatalab/pydatalab | google/datalab/ml/_metrics.py | Metrics._get_data_from_csv_files | def _get_data_from_csv_files(self):
"""Get data from input csv files."""
all_df = []
for file_name in self._input_csv_files:
with _util.open_local_or_gcs(file_name, mode='r') as f:
all_df.append(pd.read_csv(f, names=self._headers))
df = pd.concat(all_df, ignore_index=True)
return df | python | def _get_data_from_csv_files(self):
"""Get data from input csv files."""
all_df = []
for file_name in self._input_csv_files:
with _util.open_local_or_gcs(file_name, mode='r') as f:
all_df.append(pd.read_csv(f, names=self._headers))
df = pd.concat(all_df, ignore_index=True)
return df | [
"def",
"_get_data_from_csv_files",
"(",
"self",
")",
":",
"all_df",
"=",
"[",
"]",
"for",
"file_name",
"in",
"self",
".",
"_input_csv_files",
":",
"with",
"_util",
".",
"open_local_or_gcs",
"(",
"file_name",
",",
"mode",
"=",
"'r'",
")",
"as",
"f",
":",
"all_df",
".",
"append",
"(",
"pd",
".",
"read_csv",
"(",
"f",
",",
"names",
"=",
"self",
".",
"_headers",
")",
")",
"df",
"=",
"pd",
".",
"concat",
"(",
"all_df",
",",
"ignore_index",
"=",
"True",
")",
"return",
"df"
] | Get data from input csv files. | [
"Get",
"data",
"from",
"input",
"csv",
"files",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_metrics.py#L106-L114 | train | 237,633 |
googledatalab/pydatalab | google/datalab/ml/_metrics.py | Metrics._get_data_from_bigquery | def _get_data_from_bigquery(self, queries):
"""Get data from bigquery table or query."""
all_df = []
for query in queries:
all_df.append(query.execute().result().to_dataframe())
df = pd.concat(all_df, ignore_index=True)
return df | python | def _get_data_from_bigquery(self, queries):
"""Get data from bigquery table or query."""
all_df = []
for query in queries:
all_df.append(query.execute().result().to_dataframe())
df = pd.concat(all_df, ignore_index=True)
return df | [
"def",
"_get_data_from_bigquery",
"(",
"self",
",",
"queries",
")",
":",
"all_df",
"=",
"[",
"]",
"for",
"query",
"in",
"queries",
":",
"all_df",
".",
"append",
"(",
"query",
".",
"execute",
"(",
")",
".",
"result",
"(",
")",
".",
"to_dataframe",
"(",
")",
")",
"df",
"=",
"pd",
".",
"concat",
"(",
"all_df",
",",
"ignore_index",
"=",
"True",
")",
"return",
"df"
] | Get data from bigquery table or query. | [
"Get",
"data",
"from",
"bigquery",
"table",
"or",
"query",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_metrics.py#L116-L123 | train | 237,634 |
googledatalab/pydatalab | google/datalab/bigquery/_udf.py | UDF._expanded_sql | def _expanded_sql(self):
"""Get the expanded BigQuery SQL string of this UDF
Returns
The expanded SQL string of this UDF
"""
if not self._sql:
self._sql = UDF._build_udf(self._name, self._code, self._return_type, self._params,
self._language, self._imports)
return self._sql | python | def _expanded_sql(self):
"""Get the expanded BigQuery SQL string of this UDF
Returns
The expanded SQL string of this UDF
"""
if not self._sql:
self._sql = UDF._build_udf(self._name, self._code, self._return_type, self._params,
self._language, self._imports)
return self._sql | [
"def",
"_expanded_sql",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_sql",
":",
"self",
".",
"_sql",
"=",
"UDF",
".",
"_build_udf",
"(",
"self",
".",
"_name",
",",
"self",
".",
"_code",
",",
"self",
".",
"_return_type",
",",
"self",
".",
"_params",
",",
"self",
".",
"_language",
",",
"self",
".",
"_imports",
")",
"return",
"self",
".",
"_sql"
] | Get the expanded BigQuery SQL string of this UDF
Returns
The expanded SQL string of this UDF | [
"Get",
"the",
"expanded",
"BigQuery",
"SQL",
"string",
"of",
"this",
"UDF"
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_udf.py#L65-L74 | train | 237,635 |
googledatalab/pydatalab | google/datalab/bigquery/_udf.py | UDF._build_udf | def _build_udf(name, code, return_type, params, language, imports):
"""Creates the UDF part of a BigQuery query using its pieces
Args:
name: the name of the javascript function
code: function body implementing the logic.
return_type: BigQuery data type of the function return. See supported data types in
the BigQuery docs
params: dictionary of parameter names and types
language: see list of supported languages in the BigQuery docs
imports: a list of GCS paths containing further support code.
"""
params = ','.join(['%s %s' % named_param for named_param in params])
imports = ','.join(['library="%s"' % i for i in imports])
if language.lower() == 'sql':
udf = 'CREATE TEMPORARY FUNCTION {name} ({params})\n' + \
'RETURNS {return_type}\n' + \
'AS (\n' + \
'{code}\n' + \
');'
else:
udf = 'CREATE TEMPORARY FUNCTION {name} ({params})\n' +\
'RETURNS {return_type}\n' + \
'LANGUAGE {language}\n' + \
'AS """\n' +\
'{code}\n' +\
'"""\n' +\
'OPTIONS (\n' +\
'{imports}\n' +\
');'
return udf.format(name=name, params=params, return_type=return_type,
language=language, code=code, imports=imports) | python | def _build_udf(name, code, return_type, params, language, imports):
"""Creates the UDF part of a BigQuery query using its pieces
Args:
name: the name of the javascript function
code: function body implementing the logic.
return_type: BigQuery data type of the function return. See supported data types in
the BigQuery docs
params: dictionary of parameter names and types
language: see list of supported languages in the BigQuery docs
imports: a list of GCS paths containing further support code.
"""
params = ','.join(['%s %s' % named_param for named_param in params])
imports = ','.join(['library="%s"' % i for i in imports])
if language.lower() == 'sql':
udf = 'CREATE TEMPORARY FUNCTION {name} ({params})\n' + \
'RETURNS {return_type}\n' + \
'AS (\n' + \
'{code}\n' + \
');'
else:
udf = 'CREATE TEMPORARY FUNCTION {name} ({params})\n' +\
'RETURNS {return_type}\n' + \
'LANGUAGE {language}\n' + \
'AS """\n' +\
'{code}\n' +\
'"""\n' +\
'OPTIONS (\n' +\
'{imports}\n' +\
');'
return udf.format(name=name, params=params, return_type=return_type,
language=language, code=code, imports=imports) | [
"def",
"_build_udf",
"(",
"name",
",",
"code",
",",
"return_type",
",",
"params",
",",
"language",
",",
"imports",
")",
":",
"params",
"=",
"','",
".",
"join",
"(",
"[",
"'%s %s'",
"%",
"named_param",
"for",
"named_param",
"in",
"params",
"]",
")",
"imports",
"=",
"','",
".",
"join",
"(",
"[",
"'library=\"%s\"'",
"%",
"i",
"for",
"i",
"in",
"imports",
"]",
")",
"if",
"language",
".",
"lower",
"(",
")",
"==",
"'sql'",
":",
"udf",
"=",
"'CREATE TEMPORARY FUNCTION {name} ({params})\\n'",
"+",
"'RETURNS {return_type}\\n'",
"+",
"'AS (\\n'",
"+",
"'{code}\\n'",
"+",
"');'",
"else",
":",
"udf",
"=",
"'CREATE TEMPORARY FUNCTION {name} ({params})\\n'",
"+",
"'RETURNS {return_type}\\n'",
"+",
"'LANGUAGE {language}\\n'",
"+",
"'AS \"\"\"\\n'",
"+",
"'{code}\\n'",
"+",
"'\"\"\"\\n'",
"+",
"'OPTIONS (\\n'",
"+",
"'{imports}\\n'",
"+",
"');'",
"return",
"udf",
".",
"format",
"(",
"name",
"=",
"name",
",",
"params",
"=",
"params",
",",
"return_type",
"=",
"return_type",
",",
"language",
"=",
"language",
",",
"code",
"=",
"code",
",",
"imports",
"=",
"imports",
")"
] | Creates the UDF part of a BigQuery query using its pieces
Args:
name: the name of the javascript function
code: function body implementing the logic.
return_type: BigQuery data type of the function return. See supported data types in
the BigQuery docs
params: dictionary of parameter names and types
language: see list of supported languages in the BigQuery docs
imports: a list of GCS paths containing further support code. | [
"Creates",
"the",
"UDF",
"part",
"of",
"a",
"BigQuery",
"query",
"using",
"its",
"pieces"
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_udf.py#L83-L116 | train | 237,636 |
googledatalab/pydatalab | google/datalab/storage/_bucket.py | BucketMetadata.created_on | def created_on(self):
"""The created timestamp of the bucket as a datetime.datetime."""
s = self._info.get('timeCreated', None)
return dateutil.parser.parse(s) if s else None | python | def created_on(self):
"""The created timestamp of the bucket as a datetime.datetime."""
s = self._info.get('timeCreated', None)
return dateutil.parser.parse(s) if s else None | [
"def",
"created_on",
"(",
"self",
")",
":",
"s",
"=",
"self",
".",
"_info",
".",
"get",
"(",
"'timeCreated'",
",",
"None",
")",
"return",
"dateutil",
".",
"parser",
".",
"parse",
"(",
"s",
")",
"if",
"s",
"else",
"None"
] | The created timestamp of the bucket as a datetime.datetime. | [
"The",
"created",
"timestamp",
"of",
"the",
"bucket",
"as",
"a",
"datetime",
".",
"datetime",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_bucket.py#L71-L74 | train | 237,637 |
googledatalab/pydatalab | google/datalab/storage/_bucket.py | Bucket.metadata | def metadata(self):
"""Retrieves metadata about the bucket.
Returns:
A BucketMetadata instance with information about this bucket.
Raises:
Exception if there was an error requesting the bucket's metadata.
"""
if self._info is None:
try:
self._info = self._api.buckets_get(self._name)
except Exception as e:
raise e
return BucketMetadata(self._info) if self._info else None | python | def metadata(self):
"""Retrieves metadata about the bucket.
Returns:
A BucketMetadata instance with information about this bucket.
Raises:
Exception if there was an error requesting the bucket's metadata.
"""
if self._info is None:
try:
self._info = self._api.buckets_get(self._name)
except Exception as e:
raise e
return BucketMetadata(self._info) if self._info else None | [
"def",
"metadata",
"(",
"self",
")",
":",
"if",
"self",
".",
"_info",
"is",
"None",
":",
"try",
":",
"self",
".",
"_info",
"=",
"self",
".",
"_api",
".",
"buckets_get",
"(",
"self",
".",
"_name",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"e",
"return",
"BucketMetadata",
"(",
"self",
".",
"_info",
")",
"if",
"self",
".",
"_info",
"else",
"None"
] | Retrieves metadata about the bucket.
Returns:
A BucketMetadata instance with information about this bucket.
Raises:
Exception if there was an error requesting the bucket's metadata. | [
"Retrieves",
"metadata",
"about",
"the",
"bucket",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_bucket.py#L118-L132 | train | 237,638 |
googledatalab/pydatalab | google/datalab/storage/_bucket.py | Bucket.object | def object(self, key):
"""Retrieves a Storage Object for the specified key in this bucket.
The object need not exist.
Args:
key: the key of the object within the bucket.
Returns:
An Object instance representing the specified key.
"""
return _object.Object(self._name, key, context=self._context) | python | def object(self, key):
"""Retrieves a Storage Object for the specified key in this bucket.
The object need not exist.
Args:
key: the key of the object within the bucket.
Returns:
An Object instance representing the specified key.
"""
return _object.Object(self._name, key, context=self._context) | [
"def",
"object",
"(",
"self",
",",
"key",
")",
":",
"return",
"_object",
".",
"Object",
"(",
"self",
".",
"_name",
",",
"key",
",",
"context",
"=",
"self",
".",
"_context",
")"
] | Retrieves a Storage Object for the specified key in this bucket.
The object need not exist.
Args:
key: the key of the object within the bucket.
Returns:
An Object instance representing the specified key. | [
"Retrieves",
"a",
"Storage",
"Object",
"for",
"the",
"specified",
"key",
"in",
"this",
"bucket",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_bucket.py#L134-L144 | train | 237,639 |
googledatalab/pydatalab | google/datalab/storage/_bucket.py | Bucket.objects | def objects(self, prefix=None, delimiter=None):
"""Get an iterator for the objects within this bucket.
Args:
prefix: an optional prefix to match objects.
delimiter: an optional string to simulate directory-like semantics. The returned objects
will be those whose names do not contain the delimiter after the prefix. For
the remaining objects, the names will be returned truncated after the delimiter
with duplicates removed (i.e. as pseudo-directories).
Returns:
An iterable list of objects within this bucket.
"""
return _object.Objects(self._name, prefix, delimiter, context=self._context) | python | def objects(self, prefix=None, delimiter=None):
"""Get an iterator for the objects within this bucket.
Args:
prefix: an optional prefix to match objects.
delimiter: an optional string to simulate directory-like semantics. The returned objects
will be those whose names do not contain the delimiter after the prefix. For
the remaining objects, the names will be returned truncated after the delimiter
with duplicates removed (i.e. as pseudo-directories).
Returns:
An iterable list of objects within this bucket.
"""
return _object.Objects(self._name, prefix, delimiter, context=self._context) | [
"def",
"objects",
"(",
"self",
",",
"prefix",
"=",
"None",
",",
"delimiter",
"=",
"None",
")",
":",
"return",
"_object",
".",
"Objects",
"(",
"self",
".",
"_name",
",",
"prefix",
",",
"delimiter",
",",
"context",
"=",
"self",
".",
"_context",
")"
] | Get an iterator for the objects within this bucket.
Args:
prefix: an optional prefix to match objects.
delimiter: an optional string to simulate directory-like semantics. The returned objects
will be those whose names do not contain the delimiter after the prefix. For
the remaining objects, the names will be returned truncated after the delimiter
with duplicates removed (i.e. as pseudo-directories).
Returns:
An iterable list of objects within this bucket. | [
"Get",
"an",
"iterator",
"for",
"the",
"objects",
"within",
"this",
"bucket",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_bucket.py#L146-L158 | train | 237,640 |
googledatalab/pydatalab | google/datalab/storage/_bucket.py | Bucket.delete | def delete(self):
"""Deletes the bucket.
Raises:
Exception if there was an error deleting the bucket.
"""
if self.exists():
try:
self._api.buckets_delete(self._name)
except Exception as e:
raise e | python | def delete(self):
"""Deletes the bucket.
Raises:
Exception if there was an error deleting the bucket.
"""
if self.exists():
try:
self._api.buckets_delete(self._name)
except Exception as e:
raise e | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"self",
".",
"exists",
"(",
")",
":",
"try",
":",
"self",
".",
"_api",
".",
"buckets_delete",
"(",
"self",
".",
"_name",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"e"
] | Deletes the bucket.
Raises:
Exception if there was an error deleting the bucket. | [
"Deletes",
"the",
"bucket",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_bucket.py#L185-L195 | train | 237,641 |
googledatalab/pydatalab | google/datalab/storage/_bucket.py | Buckets.contains | def contains(self, name):
"""Checks if the specified bucket exists.
Args:
name: the name of the bucket to lookup.
Returns:
True if the bucket exists; False otherwise.
Raises:
Exception if there was an error requesting information about the bucket.
"""
try:
self._api.buckets_get(name)
except google.datalab.utils.RequestException as e:
if e.status == 404:
return False
raise e
except Exception as e:
raise e
return True | python | def contains(self, name):
"""Checks if the specified bucket exists.
Args:
name: the name of the bucket to lookup.
Returns:
True if the bucket exists; False otherwise.
Raises:
Exception if there was an error requesting information about the bucket.
"""
try:
self._api.buckets_get(name)
except google.datalab.utils.RequestException as e:
if e.status == 404:
return False
raise e
except Exception as e:
raise e
return True | [
"def",
"contains",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"self",
".",
"_api",
".",
"buckets_get",
"(",
"name",
")",
"except",
"google",
".",
"datalab",
".",
"utils",
".",
"RequestException",
"as",
"e",
":",
"if",
"e",
".",
"status",
"==",
"404",
":",
"return",
"False",
"raise",
"e",
"except",
"Exception",
"as",
"e",
":",
"raise",
"e",
"return",
"True"
] | Checks if the specified bucket exists.
Args:
name: the name of the bucket to lookup.
Returns:
True if the bucket exists; False otherwise.
Raises:
Exception if there was an error requesting information about the bucket. | [
"Checks",
"if",
"the",
"specified",
"bucket",
"exists",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_bucket.py#L215-L233 | train | 237,642 |
googledatalab/pydatalab | datalab/storage/_bucket.py | Bucket.item | def item(self, key):
"""Retrieves an Item object for the specified key in this bucket.
The item need not exist.
Args:
key: the key of the item within the bucket.
Returns:
An Item instance representing the specified key.
"""
return _item.Item(self._name, key, context=self._context) | python | def item(self, key):
"""Retrieves an Item object for the specified key in this bucket.
The item need not exist.
Args:
key: the key of the item within the bucket.
Returns:
An Item instance representing the specified key.
"""
return _item.Item(self._name, key, context=self._context) | [
"def",
"item",
"(",
"self",
",",
"key",
")",
":",
"return",
"_item",
".",
"Item",
"(",
"self",
".",
"_name",
",",
"key",
",",
"context",
"=",
"self",
".",
"_context",
")"
] | Retrieves an Item object for the specified key in this bucket.
The item need not exist.
Args:
key: the key of the item within the bucket.
Returns:
An Item instance representing the specified key. | [
"Retrieves",
"an",
"Item",
"object",
"for",
"the",
"specified",
"key",
"in",
"this",
"bucket",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/_bucket.py#L134-L144 | train | 237,643 |
googledatalab/pydatalab | datalab/storage/_bucket.py | Bucket.items | def items(self, prefix=None, delimiter=None):
"""Get an iterator for the items within this bucket.
Args:
prefix: an optional prefix to match items.
delimiter: an optional string to simulate directory-like semantics. The returned items
will be those whose names do not contain the delimiter after the prefix. For
the remaining items, the names will be returned truncated after the delimiter
with duplicates removed (i.e. as pseudo-directories).
Returns:
An iterable list of items within this bucket.
"""
return _item.Items(self._name, prefix, delimiter, context=self._context) | python | def items(self, prefix=None, delimiter=None):
"""Get an iterator for the items within this bucket.
Args:
prefix: an optional prefix to match items.
delimiter: an optional string to simulate directory-like semantics. The returned items
will be those whose names do not contain the delimiter after the prefix. For
the remaining items, the names will be returned truncated after the delimiter
with duplicates removed (i.e. as pseudo-directories).
Returns:
An iterable list of items within this bucket.
"""
return _item.Items(self._name, prefix, delimiter, context=self._context) | [
"def",
"items",
"(",
"self",
",",
"prefix",
"=",
"None",
",",
"delimiter",
"=",
"None",
")",
":",
"return",
"_item",
".",
"Items",
"(",
"self",
".",
"_name",
",",
"prefix",
",",
"delimiter",
",",
"context",
"=",
"self",
".",
"_context",
")"
] | Get an iterator for the items within this bucket.
Args:
prefix: an optional prefix to match items.
delimiter: an optional string to simulate directory-like semantics. The returned items
will be those whose names do not contain the delimiter after the prefix. For
the remaining items, the names will be returned truncated after the delimiter
with duplicates removed (i.e. as pseudo-directories).
Returns:
An iterable list of items within this bucket. | [
"Get",
"an",
"iterator",
"for",
"the",
"items",
"within",
"this",
"bucket",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/_bucket.py#L146-L158 | train | 237,644 |
googledatalab/pydatalab | datalab/storage/_bucket.py | Bucket.create | def create(self, project_id=None):
"""Creates the bucket.
Args:
project_id: the project in which to create the bucket.
Returns:
The bucket.
Raises:
Exception if there was an error creating the bucket.
"""
if not self.exists():
if project_id is None:
project_id = self._api.project_id
try:
self._info = self._api.buckets_insert(self._name, project_id=project_id)
except Exception as e:
raise e
return self | python | def create(self, project_id=None):
"""Creates the bucket.
Args:
project_id: the project in which to create the bucket.
Returns:
The bucket.
Raises:
Exception if there was an error creating the bucket.
"""
if not self.exists():
if project_id is None:
project_id = self._api.project_id
try:
self._info = self._api.buckets_insert(self._name, project_id=project_id)
except Exception as e:
raise e
return self | [
"def",
"create",
"(",
"self",
",",
"project_id",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"exists",
"(",
")",
":",
"if",
"project_id",
"is",
"None",
":",
"project_id",
"=",
"self",
".",
"_api",
".",
"project_id",
"try",
":",
"self",
".",
"_info",
"=",
"self",
".",
"_api",
".",
"buckets_insert",
"(",
"self",
".",
"_name",
",",
"project_id",
"=",
"project_id",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"e",
"return",
"self"
] | Creates the bucket.
Args:
project_id: the project in which to create the bucket.
Returns:
The bucket.
Raises:
Exception if there was an error creating the bucket. | [
"Creates",
"the",
"bucket",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/_bucket.py#L167-L184 | train | 237,645 |
googledatalab/pydatalab | datalab/storage/_bucket.py | Buckets.create | def create(self, name):
"""Creates a new bucket.
Args:
name: a unique name for the new bucket.
Returns:
The newly created bucket.
Raises:
Exception if there was an error creating the bucket.
"""
return Bucket(name, context=self._context).create(self._project_id) | python | def create(self, name):
"""Creates a new bucket.
Args:
name: a unique name for the new bucket.
Returns:
The newly created bucket.
Raises:
Exception if there was an error creating the bucket.
"""
return Bucket(name, context=self._context).create(self._project_id) | [
"def",
"create",
"(",
"self",
",",
"name",
")",
":",
"return",
"Bucket",
"(",
"name",
",",
"context",
"=",
"self",
".",
"_context",
")",
".",
"create",
"(",
"self",
".",
"_project_id",
")"
] | Creates a new bucket.
Args:
name: a unique name for the new bucket.
Returns:
The newly created bucket.
Raises:
Exception if there was an error creating the bucket. | [
"Creates",
"a",
"new",
"bucket",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/_bucket.py#L238-L248 | train | 237,646 |
googledatalab/pydatalab | solutionbox/structured_data/mltoolbox/regression/dnn/_regression_dnn.py | train | def train(train_dataset,
eval_dataset,
analysis_dir,
output_dir,
features,
layer_sizes,
max_steps=5000,
num_epochs=None,
train_batch_size=100,
eval_batch_size=16,
min_eval_frequency=100,
learning_rate=0.01,
epsilon=0.0005,
job_name=None,
cloud=None,
):
"""Blocking version of train_async. See documentation for train_async."""
job = train_async(
train_dataset=train_dataset,
eval_dataset=eval_dataset,
analysis_dir=analysis_dir,
output_dir=output_dir,
features=features,
layer_sizes=layer_sizes,
max_steps=max_steps,
num_epochs=num_epochs,
train_batch_size=train_batch_size,
eval_batch_size=eval_batch_size,
min_eval_frequency=min_eval_frequency,
learning_rate=learning_rate,
epsilon=epsilon,
job_name=job_name,
cloud=cloud,
)
job.wait()
print('Training: ' + str(job.state)) | python | def train(train_dataset,
eval_dataset,
analysis_dir,
output_dir,
features,
layer_sizes,
max_steps=5000,
num_epochs=None,
train_batch_size=100,
eval_batch_size=16,
min_eval_frequency=100,
learning_rate=0.01,
epsilon=0.0005,
job_name=None,
cloud=None,
):
"""Blocking version of train_async. See documentation for train_async."""
job = train_async(
train_dataset=train_dataset,
eval_dataset=eval_dataset,
analysis_dir=analysis_dir,
output_dir=output_dir,
features=features,
layer_sizes=layer_sizes,
max_steps=max_steps,
num_epochs=num_epochs,
train_batch_size=train_batch_size,
eval_batch_size=eval_batch_size,
min_eval_frequency=min_eval_frequency,
learning_rate=learning_rate,
epsilon=epsilon,
job_name=job_name,
cloud=cloud,
)
job.wait()
print('Training: ' + str(job.state)) | [
"def",
"train",
"(",
"train_dataset",
",",
"eval_dataset",
",",
"analysis_dir",
",",
"output_dir",
",",
"features",
",",
"layer_sizes",
",",
"max_steps",
"=",
"5000",
",",
"num_epochs",
"=",
"None",
",",
"train_batch_size",
"=",
"100",
",",
"eval_batch_size",
"=",
"16",
",",
"min_eval_frequency",
"=",
"100",
",",
"learning_rate",
"=",
"0.01",
",",
"epsilon",
"=",
"0.0005",
",",
"job_name",
"=",
"None",
",",
"cloud",
"=",
"None",
",",
")",
":",
"job",
"=",
"train_async",
"(",
"train_dataset",
"=",
"train_dataset",
",",
"eval_dataset",
"=",
"eval_dataset",
",",
"analysis_dir",
"=",
"analysis_dir",
",",
"output_dir",
"=",
"output_dir",
",",
"features",
"=",
"features",
",",
"layer_sizes",
"=",
"layer_sizes",
",",
"max_steps",
"=",
"max_steps",
",",
"num_epochs",
"=",
"num_epochs",
",",
"train_batch_size",
"=",
"train_batch_size",
",",
"eval_batch_size",
"=",
"eval_batch_size",
",",
"min_eval_frequency",
"=",
"min_eval_frequency",
",",
"learning_rate",
"=",
"learning_rate",
",",
"epsilon",
"=",
"epsilon",
",",
"job_name",
"=",
"job_name",
",",
"cloud",
"=",
"cloud",
",",
")",
"job",
".",
"wait",
"(",
")",
"print",
"(",
"'Training: '",
"+",
"str",
"(",
"job",
".",
"state",
")",
")"
] | Blocking version of train_async. See documentation for train_async. | [
"Blocking",
"version",
"of",
"train_async",
".",
"See",
"documentation",
"for",
"train_async",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/regression/dnn/_regression_dnn.py#L4-L39 | train | 237,647 |
googledatalab/pydatalab | datalab/stackdriver/monitoring/_resource.py | ResourceDescriptors.list | def list(self, pattern='*'):
"""Returns a list of resource descriptors that match the filters.
Args:
pattern: An optional pattern to further filter the descriptors. This can
include Unix shell-style wildcards. E.g. ``"aws*"``, ``"*cluster*"``.
Returns:
A list of ResourceDescriptor objects that match the filters.
"""
if self._descriptors is None:
self._descriptors = self._client.list_resource_descriptors(
filter_string=self._filter_string)
return [resource for resource in self._descriptors
if fnmatch.fnmatch(resource.type, pattern)] | python | def list(self, pattern='*'):
"""Returns a list of resource descriptors that match the filters.
Args:
pattern: An optional pattern to further filter the descriptors. This can
include Unix shell-style wildcards. E.g. ``"aws*"``, ``"*cluster*"``.
Returns:
A list of ResourceDescriptor objects that match the filters.
"""
if self._descriptors is None:
self._descriptors = self._client.list_resource_descriptors(
filter_string=self._filter_string)
return [resource for resource in self._descriptors
if fnmatch.fnmatch(resource.type, pattern)] | [
"def",
"list",
"(",
"self",
",",
"pattern",
"=",
"'*'",
")",
":",
"if",
"self",
".",
"_descriptors",
"is",
"None",
":",
"self",
".",
"_descriptors",
"=",
"self",
".",
"_client",
".",
"list_resource_descriptors",
"(",
"filter_string",
"=",
"self",
".",
"_filter_string",
")",
"return",
"[",
"resource",
"for",
"resource",
"in",
"self",
".",
"_descriptors",
"if",
"fnmatch",
".",
"fnmatch",
"(",
"resource",
".",
"type",
",",
"pattern",
")",
"]"
] | Returns a list of resource descriptors that match the filters.
Args:
pattern: An optional pattern to further filter the descriptors. This can
include Unix shell-style wildcards. E.g. ``"aws*"``, ``"*cluster*"``.
Returns:
A list of ResourceDescriptor objects that match the filters. | [
"Returns",
"a",
"list",
"of",
"resource",
"descriptors",
"that",
"match",
"the",
"filters",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/stackdriver/monitoring/_resource.py#L43-L57 | train | 237,648 |
googledatalab/pydatalab | google/datalab/storage/commands/_storage.py | _gcs_list_buckets | def _gcs_list_buckets(project, pattern):
""" List all Google Cloud Storage buckets that match a pattern. """
data = [{'Bucket': 'gs://' + bucket.name, 'Created': bucket.metadata.created_on}
for bucket in google.datalab.storage.Buckets(_make_context(project))
if fnmatch.fnmatch(bucket.name, pattern)]
return google.datalab.utils.commands.render_dictionary(data, ['Bucket', 'Created']) | python | def _gcs_list_buckets(project, pattern):
""" List all Google Cloud Storage buckets that match a pattern. """
data = [{'Bucket': 'gs://' + bucket.name, 'Created': bucket.metadata.created_on}
for bucket in google.datalab.storage.Buckets(_make_context(project))
if fnmatch.fnmatch(bucket.name, pattern)]
return google.datalab.utils.commands.render_dictionary(data, ['Bucket', 'Created']) | [
"def",
"_gcs_list_buckets",
"(",
"project",
",",
"pattern",
")",
":",
"data",
"=",
"[",
"{",
"'Bucket'",
":",
"'gs://'",
"+",
"bucket",
".",
"name",
",",
"'Created'",
":",
"bucket",
".",
"metadata",
".",
"created_on",
"}",
"for",
"bucket",
"in",
"google",
".",
"datalab",
".",
"storage",
".",
"Buckets",
"(",
"_make_context",
"(",
"project",
")",
")",
"if",
"fnmatch",
".",
"fnmatch",
"(",
"bucket",
".",
"name",
",",
"pattern",
")",
"]",
"return",
"google",
".",
"datalab",
".",
"utils",
".",
"commands",
".",
"render_dictionary",
"(",
"data",
",",
"[",
"'Bucket'",
",",
"'Created'",
"]",
")"
] | List all Google Cloud Storage buckets that match a pattern. | [
"List",
"all",
"Google",
"Cloud",
"Storage",
"buckets",
"that",
"match",
"a",
"pattern",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/commands/_storage.py#L278-L283 | train | 237,649 |
googledatalab/pydatalab | google/datalab/storage/commands/_storage.py | _gcs_list_keys | def _gcs_list_keys(bucket, pattern):
""" List all Google Cloud Storage keys in a specified bucket that match a pattern. """
data = [{'Name': obj.metadata.name,
'Type': obj.metadata.content_type,
'Size': obj.metadata.size,
'Updated': obj.metadata.updated_on}
for obj in _gcs_get_keys(bucket, pattern)]
return google.datalab.utils.commands.render_dictionary(data, ['Name', 'Type', 'Size', 'Updated']) | python | def _gcs_list_keys(bucket, pattern):
""" List all Google Cloud Storage keys in a specified bucket that match a pattern. """
data = [{'Name': obj.metadata.name,
'Type': obj.metadata.content_type,
'Size': obj.metadata.size,
'Updated': obj.metadata.updated_on}
for obj in _gcs_get_keys(bucket, pattern)]
return google.datalab.utils.commands.render_dictionary(data, ['Name', 'Type', 'Size', 'Updated']) | [
"def",
"_gcs_list_keys",
"(",
"bucket",
",",
"pattern",
")",
":",
"data",
"=",
"[",
"{",
"'Name'",
":",
"obj",
".",
"metadata",
".",
"name",
",",
"'Type'",
":",
"obj",
".",
"metadata",
".",
"content_type",
",",
"'Size'",
":",
"obj",
".",
"metadata",
".",
"size",
",",
"'Updated'",
":",
"obj",
".",
"metadata",
".",
"updated_on",
"}",
"for",
"obj",
"in",
"_gcs_get_keys",
"(",
"bucket",
",",
"pattern",
")",
"]",
"return",
"google",
".",
"datalab",
".",
"utils",
".",
"commands",
".",
"render_dictionary",
"(",
"data",
",",
"[",
"'Name'",
",",
"'Type'",
",",
"'Size'",
",",
"'Updated'",
"]",
")"
] | List all Google Cloud Storage keys in a specified bucket that match a pattern. | [
"List",
"all",
"Google",
"Cloud",
"Storage",
"keys",
"in",
"a",
"specified",
"bucket",
"that",
"match",
"a",
"pattern",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/commands/_storage.py#L296-L303 | train | 237,650 |
googledatalab/pydatalab | solutionbox/ml_workbench/tensorflow/transform.py | prepare_image_transforms | def prepare_image_transforms(element, image_columns):
"""Replace an images url with its jpeg bytes.
Args:
element: one input row, as a dict
image_columns: list of columns that are image paths
Return:
element, where each image file path has been replaced by a base64 image.
"""
import base64
import cStringIO
from PIL import Image
from tensorflow.python.lib.io import file_io as tf_file_io
from apache_beam.metrics import Metrics
img_error_count = Metrics.counter('main', 'ImgErrorCount')
img_missing_count = Metrics.counter('main', 'ImgMissingCount')
for name in image_columns:
uri = element[name]
if not uri:
img_missing_count.inc()
continue
try:
with tf_file_io.FileIO(uri, 'r') as f:
img = Image.open(f).convert('RGB')
# A variety of different calling libraries throw different exceptions here.
# They all correspond to an unreadable file so we treat them equivalently.
# pylint: disable broad-except
except Exception as e:
logging.exception('Error processing image %s: %s', uri, str(e))
img_error_count.inc()
return
# Convert to desired format and output.
output = cStringIO.StringIO()
img.save(output, 'jpeg')
element[name] = base64.urlsafe_b64encode(output.getvalue())
return element | python | def prepare_image_transforms(element, image_columns):
"""Replace an images url with its jpeg bytes.
Args:
element: one input row, as a dict
image_columns: list of columns that are image paths
Return:
element, where each image file path has been replaced by a base64 image.
"""
import base64
import cStringIO
from PIL import Image
from tensorflow.python.lib.io import file_io as tf_file_io
from apache_beam.metrics import Metrics
img_error_count = Metrics.counter('main', 'ImgErrorCount')
img_missing_count = Metrics.counter('main', 'ImgMissingCount')
for name in image_columns:
uri = element[name]
if not uri:
img_missing_count.inc()
continue
try:
with tf_file_io.FileIO(uri, 'r') as f:
img = Image.open(f).convert('RGB')
# A variety of different calling libraries throw different exceptions here.
# They all correspond to an unreadable file so we treat them equivalently.
# pylint: disable broad-except
except Exception as e:
logging.exception('Error processing image %s: %s', uri, str(e))
img_error_count.inc()
return
# Convert to desired format and output.
output = cStringIO.StringIO()
img.save(output, 'jpeg')
element[name] = base64.urlsafe_b64encode(output.getvalue())
return element | [
"def",
"prepare_image_transforms",
"(",
"element",
",",
"image_columns",
")",
":",
"import",
"base64",
"import",
"cStringIO",
"from",
"PIL",
"import",
"Image",
"from",
"tensorflow",
".",
"python",
".",
"lib",
".",
"io",
"import",
"file_io",
"as",
"tf_file_io",
"from",
"apache_beam",
".",
"metrics",
"import",
"Metrics",
"img_error_count",
"=",
"Metrics",
".",
"counter",
"(",
"'main'",
",",
"'ImgErrorCount'",
")",
"img_missing_count",
"=",
"Metrics",
".",
"counter",
"(",
"'main'",
",",
"'ImgMissingCount'",
")",
"for",
"name",
"in",
"image_columns",
":",
"uri",
"=",
"element",
"[",
"name",
"]",
"if",
"not",
"uri",
":",
"img_missing_count",
".",
"inc",
"(",
")",
"continue",
"try",
":",
"with",
"tf_file_io",
".",
"FileIO",
"(",
"uri",
",",
"'r'",
")",
"as",
"f",
":",
"img",
"=",
"Image",
".",
"open",
"(",
"f",
")",
".",
"convert",
"(",
"'RGB'",
")",
"# A variety of different calling libraries throw different exceptions here.",
"# They all correspond to an unreadable file so we treat them equivalently.",
"# pylint: disable broad-except",
"except",
"Exception",
"as",
"e",
":",
"logging",
".",
"exception",
"(",
"'Error processing image %s: %s'",
",",
"uri",
",",
"str",
"(",
"e",
")",
")",
"img_error_count",
".",
"inc",
"(",
")",
"return",
"# Convert to desired format and output.",
"output",
"=",
"cStringIO",
".",
"StringIO",
"(",
")",
"img",
".",
"save",
"(",
"output",
",",
"'jpeg'",
")",
"element",
"[",
"name",
"]",
"=",
"base64",
".",
"urlsafe_b64encode",
"(",
"output",
".",
"getvalue",
"(",
")",
")",
"return",
"element"
] | Replace an images url with its jpeg bytes.
Args:
element: one input row, as a dict
image_columns: list of columns that are image paths
Return:
element, where each image file path has been replaced by a base64 image. | [
"Replace",
"an",
"images",
"url",
"with",
"its",
"jpeg",
"bytes",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/transform.py#L197-L238 | train | 237,651 |
googledatalab/pydatalab | solutionbox/ml_workbench/tensorflow/transform.py | decode_csv | def decode_csv(csv_string, column_names):
"""Parse a csv line into a dict.
Args:
csv_string: a csv string. May contain missing values "a,,c"
column_names: list of column names
Returns:
Dict of {column_name, value_from_csv}. If there are missing values,
value_from_csv will be ''.
"""
import csv
r = next(csv.reader([csv_string]))
if len(r) != len(column_names):
raise ValueError('csv line %s does not have %d columns' % (csv_string, len(column_names)))
return {k: v for k, v in zip(column_names, r)} | python | def decode_csv(csv_string, column_names):
"""Parse a csv line into a dict.
Args:
csv_string: a csv string. May contain missing values "a,,c"
column_names: list of column names
Returns:
Dict of {column_name, value_from_csv}. If there are missing values,
value_from_csv will be ''.
"""
import csv
r = next(csv.reader([csv_string]))
if len(r) != len(column_names):
raise ValueError('csv line %s does not have %d columns' % (csv_string, len(column_names)))
return {k: v for k, v in zip(column_names, r)} | [
"def",
"decode_csv",
"(",
"csv_string",
",",
"column_names",
")",
":",
"import",
"csv",
"r",
"=",
"next",
"(",
"csv",
".",
"reader",
"(",
"[",
"csv_string",
"]",
")",
")",
"if",
"len",
"(",
"r",
")",
"!=",
"len",
"(",
"column_names",
")",
":",
"raise",
"ValueError",
"(",
"'csv line %s does not have %d columns'",
"%",
"(",
"csv_string",
",",
"len",
"(",
"column_names",
")",
")",
")",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"zip",
"(",
"column_names",
",",
"r",
")",
"}"
] | Parse a csv line into a dict.
Args:
csv_string: a csv string. May contain missing values "a,,c"
column_names: list of column names
Returns:
Dict of {column_name, value_from_csv}. If there are missing values,
value_from_csv will be ''. | [
"Parse",
"a",
"csv",
"line",
"into",
"a",
"dict",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/transform.py#L355-L370 | train | 237,652 |
googledatalab/pydatalab | solutionbox/ml_workbench/tensorflow/transform.py | encode_csv | def encode_csv(data_dict, column_names):
"""Builds a csv string.
Args:
data_dict: dict of {column_name: 1 value}
column_names: list of column names
Returns:
A csv string version of data_dict
"""
import csv
import six
values = [str(data_dict[x]) for x in column_names]
str_buff = six.StringIO()
writer = csv.writer(str_buff, lineterminator='')
writer.writerow(values)
return str_buff.getvalue() | python | def encode_csv(data_dict, column_names):
"""Builds a csv string.
Args:
data_dict: dict of {column_name: 1 value}
column_names: list of column names
Returns:
A csv string version of data_dict
"""
import csv
import six
values = [str(data_dict[x]) for x in column_names]
str_buff = six.StringIO()
writer = csv.writer(str_buff, lineterminator='')
writer.writerow(values)
return str_buff.getvalue() | [
"def",
"encode_csv",
"(",
"data_dict",
",",
"column_names",
")",
":",
"import",
"csv",
"import",
"six",
"values",
"=",
"[",
"str",
"(",
"data_dict",
"[",
"x",
"]",
")",
"for",
"x",
"in",
"column_names",
"]",
"str_buff",
"=",
"six",
".",
"StringIO",
"(",
")",
"writer",
"=",
"csv",
".",
"writer",
"(",
"str_buff",
",",
"lineterminator",
"=",
"''",
")",
"writer",
".",
"writerow",
"(",
"values",
")",
"return",
"str_buff",
".",
"getvalue",
"(",
")"
] | Builds a csv string.
Args:
data_dict: dict of {column_name: 1 value}
column_names: list of column names
Returns:
A csv string version of data_dict | [
"Builds",
"a",
"csv",
"string",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/transform.py#L373-L389 | train | 237,653 |
googledatalab/pydatalab | solutionbox/ml_workbench/tensorflow/transform.py | serialize_example | def serialize_example(transformed_json_data, info_dict):
"""Makes a serialized tf.example.
Args:
transformed_json_data: dict of transformed data.
info_dict: output of feature_transforms.get_transfrormed_feature_info()
Returns:
The serialized tf.example version of transformed_json_data.
"""
import six
import tensorflow as tf
def _make_int64_list(x):
return tf.train.Feature(int64_list=tf.train.Int64List(value=x))
def _make_bytes_list(x):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=x))
def _make_float_list(x):
return tf.train.Feature(float_list=tf.train.FloatList(value=x))
if sorted(six.iterkeys(transformed_json_data)) != sorted(six.iterkeys(info_dict)):
raise ValueError('Keys do not match %s, %s' % (list(six.iterkeys(transformed_json_data)),
list(six.iterkeys(info_dict))))
ex_dict = {}
for name, info in six.iteritems(info_dict):
if info['dtype'] == tf.int64:
ex_dict[name] = _make_int64_list(transformed_json_data[name])
elif info['dtype'] == tf.float32:
ex_dict[name] = _make_float_list(transformed_json_data[name])
elif info['dtype'] == tf.string:
ex_dict[name] = _make_bytes_list(transformed_json_data[name])
else:
raise ValueError('Unsupported data type %s' % info['dtype'])
ex = tf.train.Example(features=tf.train.Features(feature=ex_dict))
return ex.SerializeToString() | python | def serialize_example(transformed_json_data, info_dict):
"""Makes a serialized tf.example.
Args:
transformed_json_data: dict of transformed data.
info_dict: output of feature_transforms.get_transfrormed_feature_info()
Returns:
The serialized tf.example version of transformed_json_data.
"""
import six
import tensorflow as tf
def _make_int64_list(x):
return tf.train.Feature(int64_list=tf.train.Int64List(value=x))
def _make_bytes_list(x):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=x))
def _make_float_list(x):
return tf.train.Feature(float_list=tf.train.FloatList(value=x))
if sorted(six.iterkeys(transformed_json_data)) != sorted(six.iterkeys(info_dict)):
raise ValueError('Keys do not match %s, %s' % (list(six.iterkeys(transformed_json_data)),
list(six.iterkeys(info_dict))))
ex_dict = {}
for name, info in six.iteritems(info_dict):
if info['dtype'] == tf.int64:
ex_dict[name] = _make_int64_list(transformed_json_data[name])
elif info['dtype'] == tf.float32:
ex_dict[name] = _make_float_list(transformed_json_data[name])
elif info['dtype'] == tf.string:
ex_dict[name] = _make_bytes_list(transformed_json_data[name])
else:
raise ValueError('Unsupported data type %s' % info['dtype'])
ex = tf.train.Example(features=tf.train.Features(feature=ex_dict))
return ex.SerializeToString() | [
"def",
"serialize_example",
"(",
"transformed_json_data",
",",
"info_dict",
")",
":",
"import",
"six",
"import",
"tensorflow",
"as",
"tf",
"def",
"_make_int64_list",
"(",
"x",
")",
":",
"return",
"tf",
".",
"train",
".",
"Feature",
"(",
"int64_list",
"=",
"tf",
".",
"train",
".",
"Int64List",
"(",
"value",
"=",
"x",
")",
")",
"def",
"_make_bytes_list",
"(",
"x",
")",
":",
"return",
"tf",
".",
"train",
".",
"Feature",
"(",
"bytes_list",
"=",
"tf",
".",
"train",
".",
"BytesList",
"(",
"value",
"=",
"x",
")",
")",
"def",
"_make_float_list",
"(",
"x",
")",
":",
"return",
"tf",
".",
"train",
".",
"Feature",
"(",
"float_list",
"=",
"tf",
".",
"train",
".",
"FloatList",
"(",
"value",
"=",
"x",
")",
")",
"if",
"sorted",
"(",
"six",
".",
"iterkeys",
"(",
"transformed_json_data",
")",
")",
"!=",
"sorted",
"(",
"six",
".",
"iterkeys",
"(",
"info_dict",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Keys do not match %s, %s'",
"%",
"(",
"list",
"(",
"six",
".",
"iterkeys",
"(",
"transformed_json_data",
")",
")",
",",
"list",
"(",
"six",
".",
"iterkeys",
"(",
"info_dict",
")",
")",
")",
")",
"ex_dict",
"=",
"{",
"}",
"for",
"name",
",",
"info",
"in",
"six",
".",
"iteritems",
"(",
"info_dict",
")",
":",
"if",
"info",
"[",
"'dtype'",
"]",
"==",
"tf",
".",
"int64",
":",
"ex_dict",
"[",
"name",
"]",
"=",
"_make_int64_list",
"(",
"transformed_json_data",
"[",
"name",
"]",
")",
"elif",
"info",
"[",
"'dtype'",
"]",
"==",
"tf",
".",
"float32",
":",
"ex_dict",
"[",
"name",
"]",
"=",
"_make_float_list",
"(",
"transformed_json_data",
"[",
"name",
"]",
")",
"elif",
"info",
"[",
"'dtype'",
"]",
"==",
"tf",
".",
"string",
":",
"ex_dict",
"[",
"name",
"]",
"=",
"_make_bytes_list",
"(",
"transformed_json_data",
"[",
"name",
"]",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Unsupported data type %s'",
"%",
"info",
"[",
"'dtype'",
"]",
")",
"ex",
"=",
"tf",
".",
"train",
".",
"Example",
"(",
"features",
"=",
"tf",
".",
"train",
".",
"Features",
"(",
"feature",
"=",
"ex_dict",
")",
")",
"return",
"ex",
".",
"SerializeToString",
"(",
")"
] | Makes a serialized tf.example.
Args:
transformed_json_data: dict of transformed data.
info_dict: output of feature_transforms.get_transfrormed_feature_info()
Returns:
The serialized tf.example version of transformed_json_data. | [
"Makes",
"a",
"serialized",
"tf",
".",
"example",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/transform.py#L392-L428 | train | 237,654 |
googledatalab/pydatalab | solutionbox/ml_workbench/tensorflow/transform.py | preprocess | def preprocess(pipeline, args):
"""Transfrom csv data into transfromed tf.example files.
Outline:
1) read the input data (as csv or bigquery) into a dict format
2) replace image paths with base64 encoded image files
3) build a csv input string with images paths replaced with base64. This
matches the serving csv that a trained model would expect.
4) batch the csv strings
5) run the transformations
6) write the results to tf.example files and save any errors.
"""
from tensorflow.python.lib.io import file_io
from trainer import feature_transforms
schema = json.loads(file_io.read_file_to_string(
os.path.join(args.analysis, feature_transforms.SCHEMA_FILE)).decode())
features = json.loads(file_io.read_file_to_string(
os.path.join(args.analysis, feature_transforms.FEATURES_FILE)).decode())
stats = json.loads(file_io.read_file_to_string(
os.path.join(args.analysis, feature_transforms.STATS_FILE)).decode())
column_names = [col['name'] for col in schema]
if args.csv:
all_files = []
for i, file_pattern in enumerate(args.csv):
all_files.append(pipeline | ('ReadCSVFile%d' % i) >> beam.io.ReadFromText(file_pattern))
raw_data = (
all_files
| 'MergeCSVFiles' >> beam.Flatten()
| 'ParseCSVData' >> beam.Map(decode_csv, column_names))
else:
columns = ', '.join(column_names)
query = 'SELECT {columns} FROM `{table}`'.format(columns=columns,
table=args.bigquery)
raw_data = (
pipeline
| 'ReadBiqQueryData'
>> beam.io.Read(beam.io.BigQuerySource(query=query,
use_standard_sql=True)))
# Note that prepare_image_transforms does not make embeddings, it justs reads
# the image files and converts them to byte stings. TransformFeaturesDoFn()
# will make the image embeddings.
image_columns = image_transform_columns(features)
clean_csv_data = (
raw_data
| 'PreprocessTransferredLearningTransformations'
>> beam.Map(prepare_image_transforms, image_columns)
| 'BuildCSVString'
>> beam.Map(encode_csv, column_names))
if args.shuffle:
clean_csv_data = clean_csv_data | 'ShuffleData' >> shuffle()
transform_dofn = TransformFeaturesDoFn(args.analysis, features, schema, stats)
(transformed_data, errors) = (
clean_csv_data
| 'Batch Input'
>> beam.ParDo(EmitAsBatchDoFn(args.batch_size))
| 'Run TF Graph on Batches'
>> beam.ParDo(transform_dofn).with_outputs('errors', main='main'))
_ = (transformed_data
| 'SerializeExamples' >> beam.Map(serialize_example, feature_transforms.get_transformed_feature_info(features, schema))
| 'WriteExamples'
>> beam.io.WriteToTFRecord(
os.path.join(args.output, args.prefix),
file_name_suffix='.tfrecord.gz'))
_ = (errors
| 'WriteErrors'
>> beam.io.WriteToText(
os.path.join(args.output, 'errors_' + args.prefix),
file_name_suffix='.txt')) | python | def preprocess(pipeline, args):
"""Transfrom csv data into transfromed tf.example files.
Outline:
1) read the input data (as csv or bigquery) into a dict format
2) replace image paths with base64 encoded image files
3) build a csv input string with images paths replaced with base64. This
matches the serving csv that a trained model would expect.
4) batch the csv strings
5) run the transformations
6) write the results to tf.example files and save any errors.
"""
from tensorflow.python.lib.io import file_io
from trainer import feature_transforms
schema = json.loads(file_io.read_file_to_string(
os.path.join(args.analysis, feature_transforms.SCHEMA_FILE)).decode())
features = json.loads(file_io.read_file_to_string(
os.path.join(args.analysis, feature_transforms.FEATURES_FILE)).decode())
stats = json.loads(file_io.read_file_to_string(
os.path.join(args.analysis, feature_transforms.STATS_FILE)).decode())
column_names = [col['name'] for col in schema]
if args.csv:
all_files = []
for i, file_pattern in enumerate(args.csv):
all_files.append(pipeline | ('ReadCSVFile%d' % i) >> beam.io.ReadFromText(file_pattern))
raw_data = (
all_files
| 'MergeCSVFiles' >> beam.Flatten()
| 'ParseCSVData' >> beam.Map(decode_csv, column_names))
else:
columns = ', '.join(column_names)
query = 'SELECT {columns} FROM `{table}`'.format(columns=columns,
table=args.bigquery)
raw_data = (
pipeline
| 'ReadBiqQueryData'
>> beam.io.Read(beam.io.BigQuerySource(query=query,
use_standard_sql=True)))
# Note that prepare_image_transforms does not make embeddings, it justs reads
# the image files and converts them to byte stings. TransformFeaturesDoFn()
# will make the image embeddings.
image_columns = image_transform_columns(features)
clean_csv_data = (
raw_data
| 'PreprocessTransferredLearningTransformations'
>> beam.Map(prepare_image_transforms, image_columns)
| 'BuildCSVString'
>> beam.Map(encode_csv, column_names))
if args.shuffle:
clean_csv_data = clean_csv_data | 'ShuffleData' >> shuffle()
transform_dofn = TransformFeaturesDoFn(args.analysis, features, schema, stats)
(transformed_data, errors) = (
clean_csv_data
| 'Batch Input'
>> beam.ParDo(EmitAsBatchDoFn(args.batch_size))
| 'Run TF Graph on Batches'
>> beam.ParDo(transform_dofn).with_outputs('errors', main='main'))
_ = (transformed_data
| 'SerializeExamples' >> beam.Map(serialize_example, feature_transforms.get_transformed_feature_info(features, schema))
| 'WriteExamples'
>> beam.io.WriteToTFRecord(
os.path.join(args.output, args.prefix),
file_name_suffix='.tfrecord.gz'))
_ = (errors
| 'WriteErrors'
>> beam.io.WriteToText(
os.path.join(args.output, 'errors_' + args.prefix),
file_name_suffix='.txt')) | [
"def",
"preprocess",
"(",
"pipeline",
",",
"args",
")",
":",
"from",
"tensorflow",
".",
"python",
".",
"lib",
".",
"io",
"import",
"file_io",
"from",
"trainer",
"import",
"feature_transforms",
"schema",
"=",
"json",
".",
"loads",
"(",
"file_io",
".",
"read_file_to_string",
"(",
"os",
".",
"path",
".",
"join",
"(",
"args",
".",
"analysis",
",",
"feature_transforms",
".",
"SCHEMA_FILE",
")",
")",
".",
"decode",
"(",
")",
")",
"features",
"=",
"json",
".",
"loads",
"(",
"file_io",
".",
"read_file_to_string",
"(",
"os",
".",
"path",
".",
"join",
"(",
"args",
".",
"analysis",
",",
"feature_transforms",
".",
"FEATURES_FILE",
")",
")",
".",
"decode",
"(",
")",
")",
"stats",
"=",
"json",
".",
"loads",
"(",
"file_io",
".",
"read_file_to_string",
"(",
"os",
".",
"path",
".",
"join",
"(",
"args",
".",
"analysis",
",",
"feature_transforms",
".",
"STATS_FILE",
")",
")",
".",
"decode",
"(",
")",
")",
"column_names",
"=",
"[",
"col",
"[",
"'name'",
"]",
"for",
"col",
"in",
"schema",
"]",
"if",
"args",
".",
"csv",
":",
"all_files",
"=",
"[",
"]",
"for",
"i",
",",
"file_pattern",
"in",
"enumerate",
"(",
"args",
".",
"csv",
")",
":",
"all_files",
".",
"append",
"(",
"pipeline",
"|",
"(",
"'ReadCSVFile%d'",
"%",
"i",
")",
">>",
"beam",
".",
"io",
".",
"ReadFromText",
"(",
"file_pattern",
")",
")",
"raw_data",
"=",
"(",
"all_files",
"|",
"'MergeCSVFiles'",
">>",
"beam",
".",
"Flatten",
"(",
")",
"|",
"'ParseCSVData'",
">>",
"beam",
".",
"Map",
"(",
"decode_csv",
",",
"column_names",
")",
")",
"else",
":",
"columns",
"=",
"', '",
".",
"join",
"(",
"column_names",
")",
"query",
"=",
"'SELECT {columns} FROM `{table}`'",
".",
"format",
"(",
"columns",
"=",
"columns",
",",
"table",
"=",
"args",
".",
"bigquery",
")",
"raw_data",
"=",
"(",
"pipeline",
"|",
"'ReadBiqQueryData'",
">>",
"beam",
".",
"io",
".",
"Read",
"(",
"beam",
".",
"io",
".",
"BigQuerySource",
"(",
"query",
"=",
"query",
",",
"use_standard_sql",
"=",
"True",
")",
")",
")",
"# Note that prepare_image_transforms does not make embeddings, it justs reads",
"# the image files and converts them to byte stings. TransformFeaturesDoFn()",
"# will make the image embeddings.",
"image_columns",
"=",
"image_transform_columns",
"(",
"features",
")",
"clean_csv_data",
"=",
"(",
"raw_data",
"|",
"'PreprocessTransferredLearningTransformations'",
">>",
"beam",
".",
"Map",
"(",
"prepare_image_transforms",
",",
"image_columns",
")",
"|",
"'BuildCSVString'",
">>",
"beam",
".",
"Map",
"(",
"encode_csv",
",",
"column_names",
")",
")",
"if",
"args",
".",
"shuffle",
":",
"clean_csv_data",
"=",
"clean_csv_data",
"|",
"'ShuffleData'",
">>",
"shuffle",
"(",
")",
"transform_dofn",
"=",
"TransformFeaturesDoFn",
"(",
"args",
".",
"analysis",
",",
"features",
",",
"schema",
",",
"stats",
")",
"(",
"transformed_data",
",",
"errors",
")",
"=",
"(",
"clean_csv_data",
"|",
"'Batch Input'",
">>",
"beam",
".",
"ParDo",
"(",
"EmitAsBatchDoFn",
"(",
"args",
".",
"batch_size",
")",
")",
"|",
"'Run TF Graph on Batches'",
">>",
"beam",
".",
"ParDo",
"(",
"transform_dofn",
")",
".",
"with_outputs",
"(",
"'errors'",
",",
"main",
"=",
"'main'",
")",
")",
"_",
"=",
"(",
"transformed_data",
"|",
"'SerializeExamples'",
">>",
"beam",
".",
"Map",
"(",
"serialize_example",
",",
"feature_transforms",
".",
"get_transformed_feature_info",
"(",
"features",
",",
"schema",
")",
")",
"|",
"'WriteExamples'",
">>",
"beam",
".",
"io",
".",
"WriteToTFRecord",
"(",
"os",
".",
"path",
".",
"join",
"(",
"args",
".",
"output",
",",
"args",
".",
"prefix",
")",
",",
"file_name_suffix",
"=",
"'.tfrecord.gz'",
")",
")",
"_",
"=",
"(",
"errors",
"|",
"'WriteErrors'",
">>",
"beam",
".",
"io",
".",
"WriteToText",
"(",
"os",
".",
"path",
".",
"join",
"(",
"args",
".",
"output",
",",
"'errors_'",
"+",
"args",
".",
"prefix",
")",
",",
"file_name_suffix",
"=",
"'.txt'",
")",
")"
] | Transfrom csv data into transfromed tf.example files.
Outline:
1) read the input data (as csv or bigquery) into a dict format
2) replace image paths with base64 encoded image files
3) build a csv input string with images paths replaced with base64. This
matches the serving csv that a trained model would expect.
4) batch the csv strings
5) run the transformations
6) write the results to tf.example files and save any errors. | [
"Transfrom",
"csv",
"data",
"into",
"transfromed",
"tf",
".",
"example",
"files",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/transform.py#L431-L506 | train | 237,655 |
googledatalab/pydatalab | solutionbox/ml_workbench/tensorflow/transform.py | main | def main(argv=None):
"""Run Preprocessing as a Dataflow."""
args = parse_arguments(sys.argv if argv is None else argv)
temp_dir = os.path.join(args.output, 'tmp')
if args.cloud:
pipeline_name = 'DataflowRunner'
else:
pipeline_name = 'DirectRunner'
# Suppress TF warnings.
os.environ['TF_CPP_MIN_LOG_LEVEL']='3'
options = {
'job_name': args.job_name,
'temp_location': temp_dir,
'project': args.project_id,
'setup_file':
os.path.abspath(os.path.join(
os.path.dirname(__file__),
'setup.py')),
}
if args.num_workers:
options['num_workers'] = args.num_workers
if args.worker_machine_type:
options['worker_machine_type'] = args.worker_machine_type
pipeline_options = beam.pipeline.PipelineOptions(flags=[], **options)
p = beam.Pipeline(pipeline_name, options=pipeline_options)
preprocess(pipeline=p, args=args)
pipeline_result = p.run()
if not args.async:
pipeline_result.wait_until_finish()
if args.async and args.cloud:
print('View job at https://console.developers.google.com/dataflow/job/%s?project=%s' %
(pipeline_result.job_id(), args.project_id)) | python | def main(argv=None):
"""Run Preprocessing as a Dataflow."""
args = parse_arguments(sys.argv if argv is None else argv)
temp_dir = os.path.join(args.output, 'tmp')
if args.cloud:
pipeline_name = 'DataflowRunner'
else:
pipeline_name = 'DirectRunner'
# Suppress TF warnings.
os.environ['TF_CPP_MIN_LOG_LEVEL']='3'
options = {
'job_name': args.job_name,
'temp_location': temp_dir,
'project': args.project_id,
'setup_file':
os.path.abspath(os.path.join(
os.path.dirname(__file__),
'setup.py')),
}
if args.num_workers:
options['num_workers'] = args.num_workers
if args.worker_machine_type:
options['worker_machine_type'] = args.worker_machine_type
pipeline_options = beam.pipeline.PipelineOptions(flags=[], **options)
p = beam.Pipeline(pipeline_name, options=pipeline_options)
preprocess(pipeline=p, args=args)
pipeline_result = p.run()
if not args.async:
pipeline_result.wait_until_finish()
if args.async and args.cloud:
print('View job at https://console.developers.google.com/dataflow/job/%s?project=%s' %
(pipeline_result.job_id(), args.project_id)) | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"args",
"=",
"parse_arguments",
"(",
"sys",
".",
"argv",
"if",
"argv",
"is",
"None",
"else",
"argv",
")",
"temp_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"args",
".",
"output",
",",
"'tmp'",
")",
"if",
"args",
".",
"cloud",
":",
"pipeline_name",
"=",
"'DataflowRunner'",
"else",
":",
"pipeline_name",
"=",
"'DirectRunner'",
"# Suppress TF warnings.",
"os",
".",
"environ",
"[",
"'TF_CPP_MIN_LOG_LEVEL'",
"]",
"=",
"'3'",
"options",
"=",
"{",
"'job_name'",
":",
"args",
".",
"job_name",
",",
"'temp_location'",
":",
"temp_dir",
",",
"'project'",
":",
"args",
".",
"project_id",
",",
"'setup_file'",
":",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'setup.py'",
")",
")",
",",
"}",
"if",
"args",
".",
"num_workers",
":",
"options",
"[",
"'num_workers'",
"]",
"=",
"args",
".",
"num_workers",
"if",
"args",
".",
"worker_machine_type",
":",
"options",
"[",
"'worker_machine_type'",
"]",
"=",
"args",
".",
"worker_machine_type",
"pipeline_options",
"=",
"beam",
".",
"pipeline",
".",
"PipelineOptions",
"(",
"flags",
"=",
"[",
"]",
",",
"*",
"*",
"options",
")",
"p",
"=",
"beam",
".",
"Pipeline",
"(",
"pipeline_name",
",",
"options",
"=",
"pipeline_options",
")",
"preprocess",
"(",
"pipeline",
"=",
"p",
",",
"args",
"=",
"args",
")",
"pipeline_result",
"=",
"p",
".",
"run",
"(",
")",
"if",
"not",
"args",
".",
"async",
":",
"pipeline_result",
".",
"wait_until_finish",
"(",
")",
"if",
"args",
".",
"async",
"and",
"args",
".",
"cloud",
":",
"print",
"(",
"'View job at https://console.developers.google.com/dataflow/job/%s?project=%s'",
"%",
"(",
"pipeline_result",
".",
"job_id",
"(",
")",
",",
"args",
".",
"project_id",
")",
")"
] | Run Preprocessing as a Dataflow. | [
"Run",
"Preprocessing",
"as",
"a",
"Dataflow",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/transform.py#L509-L545 | train | 237,656 |
googledatalab/pydatalab | solutionbox/ml_workbench/tensorflow/transform.py | TransformFeaturesDoFn.start_bundle | def start_bundle(self, element=None):
"""Build the transfromation graph once."""
import tensorflow as tf
from trainer import feature_transforms
g = tf.Graph()
session = tf.Session(graph=g)
# Build the transformation graph
with g.as_default():
transformed_features, _, placeholders = (
feature_transforms.build_csv_serving_tensors_for_transform_step(
analysis_path=self._analysis_output_dir,
features=self._features,
schema=self._schema,
stats=self._stats,
keep_target=True))
session.run(tf.tables_initializer())
self._session = session
self._transformed_features = transformed_features
self._input_placeholder_tensor = placeholders['csv_example'] | python | def start_bundle(self, element=None):
"""Build the transfromation graph once."""
import tensorflow as tf
from trainer import feature_transforms
g = tf.Graph()
session = tf.Session(graph=g)
# Build the transformation graph
with g.as_default():
transformed_features, _, placeholders = (
feature_transforms.build_csv_serving_tensors_for_transform_step(
analysis_path=self._analysis_output_dir,
features=self._features,
schema=self._schema,
stats=self._stats,
keep_target=True))
session.run(tf.tables_initializer())
self._session = session
self._transformed_features = transformed_features
self._input_placeholder_tensor = placeholders['csv_example'] | [
"def",
"start_bundle",
"(",
"self",
",",
"element",
"=",
"None",
")",
":",
"import",
"tensorflow",
"as",
"tf",
"from",
"trainer",
"import",
"feature_transforms",
"g",
"=",
"tf",
".",
"Graph",
"(",
")",
"session",
"=",
"tf",
".",
"Session",
"(",
"graph",
"=",
"g",
")",
"# Build the transformation graph",
"with",
"g",
".",
"as_default",
"(",
")",
":",
"transformed_features",
",",
"_",
",",
"placeholders",
"=",
"(",
"feature_transforms",
".",
"build_csv_serving_tensors_for_transform_step",
"(",
"analysis_path",
"=",
"self",
".",
"_analysis_output_dir",
",",
"features",
"=",
"self",
".",
"_features",
",",
"schema",
"=",
"self",
".",
"_schema",
",",
"stats",
"=",
"self",
".",
"_stats",
",",
"keep_target",
"=",
"True",
")",
")",
"session",
".",
"run",
"(",
"tf",
".",
"tables_initializer",
"(",
")",
")",
"self",
".",
"_session",
"=",
"session",
"self",
".",
"_transformed_features",
"=",
"transformed_features",
"self",
".",
"_input_placeholder_tensor",
"=",
"placeholders",
"[",
"'csv_example'",
"]"
] | Build the transfromation graph once. | [
"Build",
"the",
"transfromation",
"graph",
"once",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/transform.py#L278-L299 | train | 237,657 |
googledatalab/pydatalab | solutionbox/ml_workbench/tensorflow/transform.py | TransformFeaturesDoFn.process | def process(self, element):
"""Run the transformation graph on batched input data
Args:
element: list of csv strings, representing one batch input to the TF graph.
Returns:
dict containing the transformed data. Results are un-batched. Sparse
tensors are converted to lists.
"""
import apache_beam as beam
import six
import tensorflow as tf
# This function is invoked by a separate sub-process so setting the logging level
# does not affect Datalab's kernel process.
tf.logging.set_verbosity(tf.logging.ERROR)
try:
clean_element = []
for line in element:
clean_element.append(line.rstrip())
# batch_result is list of numpy arrays with batch_size many rows.
batch_result = self._session.run(
fetches=self._transformed_features,
feed_dict={self._input_placeholder_tensor: clean_element})
# ex batch_result.
# Dense tensor: {'col1': array([[batch_1], [batch_2]])}
# Sparse tensor: {'col1': tf.SparseTensorValue(
# indices=array([[batch_1, 0], [batch_1, 1], ...,
# [batch_2, 0], [batch_2, 1], ...]],
# values=array[value, value, value, ...])}
# Unbatch the results.
for i in range(len(clean_element)):
transformed_features = {}
for name, value in six.iteritems(batch_result):
if isinstance(value, tf.SparseTensorValue):
batch_i_indices = value.indices[:, 0] == i
batch_i_values = value.values[batch_i_indices]
transformed_features[name] = batch_i_values.tolist()
else:
transformed_features[name] = value[i].tolist()
yield transformed_features
except Exception as e: # pylint: disable=broad-except
yield beam.pvalue.TaggedOutput('errors', (str(e), element)) | python | def process(self, element):
"""Run the transformation graph on batched input data
Args:
element: list of csv strings, representing one batch input to the TF graph.
Returns:
dict containing the transformed data. Results are un-batched. Sparse
tensors are converted to lists.
"""
import apache_beam as beam
import six
import tensorflow as tf
# This function is invoked by a separate sub-process so setting the logging level
# does not affect Datalab's kernel process.
tf.logging.set_verbosity(tf.logging.ERROR)
try:
clean_element = []
for line in element:
clean_element.append(line.rstrip())
# batch_result is list of numpy arrays with batch_size many rows.
batch_result = self._session.run(
fetches=self._transformed_features,
feed_dict={self._input_placeholder_tensor: clean_element})
# ex batch_result.
# Dense tensor: {'col1': array([[batch_1], [batch_2]])}
# Sparse tensor: {'col1': tf.SparseTensorValue(
# indices=array([[batch_1, 0], [batch_1, 1], ...,
# [batch_2, 0], [batch_2, 1], ...]],
# values=array[value, value, value, ...])}
# Unbatch the results.
for i in range(len(clean_element)):
transformed_features = {}
for name, value in six.iteritems(batch_result):
if isinstance(value, tf.SparseTensorValue):
batch_i_indices = value.indices[:, 0] == i
batch_i_values = value.values[batch_i_indices]
transformed_features[name] = batch_i_values.tolist()
else:
transformed_features[name] = value[i].tolist()
yield transformed_features
except Exception as e: # pylint: disable=broad-except
yield beam.pvalue.TaggedOutput('errors', (str(e), element)) | [
"def",
"process",
"(",
"self",
",",
"element",
")",
":",
"import",
"apache_beam",
"as",
"beam",
"import",
"six",
"import",
"tensorflow",
"as",
"tf",
"# This function is invoked by a separate sub-process so setting the logging level",
"# does not affect Datalab's kernel process.",
"tf",
".",
"logging",
".",
"set_verbosity",
"(",
"tf",
".",
"logging",
".",
"ERROR",
")",
"try",
":",
"clean_element",
"=",
"[",
"]",
"for",
"line",
"in",
"element",
":",
"clean_element",
".",
"append",
"(",
"line",
".",
"rstrip",
"(",
")",
")",
"# batch_result is list of numpy arrays with batch_size many rows.",
"batch_result",
"=",
"self",
".",
"_session",
".",
"run",
"(",
"fetches",
"=",
"self",
".",
"_transformed_features",
",",
"feed_dict",
"=",
"{",
"self",
".",
"_input_placeholder_tensor",
":",
"clean_element",
"}",
")",
"# ex batch_result. ",
"# Dense tensor: {'col1': array([[batch_1], [batch_2]])}",
"# Sparse tensor: {'col1': tf.SparseTensorValue(",
"# indices=array([[batch_1, 0], [batch_1, 1], ...,",
"# [batch_2, 0], [batch_2, 1], ...]],",
"# values=array[value, value, value, ...])}",
"# Unbatch the results.",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"clean_element",
")",
")",
":",
"transformed_features",
"=",
"{",
"}",
"for",
"name",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"batch_result",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"tf",
".",
"SparseTensorValue",
")",
":",
"batch_i_indices",
"=",
"value",
".",
"indices",
"[",
":",
",",
"0",
"]",
"==",
"i",
"batch_i_values",
"=",
"value",
".",
"values",
"[",
"batch_i_indices",
"]",
"transformed_features",
"[",
"name",
"]",
"=",
"batch_i_values",
".",
"tolist",
"(",
")",
"else",
":",
"transformed_features",
"[",
"name",
"]",
"=",
"value",
"[",
"i",
"]",
".",
"tolist",
"(",
")",
"yield",
"transformed_features",
"except",
"Exception",
"as",
"e",
":",
"# pylint: disable=broad-except",
"yield",
"beam",
".",
"pvalue",
".",
"TaggedOutput",
"(",
"'errors'",
",",
"(",
"str",
"(",
"e",
")",
",",
"element",
")",
")"
] | Run the transformation graph on batched input data
Args:
element: list of csv strings, representing one batch input to the TF graph.
Returns:
dict containing the transformed data. Results are un-batched. Sparse
tensors are converted to lists. | [
"Run",
"the",
"transformation",
"graph",
"on",
"batched",
"input",
"data"
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/transform.py#L304-L352 | train | 237,658 |
googledatalab/pydatalab | google/datalab/bigquery/_parser.py | Parser.parse_row | def parse_row(schema, data):
"""Parses a row from query results into an equivalent object.
Args:
schema: the array of fields defining the schema of the data.
data: the JSON row from a query result.
Returns:
The parsed row object.
"""
def parse_value(data_type, value):
"""Parses a value returned from a BigQuery response.
Args:
data_type: the type of the value as specified by the schema.
value: the raw value to return (before casting to data_type).
Returns:
The value cast to the data_type.
"""
if value is not None:
if value == 'null':
value = None
elif data_type == 'INTEGER':
value = int(value)
elif data_type == 'FLOAT':
value = float(value)
elif data_type == 'TIMESTAMP':
value = datetime.datetime.utcfromtimestamp(float(value))
elif data_type == 'BOOLEAN':
value = value == 'true'
elif (type(value) != str):
# TODO(gram): Handle nested JSON records
value = str(value)
return value
row = {}
if data is None:
return row
for i, (field, schema_field) in enumerate(zip(data['f'], schema)):
val = field['v']
name = schema_field['name']
data_type = schema_field['type']
repeated = True if 'mode' in schema_field and schema_field['mode'] == 'REPEATED' else False
if repeated and val is None:
row[name] = []
elif data_type == 'RECORD':
sub_schema = schema_field['fields']
if repeated:
row[name] = [Parser.parse_row(sub_schema, v['v']) for v in val]
else:
row[name] = Parser.parse_row(sub_schema, val)
elif repeated:
row[name] = [parse_value(data_type, v['v']) for v in val]
else:
row[name] = parse_value(data_type, val)
return row | python | def parse_row(schema, data):
"""Parses a row from query results into an equivalent object.
Args:
schema: the array of fields defining the schema of the data.
data: the JSON row from a query result.
Returns:
The parsed row object.
"""
def parse_value(data_type, value):
"""Parses a value returned from a BigQuery response.
Args:
data_type: the type of the value as specified by the schema.
value: the raw value to return (before casting to data_type).
Returns:
The value cast to the data_type.
"""
if value is not None:
if value == 'null':
value = None
elif data_type == 'INTEGER':
value = int(value)
elif data_type == 'FLOAT':
value = float(value)
elif data_type == 'TIMESTAMP':
value = datetime.datetime.utcfromtimestamp(float(value))
elif data_type == 'BOOLEAN':
value = value == 'true'
elif (type(value) != str):
# TODO(gram): Handle nested JSON records
value = str(value)
return value
row = {}
if data is None:
return row
for i, (field, schema_field) in enumerate(zip(data['f'], schema)):
val = field['v']
name = schema_field['name']
data_type = schema_field['type']
repeated = True if 'mode' in schema_field and schema_field['mode'] == 'REPEATED' else False
if repeated and val is None:
row[name] = []
elif data_type == 'RECORD':
sub_schema = schema_field['fields']
if repeated:
row[name] = [Parser.parse_row(sub_schema, v['v']) for v in val]
else:
row[name] = Parser.parse_row(sub_schema, val)
elif repeated:
row[name] = [parse_value(data_type, v['v']) for v in val]
else:
row[name] = parse_value(data_type, val)
return row | [
"def",
"parse_row",
"(",
"schema",
",",
"data",
")",
":",
"def",
"parse_value",
"(",
"data_type",
",",
"value",
")",
":",
"\"\"\"Parses a value returned from a BigQuery response.\n\n Args:\n data_type: the type of the value as specified by the schema.\n value: the raw value to return (before casting to data_type).\n\n Returns:\n The value cast to the data_type.\n \"\"\"",
"if",
"value",
"is",
"not",
"None",
":",
"if",
"value",
"==",
"'null'",
":",
"value",
"=",
"None",
"elif",
"data_type",
"==",
"'INTEGER'",
":",
"value",
"=",
"int",
"(",
"value",
")",
"elif",
"data_type",
"==",
"'FLOAT'",
":",
"value",
"=",
"float",
"(",
"value",
")",
"elif",
"data_type",
"==",
"'TIMESTAMP'",
":",
"value",
"=",
"datetime",
".",
"datetime",
".",
"utcfromtimestamp",
"(",
"float",
"(",
"value",
")",
")",
"elif",
"data_type",
"==",
"'BOOLEAN'",
":",
"value",
"=",
"value",
"==",
"'true'",
"elif",
"(",
"type",
"(",
"value",
")",
"!=",
"str",
")",
":",
"# TODO(gram): Handle nested JSON records",
"value",
"=",
"str",
"(",
"value",
")",
"return",
"value",
"row",
"=",
"{",
"}",
"if",
"data",
"is",
"None",
":",
"return",
"row",
"for",
"i",
",",
"(",
"field",
",",
"schema_field",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"data",
"[",
"'f'",
"]",
",",
"schema",
")",
")",
":",
"val",
"=",
"field",
"[",
"'v'",
"]",
"name",
"=",
"schema_field",
"[",
"'name'",
"]",
"data_type",
"=",
"schema_field",
"[",
"'type'",
"]",
"repeated",
"=",
"True",
"if",
"'mode'",
"in",
"schema_field",
"and",
"schema_field",
"[",
"'mode'",
"]",
"==",
"'REPEATED'",
"else",
"False",
"if",
"repeated",
"and",
"val",
"is",
"None",
":",
"row",
"[",
"name",
"]",
"=",
"[",
"]",
"elif",
"data_type",
"==",
"'RECORD'",
":",
"sub_schema",
"=",
"schema_field",
"[",
"'fields'",
"]",
"if",
"repeated",
":",
"row",
"[",
"name",
"]",
"=",
"[",
"Parser",
".",
"parse_row",
"(",
"sub_schema",
",",
"v",
"[",
"'v'",
"]",
")",
"for",
"v",
"in",
"val",
"]",
"else",
":",
"row",
"[",
"name",
"]",
"=",
"Parser",
".",
"parse_row",
"(",
"sub_schema",
",",
"val",
")",
"elif",
"repeated",
":",
"row",
"[",
"name",
"]",
"=",
"[",
"parse_value",
"(",
"data_type",
",",
"v",
"[",
"'v'",
"]",
")",
"for",
"v",
"in",
"val",
"]",
"else",
":",
"row",
"[",
"name",
"]",
"=",
"parse_value",
"(",
"data_type",
",",
"val",
")",
"return",
"row"
] | Parses a row from query results into an equivalent object.
Args:
schema: the array of fields defining the schema of the data.
data: the JSON row from a query result.
Returns:
The parsed row object. | [
"Parses",
"a",
"row",
"from",
"query",
"results",
"into",
"an",
"equivalent",
"object",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_parser.py#L31-L89 | train | 237,659 |
googledatalab/pydatalab | google/datalab/contrib/mlworkbench/_local_predict.py | _tf_predict | def _tf_predict(model_dir, input_csvlines):
"""Prediction with a tf savedmodel.
Args:
model_dir: directory that contains a saved model
input_csvlines: list of csv strings
Returns:
Dict in the form tensor_name:prediction_list. Note that the value is always
a list, even if there was only 1 row in input_csvlines.
"""
with tf.Graph().as_default(), tf.Session() as sess:
input_alias_map, output_alias_map = _tf_load_model(sess, model_dir)
csv_tensor_name = list(input_alias_map.values())[0]
results = sess.run(fetches=output_alias_map,
feed_dict={csv_tensor_name: input_csvlines})
# convert any scalar values to a list. This may happen when there is one
# example in input_csvlines and the model uses tf.squeeze on the output
# tensor.
if len(input_csvlines) == 1:
for k, v in six.iteritems(results):
if not isinstance(v, (list, np.ndarray)):
results[k] = [v]
# Convert bytes to string. In python3 the results may be bytes.
for k, v in six.iteritems(results):
if any(isinstance(x, bytes) for x in v):
results[k] = [x.decode('utf-8') for x in v]
return results | python | def _tf_predict(model_dir, input_csvlines):
"""Prediction with a tf savedmodel.
Args:
model_dir: directory that contains a saved model
input_csvlines: list of csv strings
Returns:
Dict in the form tensor_name:prediction_list. Note that the value is always
a list, even if there was only 1 row in input_csvlines.
"""
with tf.Graph().as_default(), tf.Session() as sess:
input_alias_map, output_alias_map = _tf_load_model(sess, model_dir)
csv_tensor_name = list(input_alias_map.values())[0]
results = sess.run(fetches=output_alias_map,
feed_dict={csv_tensor_name: input_csvlines})
# convert any scalar values to a list. This may happen when there is one
# example in input_csvlines and the model uses tf.squeeze on the output
# tensor.
if len(input_csvlines) == 1:
for k, v in six.iteritems(results):
if not isinstance(v, (list, np.ndarray)):
results[k] = [v]
# Convert bytes to string. In python3 the results may be bytes.
for k, v in six.iteritems(results):
if any(isinstance(x, bytes) for x in v):
results[k] = [x.decode('utf-8') for x in v]
return results | [
"def",
"_tf_predict",
"(",
"model_dir",
",",
"input_csvlines",
")",
":",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
")",
",",
"tf",
".",
"Session",
"(",
")",
"as",
"sess",
":",
"input_alias_map",
",",
"output_alias_map",
"=",
"_tf_load_model",
"(",
"sess",
",",
"model_dir",
")",
"csv_tensor_name",
"=",
"list",
"(",
"input_alias_map",
".",
"values",
"(",
")",
")",
"[",
"0",
"]",
"results",
"=",
"sess",
".",
"run",
"(",
"fetches",
"=",
"output_alias_map",
",",
"feed_dict",
"=",
"{",
"csv_tensor_name",
":",
"input_csvlines",
"}",
")",
"# convert any scalar values to a list. This may happen when there is one",
"# example in input_csvlines and the model uses tf.squeeze on the output",
"# tensor.",
"if",
"len",
"(",
"input_csvlines",
")",
"==",
"1",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"results",
")",
":",
"if",
"not",
"isinstance",
"(",
"v",
",",
"(",
"list",
",",
"np",
".",
"ndarray",
")",
")",
":",
"results",
"[",
"k",
"]",
"=",
"[",
"v",
"]",
"# Convert bytes to string. In python3 the results may be bytes.",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"results",
")",
":",
"if",
"any",
"(",
"isinstance",
"(",
"x",
",",
"bytes",
")",
"for",
"x",
"in",
"v",
")",
":",
"results",
"[",
"k",
"]",
"=",
"[",
"x",
".",
"decode",
"(",
"'utf-8'",
")",
"for",
"x",
"in",
"v",
"]",
"return",
"results"
] | Prediction with a tf savedmodel.
Args:
model_dir: directory that contains a saved model
input_csvlines: list of csv strings
Returns:
Dict in the form tensor_name:prediction_list. Note that the value is always
a list, even if there was only 1 row in input_csvlines. | [
"Prediction",
"with",
"a",
"tf",
"savedmodel",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_local_predict.py#L56-L87 | train | 237,660 |
googledatalab/pydatalab | google/datalab/contrib/mlworkbench/_local_predict.py | _download_images | def _download_images(data, img_cols):
"""Download images given image columns."""
images = collections.defaultdict(list)
for d in data:
for img_col in img_cols:
if d.get(img_col, None):
if isinstance(d[img_col], Image.Image):
# If it is already an Image, just copy and continue.
images[img_col].append(d[img_col])
else:
# Otherwise it is image url. Load the image.
with file_io.FileIO(d[img_col], 'rb') as fi:
im = Image.open(fi)
images[img_col].append(im)
else:
images[img_col].append('')
return images | python | def _download_images(data, img_cols):
"""Download images given image columns."""
images = collections.defaultdict(list)
for d in data:
for img_col in img_cols:
if d.get(img_col, None):
if isinstance(d[img_col], Image.Image):
# If it is already an Image, just copy and continue.
images[img_col].append(d[img_col])
else:
# Otherwise it is image url. Load the image.
with file_io.FileIO(d[img_col], 'rb') as fi:
im = Image.open(fi)
images[img_col].append(im)
else:
images[img_col].append('')
return images | [
"def",
"_download_images",
"(",
"data",
",",
"img_cols",
")",
":",
"images",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"d",
"in",
"data",
":",
"for",
"img_col",
"in",
"img_cols",
":",
"if",
"d",
".",
"get",
"(",
"img_col",
",",
"None",
")",
":",
"if",
"isinstance",
"(",
"d",
"[",
"img_col",
"]",
",",
"Image",
".",
"Image",
")",
":",
"# If it is already an Image, just copy and continue.",
"images",
"[",
"img_col",
"]",
".",
"append",
"(",
"d",
"[",
"img_col",
"]",
")",
"else",
":",
"# Otherwise it is image url. Load the image.",
"with",
"file_io",
".",
"FileIO",
"(",
"d",
"[",
"img_col",
"]",
",",
"'rb'",
")",
"as",
"fi",
":",
"im",
"=",
"Image",
".",
"open",
"(",
"fi",
")",
"images",
"[",
"img_col",
"]",
".",
"append",
"(",
"im",
")",
"else",
":",
"images",
"[",
"img_col",
"]",
".",
"append",
"(",
"''",
")",
"return",
"images"
] | Download images given image columns. | [
"Download",
"images",
"given",
"image",
"columns",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_local_predict.py#L90-L108 | train | 237,661 |
googledatalab/pydatalab | google/datalab/contrib/mlworkbench/_local_predict.py | _get_predicton_csv_lines | def _get_predicton_csv_lines(data, headers, images):
"""Create CSV lines from list-of-dict data."""
if images:
data = copy.deepcopy(data)
for img_col in images:
for d, im in zip(data, images[img_col]):
if im == '':
continue
im = im.copy()
im.thumbnail((299, 299), Image.ANTIALIAS)
buf = BytesIO()
im.save(buf, "JPEG")
content = base64.urlsafe_b64encode(buf.getvalue()).decode('ascii')
d[img_col] = content
csv_lines = []
for d in data:
buf = six.StringIO()
writer = csv.DictWriter(buf, fieldnames=headers, lineterminator='')
writer.writerow(d)
csv_lines.append(buf.getvalue())
return csv_lines | python | def _get_predicton_csv_lines(data, headers, images):
"""Create CSV lines from list-of-dict data."""
if images:
data = copy.deepcopy(data)
for img_col in images:
for d, im in zip(data, images[img_col]):
if im == '':
continue
im = im.copy()
im.thumbnail((299, 299), Image.ANTIALIAS)
buf = BytesIO()
im.save(buf, "JPEG")
content = base64.urlsafe_b64encode(buf.getvalue()).decode('ascii')
d[img_col] = content
csv_lines = []
for d in data:
buf = six.StringIO()
writer = csv.DictWriter(buf, fieldnames=headers, lineterminator='')
writer.writerow(d)
csv_lines.append(buf.getvalue())
return csv_lines | [
"def",
"_get_predicton_csv_lines",
"(",
"data",
",",
"headers",
",",
"images",
")",
":",
"if",
"images",
":",
"data",
"=",
"copy",
".",
"deepcopy",
"(",
"data",
")",
"for",
"img_col",
"in",
"images",
":",
"for",
"d",
",",
"im",
"in",
"zip",
"(",
"data",
",",
"images",
"[",
"img_col",
"]",
")",
":",
"if",
"im",
"==",
"''",
":",
"continue",
"im",
"=",
"im",
".",
"copy",
"(",
")",
"im",
".",
"thumbnail",
"(",
"(",
"299",
",",
"299",
")",
",",
"Image",
".",
"ANTIALIAS",
")",
"buf",
"=",
"BytesIO",
"(",
")",
"im",
".",
"save",
"(",
"buf",
",",
"\"JPEG\"",
")",
"content",
"=",
"base64",
".",
"urlsafe_b64encode",
"(",
"buf",
".",
"getvalue",
"(",
")",
")",
".",
"decode",
"(",
"'ascii'",
")",
"d",
"[",
"img_col",
"]",
"=",
"content",
"csv_lines",
"=",
"[",
"]",
"for",
"d",
"in",
"data",
":",
"buf",
"=",
"six",
".",
"StringIO",
"(",
")",
"writer",
"=",
"csv",
".",
"DictWriter",
"(",
"buf",
",",
"fieldnames",
"=",
"headers",
",",
"lineterminator",
"=",
"''",
")",
"writer",
".",
"writerow",
"(",
"d",
")",
"csv_lines",
".",
"append",
"(",
"buf",
".",
"getvalue",
"(",
")",
")",
"return",
"csv_lines"
] | Create CSV lines from list-of-dict data. | [
"Create",
"CSV",
"lines",
"from",
"list",
"-",
"of",
"-",
"dict",
"data",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_local_predict.py#L111-L135 | train | 237,662 |
googledatalab/pydatalab | google/datalab/contrib/mlworkbench/_local_predict.py | _get_display_data_with_images | def _get_display_data_with_images(data, images):
"""Create display data by converting image urls to base64 strings."""
if not images:
return data
display_data = copy.deepcopy(data)
for img_col in images:
for d, im in zip(display_data, images[img_col]):
if im == '':
d[img_col + '_image'] = ''
else:
im = im.copy()
im.thumbnail((128, 128), Image.ANTIALIAS)
buf = BytesIO()
im.save(buf, "PNG")
content = base64.b64encode(buf.getvalue()).decode('ascii')
d[img_col + '_image'] = content
return display_data | python | def _get_display_data_with_images(data, images):
"""Create display data by converting image urls to base64 strings."""
if not images:
return data
display_data = copy.deepcopy(data)
for img_col in images:
for d, im in zip(display_data, images[img_col]):
if im == '':
d[img_col + '_image'] = ''
else:
im = im.copy()
im.thumbnail((128, 128), Image.ANTIALIAS)
buf = BytesIO()
im.save(buf, "PNG")
content = base64.b64encode(buf.getvalue()).decode('ascii')
d[img_col + '_image'] = content
return display_data | [
"def",
"_get_display_data_with_images",
"(",
"data",
",",
"images",
")",
":",
"if",
"not",
"images",
":",
"return",
"data",
"display_data",
"=",
"copy",
".",
"deepcopy",
"(",
"data",
")",
"for",
"img_col",
"in",
"images",
":",
"for",
"d",
",",
"im",
"in",
"zip",
"(",
"display_data",
",",
"images",
"[",
"img_col",
"]",
")",
":",
"if",
"im",
"==",
"''",
":",
"d",
"[",
"img_col",
"+",
"'_image'",
"]",
"=",
"''",
"else",
":",
"im",
"=",
"im",
".",
"copy",
"(",
")",
"im",
".",
"thumbnail",
"(",
"(",
"128",
",",
"128",
")",
",",
"Image",
".",
"ANTIALIAS",
")",
"buf",
"=",
"BytesIO",
"(",
")",
"im",
".",
"save",
"(",
"buf",
",",
"\"PNG\"",
")",
"content",
"=",
"base64",
".",
"b64encode",
"(",
"buf",
".",
"getvalue",
"(",
")",
")",
".",
"decode",
"(",
"'ascii'",
")",
"d",
"[",
"img_col",
"+",
"'_image'",
"]",
"=",
"content",
"return",
"display_data"
] | Create display data by converting image urls to base64 strings. | [
"Create",
"display",
"data",
"by",
"converting",
"image",
"urls",
"to",
"base64",
"strings",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_local_predict.py#L138-L157 | train | 237,663 |
googledatalab/pydatalab | google/datalab/contrib/mlworkbench/_local_predict.py | get_model_schema_and_features | def get_model_schema_and_features(model_dir):
"""Get a local model's schema and features config.
Args:
model_dir: local or GCS path of a model.
Returns:
A tuple of schema (list) and features config (dict).
"""
schema_file = os.path.join(model_dir, 'assets.extra', 'schema.json')
schema = json.loads(file_io.read_file_to_string(schema_file))
features_file = os.path.join(model_dir, 'assets.extra', 'features.json')
features_config = json.loads(file_io.read_file_to_string(features_file))
return schema, features_config | python | def get_model_schema_and_features(model_dir):
"""Get a local model's schema and features config.
Args:
model_dir: local or GCS path of a model.
Returns:
A tuple of schema (list) and features config (dict).
"""
schema_file = os.path.join(model_dir, 'assets.extra', 'schema.json')
schema = json.loads(file_io.read_file_to_string(schema_file))
features_file = os.path.join(model_dir, 'assets.extra', 'features.json')
features_config = json.loads(file_io.read_file_to_string(features_file))
return schema, features_config | [
"def",
"get_model_schema_and_features",
"(",
"model_dir",
")",
":",
"schema_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"model_dir",
",",
"'assets.extra'",
",",
"'schema.json'",
")",
"schema",
"=",
"json",
".",
"loads",
"(",
"file_io",
".",
"read_file_to_string",
"(",
"schema_file",
")",
")",
"features_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"model_dir",
",",
"'assets.extra'",
",",
"'features.json'",
")",
"features_config",
"=",
"json",
".",
"loads",
"(",
"file_io",
".",
"read_file_to_string",
"(",
"features_file",
")",
")",
"return",
"schema",
",",
"features_config"
] | Get a local model's schema and features config.
Args:
model_dir: local or GCS path of a model.
Returns:
A tuple of schema (list) and features config (dict). | [
"Get",
"a",
"local",
"model",
"s",
"schema",
"and",
"features",
"config",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_local_predict.py#L160-L172 | train | 237,664 |
googledatalab/pydatalab | google/datalab/contrib/mlworkbench/_local_predict.py | get_prediction_results | def get_prediction_results(model_dir_or_id, data, headers, img_cols=None,
cloud=False, with_source=True, show_image=True):
""" Predict with a specified model.
It predicts with the model, join source data with prediction results, and formats
the results so they can be displayed nicely in Datalab.
Args:
model_dir_or_id: The model directory if cloud is False, or model.version if cloud is True.
data: Can be a list of dictionaries, a list of csv lines, or a Pandas DataFrame. If it is not
a list of csv lines, data will be converted to csv lines first, using the orders specified
by headers and then send to model. For images, it can be image gs urls or in-memory PIL
images. Images will be converted to base64 encoded strings before prediction.
headers: the column names of data. It specifies the order of the columns when
serializing to csv lines for prediction.
img_cols: The image url columns. If specified, the img_urls will be converted to
base64 encoded image bytes.
with_source: Whether return a joined prediction source and prediction results, or prediction
results only.
show_image: When displaying prediction source, whether to add a column of image bytes for
each image url column.
Returns:
A dataframe of joined prediction source and prediction results, or prediction results only.
"""
if img_cols is None:
img_cols = []
if isinstance(data, pd.DataFrame):
data = list(data.T.to_dict().values())
elif isinstance(data[0], six.string_types):
data = list(csv.DictReader(data, fieldnames=headers))
images = _download_images(data, img_cols)
predict_data = _get_predicton_csv_lines(data, headers, images)
if cloud:
parts = model_dir_or_id.split('.')
if len(parts) != 2:
raise ValueError('Invalid model name for cloud prediction. Use "model.version".')
predict_results = ml.ModelVersions(parts[0]).predict(parts[1], predict_data)
else:
tf_logging_level = logging.getLogger("tensorflow").level
logging.getLogger("tensorflow").setLevel(logging.WARNING)
try:
predict_results = _tf_predict(model_dir_or_id, predict_data)
finally:
logging.getLogger("tensorflow").setLevel(tf_logging_level)
df_r = pd.DataFrame(predict_results)
if not with_source:
return df_r
display_data = data
if show_image:
display_data = _get_display_data_with_images(data, images)
df_s = pd.DataFrame(display_data)
df = pd.concat([df_r, df_s], axis=1)
# Remove duplicate columns. All 'key' columns are duplicate here.
df = df.loc[:, ~df.columns.duplicated()]
return df | python | def get_prediction_results(model_dir_or_id, data, headers, img_cols=None,
cloud=False, with_source=True, show_image=True):
""" Predict with a specified model.
It predicts with the model, join source data with prediction results, and formats
the results so they can be displayed nicely in Datalab.
Args:
model_dir_or_id: The model directory if cloud is False, or model.version if cloud is True.
data: Can be a list of dictionaries, a list of csv lines, or a Pandas DataFrame. If it is not
a list of csv lines, data will be converted to csv lines first, using the orders specified
by headers and then send to model. For images, it can be image gs urls or in-memory PIL
images. Images will be converted to base64 encoded strings before prediction.
headers: the column names of data. It specifies the order of the columns when
serializing to csv lines for prediction.
img_cols: The image url columns. If specified, the img_urls will be converted to
base64 encoded image bytes.
with_source: Whether return a joined prediction source and prediction results, or prediction
results only.
show_image: When displaying prediction source, whether to add a column of image bytes for
each image url column.
Returns:
A dataframe of joined prediction source and prediction results, or prediction results only.
"""
if img_cols is None:
img_cols = []
if isinstance(data, pd.DataFrame):
data = list(data.T.to_dict().values())
elif isinstance(data[0], six.string_types):
data = list(csv.DictReader(data, fieldnames=headers))
images = _download_images(data, img_cols)
predict_data = _get_predicton_csv_lines(data, headers, images)
if cloud:
parts = model_dir_or_id.split('.')
if len(parts) != 2:
raise ValueError('Invalid model name for cloud prediction. Use "model.version".')
predict_results = ml.ModelVersions(parts[0]).predict(parts[1], predict_data)
else:
tf_logging_level = logging.getLogger("tensorflow").level
logging.getLogger("tensorflow").setLevel(logging.WARNING)
try:
predict_results = _tf_predict(model_dir_or_id, predict_data)
finally:
logging.getLogger("tensorflow").setLevel(tf_logging_level)
df_r = pd.DataFrame(predict_results)
if not with_source:
return df_r
display_data = data
if show_image:
display_data = _get_display_data_with_images(data, images)
df_s = pd.DataFrame(display_data)
df = pd.concat([df_r, df_s], axis=1)
# Remove duplicate columns. All 'key' columns are duplicate here.
df = df.loc[:, ~df.columns.duplicated()]
return df | [
"def",
"get_prediction_results",
"(",
"model_dir_or_id",
",",
"data",
",",
"headers",
",",
"img_cols",
"=",
"None",
",",
"cloud",
"=",
"False",
",",
"with_source",
"=",
"True",
",",
"show_image",
"=",
"True",
")",
":",
"if",
"img_cols",
"is",
"None",
":",
"img_cols",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"data",
",",
"pd",
".",
"DataFrame",
")",
":",
"data",
"=",
"list",
"(",
"data",
".",
"T",
".",
"to_dict",
"(",
")",
".",
"values",
"(",
")",
")",
"elif",
"isinstance",
"(",
"data",
"[",
"0",
"]",
",",
"six",
".",
"string_types",
")",
":",
"data",
"=",
"list",
"(",
"csv",
".",
"DictReader",
"(",
"data",
",",
"fieldnames",
"=",
"headers",
")",
")",
"images",
"=",
"_download_images",
"(",
"data",
",",
"img_cols",
")",
"predict_data",
"=",
"_get_predicton_csv_lines",
"(",
"data",
",",
"headers",
",",
"images",
")",
"if",
"cloud",
":",
"parts",
"=",
"model_dir_or_id",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"parts",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"'Invalid model name for cloud prediction. Use \"model.version\".'",
")",
"predict_results",
"=",
"ml",
".",
"ModelVersions",
"(",
"parts",
"[",
"0",
"]",
")",
".",
"predict",
"(",
"parts",
"[",
"1",
"]",
",",
"predict_data",
")",
"else",
":",
"tf_logging_level",
"=",
"logging",
".",
"getLogger",
"(",
"\"tensorflow\"",
")",
".",
"level",
"logging",
".",
"getLogger",
"(",
"\"tensorflow\"",
")",
".",
"setLevel",
"(",
"logging",
".",
"WARNING",
")",
"try",
":",
"predict_results",
"=",
"_tf_predict",
"(",
"model_dir_or_id",
",",
"predict_data",
")",
"finally",
":",
"logging",
".",
"getLogger",
"(",
"\"tensorflow\"",
")",
".",
"setLevel",
"(",
"tf_logging_level",
")",
"df_r",
"=",
"pd",
".",
"DataFrame",
"(",
"predict_results",
")",
"if",
"not",
"with_source",
":",
"return",
"df_r",
"display_data",
"=",
"data",
"if",
"show_image",
":",
"display_data",
"=",
"_get_display_data_with_images",
"(",
"data",
",",
"images",
")",
"df_s",
"=",
"pd",
".",
"DataFrame",
"(",
"display_data",
")",
"df",
"=",
"pd",
".",
"concat",
"(",
"[",
"df_r",
",",
"df_s",
"]",
",",
"axis",
"=",
"1",
")",
"# Remove duplicate columns. All 'key' columns are duplicate here.",
"df",
"=",
"df",
".",
"loc",
"[",
":",
",",
"~",
"df",
".",
"columns",
".",
"duplicated",
"(",
")",
"]",
"return",
"df"
] | Predict with a specified model.
It predicts with the model, join source data with prediction results, and formats
the results so they can be displayed nicely in Datalab.
Args:
model_dir_or_id: The model directory if cloud is False, or model.version if cloud is True.
data: Can be a list of dictionaries, a list of csv lines, or a Pandas DataFrame. If it is not
a list of csv lines, data will be converted to csv lines first, using the orders specified
by headers and then send to model. For images, it can be image gs urls or in-memory PIL
images. Images will be converted to base64 encoded strings before prediction.
headers: the column names of data. It specifies the order of the columns when
serializing to csv lines for prediction.
img_cols: The image url columns. If specified, the img_urls will be converted to
base64 encoded image bytes.
with_source: Whether return a joined prediction source and prediction results, or prediction
results only.
show_image: When displaying prediction source, whether to add a column of image bytes for
each image url column.
Returns:
A dataframe of joined prediction source and prediction results, or prediction results only. | [
"Predict",
"with",
"a",
"specified",
"model",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_local_predict.py#L175-L239 | train | 237,665 |
googledatalab/pydatalab | google/datalab/contrib/mlworkbench/_local_predict.py | get_probs_for_labels | def get_probs_for_labels(labels, prediction_results):
""" Given ML Workbench prediction results, get probs of each label for each instance.
The prediction results are like:
[
{'predicted': 'daisy', 'probability': 0.8, 'predicted_2': 'rose', 'probability_2': 0.1},
{'predicted': 'sunflower', 'probability': 0.9, 'predicted_2': 'daisy', 'probability_2': 0.01},
...
]
Each instance is ordered by prob. But in some cases probs are needed for fixed
order of labels. For example, given labels = ['daisy', 'rose', 'sunflower'], the
results of above is expected to be:
[
[0.8, 0.1, 0.0],
[0.01, 0.0, 0.9],
...
]
Note that the sum of each instance may not be always 1. If model's top_n is set to
none-zero, and is less than number of labels, then prediction results may not contain
probs for all labels.
Args:
labels: a list of labels specifying the order of the labels.
prediction_results: a pandas DataFrame containing prediction results, usually returned
by get_prediction_results() call.
Returns:
A list of list of probs for each class.
"""
probs = []
if 'probability' in prediction_results:
# 'probability' exists so top-n is set to none zero, and results are like
# "predicted, predicted_2,...,probability,probability_2,...
for i, r in prediction_results.iterrows():
probs_one = [0.0] * len(labels)
for k, v in six.iteritems(r):
if v in labels and k.startswith('predicted'):
if k == 'predict':
prob_name = 'probability'
else:
prob_name = 'probability' + k[9:]
probs_one[labels.index(v)] = r[prob_name]
probs.append(probs_one)
return probs
else:
# 'probability' does not exist, so top-n is set to zero. Results are like
# "predicted, class_name1, class_name2,...
for i, r in prediction_results.iterrows():
probs_one = [0.0] * len(labels)
for k, v in six.iteritems(r):
if k in labels:
probs_one[labels.index(k)] = v
probs.append(probs_one)
return probs | python | def get_probs_for_labels(labels, prediction_results):
""" Given ML Workbench prediction results, get probs of each label for each instance.
The prediction results are like:
[
{'predicted': 'daisy', 'probability': 0.8, 'predicted_2': 'rose', 'probability_2': 0.1},
{'predicted': 'sunflower', 'probability': 0.9, 'predicted_2': 'daisy', 'probability_2': 0.01},
...
]
Each instance is ordered by prob. But in some cases probs are needed for fixed
order of labels. For example, given labels = ['daisy', 'rose', 'sunflower'], the
results of above is expected to be:
[
[0.8, 0.1, 0.0],
[0.01, 0.0, 0.9],
...
]
Note that the sum of each instance may not be always 1. If model's top_n is set to
none-zero, and is less than number of labels, then prediction results may not contain
probs for all labels.
Args:
labels: a list of labels specifying the order of the labels.
prediction_results: a pandas DataFrame containing prediction results, usually returned
by get_prediction_results() call.
Returns:
A list of list of probs for each class.
"""
probs = []
if 'probability' in prediction_results:
# 'probability' exists so top-n is set to none zero, and results are like
# "predicted, predicted_2,...,probability,probability_2,...
for i, r in prediction_results.iterrows():
probs_one = [0.0] * len(labels)
for k, v in six.iteritems(r):
if v in labels and k.startswith('predicted'):
if k == 'predict':
prob_name = 'probability'
else:
prob_name = 'probability' + k[9:]
probs_one[labels.index(v)] = r[prob_name]
probs.append(probs_one)
return probs
else:
# 'probability' does not exist, so top-n is set to zero. Results are like
# "predicted, class_name1, class_name2,...
for i, r in prediction_results.iterrows():
probs_one = [0.0] * len(labels)
for k, v in six.iteritems(r):
if k in labels:
probs_one[labels.index(k)] = v
probs.append(probs_one)
return probs | [
"def",
"get_probs_for_labels",
"(",
"labels",
",",
"prediction_results",
")",
":",
"probs",
"=",
"[",
"]",
"if",
"'probability'",
"in",
"prediction_results",
":",
"# 'probability' exists so top-n is set to none zero, and results are like",
"# \"predicted, predicted_2,...,probability,probability_2,...",
"for",
"i",
",",
"r",
"in",
"prediction_results",
".",
"iterrows",
"(",
")",
":",
"probs_one",
"=",
"[",
"0.0",
"]",
"*",
"len",
"(",
"labels",
")",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"r",
")",
":",
"if",
"v",
"in",
"labels",
"and",
"k",
".",
"startswith",
"(",
"'predicted'",
")",
":",
"if",
"k",
"==",
"'predict'",
":",
"prob_name",
"=",
"'probability'",
"else",
":",
"prob_name",
"=",
"'probability'",
"+",
"k",
"[",
"9",
":",
"]",
"probs_one",
"[",
"labels",
".",
"index",
"(",
"v",
")",
"]",
"=",
"r",
"[",
"prob_name",
"]",
"probs",
".",
"append",
"(",
"probs_one",
")",
"return",
"probs",
"else",
":",
"# 'probability' does not exist, so top-n is set to zero. Results are like",
"# \"predicted, class_name1, class_name2,...",
"for",
"i",
",",
"r",
"in",
"prediction_results",
".",
"iterrows",
"(",
")",
":",
"probs_one",
"=",
"[",
"0.0",
"]",
"*",
"len",
"(",
"labels",
")",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"r",
")",
":",
"if",
"k",
"in",
"labels",
":",
"probs_one",
"[",
"labels",
".",
"index",
"(",
"k",
")",
"]",
"=",
"v",
"probs",
".",
"append",
"(",
"probs_one",
")",
"return",
"probs"
] | Given ML Workbench prediction results, get probs of each label for each instance.
The prediction results are like:
[
{'predicted': 'daisy', 'probability': 0.8, 'predicted_2': 'rose', 'probability_2': 0.1},
{'predicted': 'sunflower', 'probability': 0.9, 'predicted_2': 'daisy', 'probability_2': 0.01},
...
]
Each instance is ordered by prob. But in some cases probs are needed for fixed
order of labels. For example, given labels = ['daisy', 'rose', 'sunflower'], the
results of above is expected to be:
[
[0.8, 0.1, 0.0],
[0.01, 0.0, 0.9],
...
]
Note that the sum of each instance may not be always 1. If model's top_n is set to
none-zero, and is less than number of labels, then prediction results may not contain
probs for all labels.
Args:
labels: a list of labels specifying the order of the labels.
prediction_results: a pandas DataFrame containing prediction results, usually returned
by get_prediction_results() call.
Returns:
A list of list of probs for each class. | [
"Given",
"ML",
"Workbench",
"prediction",
"results",
"get",
"probs",
"of",
"each",
"label",
"for",
"each",
"instance",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_local_predict.py#L242-L297 | train | 237,666 |
googledatalab/pydatalab | google/datalab/contrib/mlworkbench/_local_predict.py | local_batch_predict | def local_batch_predict(model_dir, csv_file_pattern, output_dir, output_format, batch_size=100):
""" Batch Predict with a specified model.
It does batch prediction, saves results to output files and also creates an output
schema file. The output file names are input file names prepended by 'predict_results_'.
Args:
model_dir: The model directory containing a SavedModel (usually saved_model.pb).
csv_file_pattern: a pattern of csv files as batch prediction source.
output_dir: the path of the output directory.
output_format: csv or json.
batch_size: Larger batch_size improves performance but may
cause more memory usage.
"""
file_io.recursive_create_dir(output_dir)
csv_files = file_io.get_matching_files(csv_file_pattern)
if len(csv_files) == 0:
raise ValueError('No files found given ' + csv_file_pattern)
with tf.Graph().as_default(), tf.Session() as sess:
input_alias_map, output_alias_map = _tf_load_model(sess, model_dir)
csv_tensor_name = list(input_alias_map.values())[0]
output_schema = _get_output_schema(sess, output_alias_map)
for csv_file in csv_files:
output_file = os.path.join(
output_dir,
'predict_results_' +
os.path.splitext(os.path.basename(csv_file))[0] + '.' + output_format)
with file_io.FileIO(output_file, 'w') as f:
prediction_source = _batch_csv_reader(csv_file, batch_size)
for batch in prediction_source:
batch = [l.rstrip() for l in batch if l]
predict_results = sess.run(fetches=output_alias_map, feed_dict={csv_tensor_name: batch})
formatted_results = _format_results(output_format, output_schema, predict_results)
f.write('\n'.join(formatted_results) + '\n')
file_io.write_string_to_file(os.path.join(output_dir, 'predict_results_schema.json'),
json.dumps(output_schema, indent=2)) | python | def local_batch_predict(model_dir, csv_file_pattern, output_dir, output_format, batch_size=100):
""" Batch Predict with a specified model.
It does batch prediction, saves results to output files and also creates an output
schema file. The output file names are input file names prepended by 'predict_results_'.
Args:
model_dir: The model directory containing a SavedModel (usually saved_model.pb).
csv_file_pattern: a pattern of csv files as batch prediction source.
output_dir: the path of the output directory.
output_format: csv or json.
batch_size: Larger batch_size improves performance but may
cause more memory usage.
"""
file_io.recursive_create_dir(output_dir)
csv_files = file_io.get_matching_files(csv_file_pattern)
if len(csv_files) == 0:
raise ValueError('No files found given ' + csv_file_pattern)
with tf.Graph().as_default(), tf.Session() as sess:
input_alias_map, output_alias_map = _tf_load_model(sess, model_dir)
csv_tensor_name = list(input_alias_map.values())[0]
output_schema = _get_output_schema(sess, output_alias_map)
for csv_file in csv_files:
output_file = os.path.join(
output_dir,
'predict_results_' +
os.path.splitext(os.path.basename(csv_file))[0] + '.' + output_format)
with file_io.FileIO(output_file, 'w') as f:
prediction_source = _batch_csv_reader(csv_file, batch_size)
for batch in prediction_source:
batch = [l.rstrip() for l in batch if l]
predict_results = sess.run(fetches=output_alias_map, feed_dict={csv_tensor_name: batch})
formatted_results = _format_results(output_format, output_schema, predict_results)
f.write('\n'.join(formatted_results) + '\n')
file_io.write_string_to_file(os.path.join(output_dir, 'predict_results_schema.json'),
json.dumps(output_schema, indent=2)) | [
"def",
"local_batch_predict",
"(",
"model_dir",
",",
"csv_file_pattern",
",",
"output_dir",
",",
"output_format",
",",
"batch_size",
"=",
"100",
")",
":",
"file_io",
".",
"recursive_create_dir",
"(",
"output_dir",
")",
"csv_files",
"=",
"file_io",
".",
"get_matching_files",
"(",
"csv_file_pattern",
")",
"if",
"len",
"(",
"csv_files",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'No files found given '",
"+",
"csv_file_pattern",
")",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
")",
",",
"tf",
".",
"Session",
"(",
")",
"as",
"sess",
":",
"input_alias_map",
",",
"output_alias_map",
"=",
"_tf_load_model",
"(",
"sess",
",",
"model_dir",
")",
"csv_tensor_name",
"=",
"list",
"(",
"input_alias_map",
".",
"values",
"(",
")",
")",
"[",
"0",
"]",
"output_schema",
"=",
"_get_output_schema",
"(",
"sess",
",",
"output_alias_map",
")",
"for",
"csv_file",
"in",
"csv_files",
":",
"output_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"'predict_results_'",
"+",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"csv_file",
")",
")",
"[",
"0",
"]",
"+",
"'.'",
"+",
"output_format",
")",
"with",
"file_io",
".",
"FileIO",
"(",
"output_file",
",",
"'w'",
")",
"as",
"f",
":",
"prediction_source",
"=",
"_batch_csv_reader",
"(",
"csv_file",
",",
"batch_size",
")",
"for",
"batch",
"in",
"prediction_source",
":",
"batch",
"=",
"[",
"l",
".",
"rstrip",
"(",
")",
"for",
"l",
"in",
"batch",
"if",
"l",
"]",
"predict_results",
"=",
"sess",
".",
"run",
"(",
"fetches",
"=",
"output_alias_map",
",",
"feed_dict",
"=",
"{",
"csv_tensor_name",
":",
"batch",
"}",
")",
"formatted_results",
"=",
"_format_results",
"(",
"output_format",
",",
"output_schema",
",",
"predict_results",
")",
"f",
".",
"write",
"(",
"'\\n'",
".",
"join",
"(",
"formatted_results",
")",
"+",
"'\\n'",
")",
"file_io",
".",
"write_string_to_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"'predict_results_schema.json'",
")",
",",
"json",
".",
"dumps",
"(",
"output_schema",
",",
"indent",
"=",
"2",
")",
")"
] | Batch Predict with a specified model.
It does batch prediction, saves results to output files and also creates an output
schema file. The output file names are input file names prepended by 'predict_results_'.
Args:
model_dir: The model directory containing a SavedModel (usually saved_model.pb).
csv_file_pattern: a pattern of csv files as batch prediction source.
output_dir: the path of the output directory.
output_format: csv or json.
batch_size: Larger batch_size improves performance but may
cause more memory usage. | [
"Batch",
"Predict",
"with",
"a",
"specified",
"model",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_local_predict.py#L359-L397 | train | 237,667 |
googledatalab/pydatalab | google/datalab/ml/_job.py | Job.submit_training | def submit_training(job_request, job_id=None):
"""Submit a training job.
Args:
job_request: the arguments of the training job in a dict. For example,
{
'package_uris': 'gs://my-bucket/iris/trainer-0.1.tar.gz',
'python_module': 'trainer.task',
'scale_tier': 'BASIC',
'region': 'us-central1',
'args': {
'train_data_paths': ['gs://mubucket/data/features_train'],
'eval_data_paths': ['gs://mubucket/data/features_eval'],
'metadata_path': 'gs://mubucket/data/metadata.yaml',
'output_path': 'gs://mubucket/data/mymodel/',
}
}
If 'args' is present in job_request and is a dict, it will be expanded to
--key value or --key list_item_0 --key list_item_1, ...
job_id: id for the training job. If None, an id based on timestamp will be generated.
Returns:
A Job object representing the cloud training job.
"""
new_job_request = dict(job_request)
# convert job_args from dict to list as service required.
if 'args' in job_request and isinstance(job_request['args'], dict):
job_args = job_request['args']
args = []
for k, v in six.iteritems(job_args):
if isinstance(v, list):
for item in v:
args.append('--' + str(k))
args.append(str(item))
else:
args.append('--' + str(k))
args.append(str(v))
new_job_request['args'] = args
if job_id is None:
job_id = datetime.datetime.now().strftime('%y%m%d_%H%M%S')
if 'python_module' in new_job_request:
job_id = new_job_request['python_module'].replace('.', '_') + \
'_' + job_id
job = {
'job_id': job_id,
'training_input': new_job_request,
}
context = datalab.Context.default()
cloudml = discovery.build('ml', 'v1', credentials=context.credentials)
request = cloudml.projects().jobs().create(body=job,
parent='projects/' + context.project_id)
request.headers['user-agent'] = 'GoogleCloudDataLab/1.0'
request.execute()
return Job(job_id) | python | def submit_training(job_request, job_id=None):
"""Submit a training job.
Args:
job_request: the arguments of the training job in a dict. For example,
{
'package_uris': 'gs://my-bucket/iris/trainer-0.1.tar.gz',
'python_module': 'trainer.task',
'scale_tier': 'BASIC',
'region': 'us-central1',
'args': {
'train_data_paths': ['gs://mubucket/data/features_train'],
'eval_data_paths': ['gs://mubucket/data/features_eval'],
'metadata_path': 'gs://mubucket/data/metadata.yaml',
'output_path': 'gs://mubucket/data/mymodel/',
}
}
If 'args' is present in job_request and is a dict, it will be expanded to
--key value or --key list_item_0 --key list_item_1, ...
job_id: id for the training job. If None, an id based on timestamp will be generated.
Returns:
A Job object representing the cloud training job.
"""
new_job_request = dict(job_request)
# convert job_args from dict to list as service required.
if 'args' in job_request and isinstance(job_request['args'], dict):
job_args = job_request['args']
args = []
for k, v in six.iteritems(job_args):
if isinstance(v, list):
for item in v:
args.append('--' + str(k))
args.append(str(item))
else:
args.append('--' + str(k))
args.append(str(v))
new_job_request['args'] = args
if job_id is None:
job_id = datetime.datetime.now().strftime('%y%m%d_%H%M%S')
if 'python_module' in new_job_request:
job_id = new_job_request['python_module'].replace('.', '_') + \
'_' + job_id
job = {
'job_id': job_id,
'training_input': new_job_request,
}
context = datalab.Context.default()
cloudml = discovery.build('ml', 'v1', credentials=context.credentials)
request = cloudml.projects().jobs().create(body=job,
parent='projects/' + context.project_id)
request.headers['user-agent'] = 'GoogleCloudDataLab/1.0'
request.execute()
return Job(job_id) | [
"def",
"submit_training",
"(",
"job_request",
",",
"job_id",
"=",
"None",
")",
":",
"new_job_request",
"=",
"dict",
"(",
"job_request",
")",
"# convert job_args from dict to list as service required.",
"if",
"'args'",
"in",
"job_request",
"and",
"isinstance",
"(",
"job_request",
"[",
"'args'",
"]",
",",
"dict",
")",
":",
"job_args",
"=",
"job_request",
"[",
"'args'",
"]",
"args",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"job_args",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"list",
")",
":",
"for",
"item",
"in",
"v",
":",
"args",
".",
"append",
"(",
"'--'",
"+",
"str",
"(",
"k",
")",
")",
"args",
".",
"append",
"(",
"str",
"(",
"item",
")",
")",
"else",
":",
"args",
".",
"append",
"(",
"'--'",
"+",
"str",
"(",
"k",
")",
")",
"args",
".",
"append",
"(",
"str",
"(",
"v",
")",
")",
"new_job_request",
"[",
"'args'",
"]",
"=",
"args",
"if",
"job_id",
"is",
"None",
":",
"job_id",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"'%y%m%d_%H%M%S'",
")",
"if",
"'python_module'",
"in",
"new_job_request",
":",
"job_id",
"=",
"new_job_request",
"[",
"'python_module'",
"]",
".",
"replace",
"(",
"'.'",
",",
"'_'",
")",
"+",
"'_'",
"+",
"job_id",
"job",
"=",
"{",
"'job_id'",
":",
"job_id",
",",
"'training_input'",
":",
"new_job_request",
",",
"}",
"context",
"=",
"datalab",
".",
"Context",
".",
"default",
"(",
")",
"cloudml",
"=",
"discovery",
".",
"build",
"(",
"'ml'",
",",
"'v1'",
",",
"credentials",
"=",
"context",
".",
"credentials",
")",
"request",
"=",
"cloudml",
".",
"projects",
"(",
")",
".",
"jobs",
"(",
")",
".",
"create",
"(",
"body",
"=",
"job",
",",
"parent",
"=",
"'projects/'",
"+",
"context",
".",
"project_id",
")",
"request",
".",
"headers",
"[",
"'user-agent'",
"]",
"=",
"'GoogleCloudDataLab/1.0'",
"request",
".",
"execute",
"(",
")",
"return",
"Job",
"(",
"job_id",
")"
] | Submit a training job.
Args:
job_request: the arguments of the training job in a dict. For example,
{
'package_uris': 'gs://my-bucket/iris/trainer-0.1.tar.gz',
'python_module': 'trainer.task',
'scale_tier': 'BASIC',
'region': 'us-central1',
'args': {
'train_data_paths': ['gs://mubucket/data/features_train'],
'eval_data_paths': ['gs://mubucket/data/features_eval'],
'metadata_path': 'gs://mubucket/data/metadata.yaml',
'output_path': 'gs://mubucket/data/mymodel/',
}
}
If 'args' is present in job_request and is a dict, it will be expanded to
--key value or --key list_item_0 --key list_item_1, ...
job_id: id for the training job. If None, an id based on timestamp will be generated.
Returns:
A Job object representing the cloud training job. | [
"Submit",
"a",
"training",
"job",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_job.py#L62-L116 | train | 237,668 |
googledatalab/pydatalab | google/datalab/ml/_job.py | Job.submit_batch_prediction | def submit_batch_prediction(job_request, job_id=None):
"""Submit a batch prediction job.
Args:
job_request: the arguments of the training job in a dict. For example,
{
'version_name': 'projects/my-project/models/my-model/versions/my-version',
'data_format': 'TEXT',
'input_paths': ['gs://my_bucket/my_file.csv'],
'output_path': 'gs://my_bucket/predict_output',
'region': 'us-central1',
'max_worker_count': 1,
}
job_id: id for the training job. If None, an id based on timestamp will be generated.
Returns:
A Job object representing the batch prediction job.
"""
if job_id is None:
job_id = 'prediction_' + datetime.datetime.now().strftime('%y%m%d_%H%M%S')
job = {
'job_id': job_id,
'prediction_input': job_request,
}
context = datalab.Context.default()
cloudml = discovery.build('ml', 'v1', credentials=context.credentials)
request = cloudml.projects().jobs().create(body=job,
parent='projects/' + context.project_id)
request.headers['user-agent'] = 'GoogleCloudDataLab/1.0'
request.execute()
return Job(job_id) | python | def submit_batch_prediction(job_request, job_id=None):
"""Submit a batch prediction job.
Args:
job_request: the arguments of the training job in a dict. For example,
{
'version_name': 'projects/my-project/models/my-model/versions/my-version',
'data_format': 'TEXT',
'input_paths': ['gs://my_bucket/my_file.csv'],
'output_path': 'gs://my_bucket/predict_output',
'region': 'us-central1',
'max_worker_count': 1,
}
job_id: id for the training job. If None, an id based on timestamp will be generated.
Returns:
A Job object representing the batch prediction job.
"""
if job_id is None:
job_id = 'prediction_' + datetime.datetime.now().strftime('%y%m%d_%H%M%S')
job = {
'job_id': job_id,
'prediction_input': job_request,
}
context = datalab.Context.default()
cloudml = discovery.build('ml', 'v1', credentials=context.credentials)
request = cloudml.projects().jobs().create(body=job,
parent='projects/' + context.project_id)
request.headers['user-agent'] = 'GoogleCloudDataLab/1.0'
request.execute()
return Job(job_id) | [
"def",
"submit_batch_prediction",
"(",
"job_request",
",",
"job_id",
"=",
"None",
")",
":",
"if",
"job_id",
"is",
"None",
":",
"job_id",
"=",
"'prediction_'",
"+",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"'%y%m%d_%H%M%S'",
")",
"job",
"=",
"{",
"'job_id'",
":",
"job_id",
",",
"'prediction_input'",
":",
"job_request",
",",
"}",
"context",
"=",
"datalab",
".",
"Context",
".",
"default",
"(",
")",
"cloudml",
"=",
"discovery",
".",
"build",
"(",
"'ml'",
",",
"'v1'",
",",
"credentials",
"=",
"context",
".",
"credentials",
")",
"request",
"=",
"cloudml",
".",
"projects",
"(",
")",
".",
"jobs",
"(",
")",
".",
"create",
"(",
"body",
"=",
"job",
",",
"parent",
"=",
"'projects/'",
"+",
"context",
".",
"project_id",
")",
"request",
".",
"headers",
"[",
"'user-agent'",
"]",
"=",
"'GoogleCloudDataLab/1.0'",
"request",
".",
"execute",
"(",
")",
"return",
"Job",
"(",
"job_id",
")"
] | Submit a batch prediction job.
Args:
job_request: the arguments of the training job in a dict. For example,
{
'version_name': 'projects/my-project/models/my-model/versions/my-version',
'data_format': 'TEXT',
'input_paths': ['gs://my_bucket/my_file.csv'],
'output_path': 'gs://my_bucket/predict_output',
'region': 'us-central1',
'max_worker_count': 1,
}
job_id: id for the training job. If None, an id based on timestamp will be generated.
Returns:
A Job object representing the batch prediction job. | [
"Submit",
"a",
"batch",
"prediction",
"job",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_job.py#L119-L151 | train | 237,669 |
googledatalab/pydatalab | solutionbox/image_classification/mltoolbox/image/classification/_inceptionlib.py | _reduced_kernel_size_for_small_input | def _reduced_kernel_size_for_small_input(input_tensor, kernel_size):
"""Define kernel size which is automatically reduced for small input.
If the shape of the input images is unknown at graph construction time this
function assumes that the input images are is large enough.
Args:
input_tensor: input tensor of size [batch_size, height, width, channels].
kernel_size: desired kernel size of length 2: [kernel_height, kernel_width]
Returns:
a tensor with the kernel size.
TODO(jrru): Make this function work with unknown shapes. Theoretically, this
can be done with the code below. Problems are two-fold: (1) If the shape was
known, it will be lost. (2) inception.slim.ops._two_element_tuple cannot
handle tensors that define the kernel size.
shape = tf.shape(input_tensor)
return = tf.stack([tf.minimum(shape[1], kernel_size[0]),
tf.minimum(shape[2], kernel_size[1])])
"""
shape = input_tensor.get_shape().as_list()
if shape[1] is None or shape[2] is None:
kernel_size_out = kernel_size
else:
kernel_size_out = [min(shape[1], kernel_size[0]),
min(shape[2], kernel_size[1])]
return kernel_size_out | python | def _reduced_kernel_size_for_small_input(input_tensor, kernel_size):
"""Define kernel size which is automatically reduced for small input.
If the shape of the input images is unknown at graph construction time this
function assumes that the input images are is large enough.
Args:
input_tensor: input tensor of size [batch_size, height, width, channels].
kernel_size: desired kernel size of length 2: [kernel_height, kernel_width]
Returns:
a tensor with the kernel size.
TODO(jrru): Make this function work with unknown shapes. Theoretically, this
can be done with the code below. Problems are two-fold: (1) If the shape was
known, it will be lost. (2) inception.slim.ops._two_element_tuple cannot
handle tensors that define the kernel size.
shape = tf.shape(input_tensor)
return = tf.stack([tf.minimum(shape[1], kernel_size[0]),
tf.minimum(shape[2], kernel_size[1])])
"""
shape = input_tensor.get_shape().as_list()
if shape[1] is None or shape[2] is None:
kernel_size_out = kernel_size
else:
kernel_size_out = [min(shape[1], kernel_size[0]),
min(shape[2], kernel_size[1])]
return kernel_size_out | [
"def",
"_reduced_kernel_size_for_small_input",
"(",
"input_tensor",
",",
"kernel_size",
")",
":",
"shape",
"=",
"input_tensor",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"if",
"shape",
"[",
"1",
"]",
"is",
"None",
"or",
"shape",
"[",
"2",
"]",
"is",
"None",
":",
"kernel_size_out",
"=",
"kernel_size",
"else",
":",
"kernel_size_out",
"=",
"[",
"min",
"(",
"shape",
"[",
"1",
"]",
",",
"kernel_size",
"[",
"0",
"]",
")",
",",
"min",
"(",
"shape",
"[",
"2",
"]",
",",
"kernel_size",
"[",
"1",
"]",
")",
"]",
"return",
"kernel_size_out"
] | Define kernel size which is automatically reduced for small input.
If the shape of the input images is unknown at graph construction time this
function assumes that the input images are is large enough.
Args:
input_tensor: input tensor of size [batch_size, height, width, channels].
kernel_size: desired kernel size of length 2: [kernel_height, kernel_width]
Returns:
a tensor with the kernel size.
TODO(jrru): Make this function work with unknown shapes. Theoretically, this
can be done with the code below. Problems are two-fold: (1) If the shape was
known, it will be lost. (2) inception.slim.ops._two_element_tuple cannot
handle tensors that define the kernel size.
shape = tf.shape(input_tensor)
return = tf.stack([tf.minimum(shape[1], kernel_size[0]),
tf.minimum(shape[2], kernel_size[1])]) | [
"Define",
"kernel",
"size",
"which",
"is",
"automatically",
"reduced",
"for",
"small",
"input",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_inceptionlib.py#L556-L584 | train | 237,670 |
googledatalab/pydatalab | solutionbox/image_classification/mltoolbox/image/classification/_inceptionlib.py | inception_v3_arg_scope | def inception_v3_arg_scope(weight_decay=0.00004,
stddev=0.1,
batch_norm_var_collection='moving_vars'):
"""Defines the default InceptionV3 arg scope.
Args:
weight_decay: The weight decay to use for regularizing the model.
stddev: The standard deviation of the trunctated normal weight initializer.
batch_norm_var_collection: The name of the collection for the batch norm
variables.
Returns:
An `arg_scope` to use for the inception v3 model.
"""
batch_norm_params = {
# Decay for the moving averages.
'decay': 0.9997,
# epsilon to prevent 0s in variance.
'epsilon': 0.001,
# collection containing update_ops.
'updates_collections': tf.GraphKeys.UPDATE_OPS,
# collection containing the moving mean and moving variance.
'variables_collections': {
'beta': None,
'gamma': None,
'moving_mean': [batch_norm_var_collection],
'moving_variance': [batch_norm_var_collection],
}
}
# Set weight_decay for weights in Conv and FC layers.
with slim.arg_scope([slim.conv2d, slim.fully_connected],
weights_regularizer=slim.l2_regularizer(weight_decay)):
with slim.arg_scope([slim.conv2d],
weights_initializer=tf.truncated_normal_initializer(stddev=stddev),
activation_fn=tf.nn.relu, normalizer_fn=slim.batch_norm,
normalizer_params=batch_norm_params) as sc:
return sc | python | def inception_v3_arg_scope(weight_decay=0.00004,
stddev=0.1,
batch_norm_var_collection='moving_vars'):
"""Defines the default InceptionV3 arg scope.
Args:
weight_decay: The weight decay to use for regularizing the model.
stddev: The standard deviation of the trunctated normal weight initializer.
batch_norm_var_collection: The name of the collection for the batch norm
variables.
Returns:
An `arg_scope` to use for the inception v3 model.
"""
batch_norm_params = {
# Decay for the moving averages.
'decay': 0.9997,
# epsilon to prevent 0s in variance.
'epsilon': 0.001,
# collection containing update_ops.
'updates_collections': tf.GraphKeys.UPDATE_OPS,
# collection containing the moving mean and moving variance.
'variables_collections': {
'beta': None,
'gamma': None,
'moving_mean': [batch_norm_var_collection],
'moving_variance': [batch_norm_var_collection],
}
}
# Set weight_decay for weights in Conv and FC layers.
with slim.arg_scope([slim.conv2d, slim.fully_connected],
weights_regularizer=slim.l2_regularizer(weight_decay)):
with slim.arg_scope([slim.conv2d],
weights_initializer=tf.truncated_normal_initializer(stddev=stddev),
activation_fn=tf.nn.relu, normalizer_fn=slim.batch_norm,
normalizer_params=batch_norm_params) as sc:
return sc | [
"def",
"inception_v3_arg_scope",
"(",
"weight_decay",
"=",
"0.00004",
",",
"stddev",
"=",
"0.1",
",",
"batch_norm_var_collection",
"=",
"'moving_vars'",
")",
":",
"batch_norm_params",
"=",
"{",
"# Decay for the moving averages.",
"'decay'",
":",
"0.9997",
",",
"# epsilon to prevent 0s in variance.",
"'epsilon'",
":",
"0.001",
",",
"# collection containing update_ops.",
"'updates_collections'",
":",
"tf",
".",
"GraphKeys",
".",
"UPDATE_OPS",
",",
"# collection containing the moving mean and moving variance.",
"'variables_collections'",
":",
"{",
"'beta'",
":",
"None",
",",
"'gamma'",
":",
"None",
",",
"'moving_mean'",
":",
"[",
"batch_norm_var_collection",
"]",
",",
"'moving_variance'",
":",
"[",
"batch_norm_var_collection",
"]",
",",
"}",
"}",
"# Set weight_decay for weights in Conv and FC layers.",
"with",
"slim",
".",
"arg_scope",
"(",
"[",
"slim",
".",
"conv2d",
",",
"slim",
".",
"fully_connected",
"]",
",",
"weights_regularizer",
"=",
"slim",
".",
"l2_regularizer",
"(",
"weight_decay",
")",
")",
":",
"with",
"slim",
".",
"arg_scope",
"(",
"[",
"slim",
".",
"conv2d",
"]",
",",
"weights_initializer",
"=",
"tf",
".",
"truncated_normal_initializer",
"(",
"stddev",
"=",
"stddev",
")",
",",
"activation_fn",
"=",
"tf",
".",
"nn",
".",
"relu",
",",
"normalizer_fn",
"=",
"slim",
".",
"batch_norm",
",",
"normalizer_params",
"=",
"batch_norm_params",
")",
"as",
"sc",
":",
"return",
"sc"
] | Defines the default InceptionV3 arg scope.
Args:
weight_decay: The weight decay to use for regularizing the model.
stddev: The standard deviation of the trunctated normal weight initializer.
batch_norm_var_collection: The name of the collection for the batch norm
variables.
Returns:
An `arg_scope` to use for the inception v3 model. | [
"Defines",
"the",
"default",
"InceptionV3",
"arg",
"scope",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_inceptionlib.py#L587-L624 | train | 237,671 |
googledatalab/pydatalab | solutionbox/image_classification/mltoolbox/image/classification/_local.py | Local.preprocess | def preprocess(train_dataset, output_dir, eval_dataset, checkpoint):
"""Preprocess data locally."""
import apache_beam as beam
from google.datalab.utils import LambdaJob
from . import _preprocess
if checkpoint is None:
checkpoint = _util._DEFAULT_CHECKPOINT_GSURL
job_id = ('preprocess-image-classification-' +
datetime.datetime.now().strftime('%y%m%d-%H%M%S'))
# Project is needed for bigquery data source, even in local run.
options = {
'project': _util.default_project(),
}
opts = beam.pipeline.PipelineOptions(flags=[], **options)
p = beam.Pipeline('DirectRunner', options=opts)
_preprocess.configure_pipeline(p, train_dataset, eval_dataset, checkpoint, output_dir, job_id)
job = LambdaJob(lambda: p.run().wait_until_finish(), job_id)
return job | python | def preprocess(train_dataset, output_dir, eval_dataset, checkpoint):
"""Preprocess data locally."""
import apache_beam as beam
from google.datalab.utils import LambdaJob
from . import _preprocess
if checkpoint is None:
checkpoint = _util._DEFAULT_CHECKPOINT_GSURL
job_id = ('preprocess-image-classification-' +
datetime.datetime.now().strftime('%y%m%d-%H%M%S'))
# Project is needed for bigquery data source, even in local run.
options = {
'project': _util.default_project(),
}
opts = beam.pipeline.PipelineOptions(flags=[], **options)
p = beam.Pipeline('DirectRunner', options=opts)
_preprocess.configure_pipeline(p, train_dataset, eval_dataset, checkpoint, output_dir, job_id)
job = LambdaJob(lambda: p.run().wait_until_finish(), job_id)
return job | [
"def",
"preprocess",
"(",
"train_dataset",
",",
"output_dir",
",",
"eval_dataset",
",",
"checkpoint",
")",
":",
"import",
"apache_beam",
"as",
"beam",
"from",
"google",
".",
"datalab",
".",
"utils",
"import",
"LambdaJob",
"from",
".",
"import",
"_preprocess",
"if",
"checkpoint",
"is",
"None",
":",
"checkpoint",
"=",
"_util",
".",
"_DEFAULT_CHECKPOINT_GSURL",
"job_id",
"=",
"(",
"'preprocess-image-classification-'",
"+",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"'%y%m%d-%H%M%S'",
")",
")",
"# Project is needed for bigquery data source, even in local run.",
"options",
"=",
"{",
"'project'",
":",
"_util",
".",
"default_project",
"(",
")",
",",
"}",
"opts",
"=",
"beam",
".",
"pipeline",
".",
"PipelineOptions",
"(",
"flags",
"=",
"[",
"]",
",",
"*",
"*",
"options",
")",
"p",
"=",
"beam",
".",
"Pipeline",
"(",
"'DirectRunner'",
",",
"options",
"=",
"opts",
")",
"_preprocess",
".",
"configure_pipeline",
"(",
"p",
",",
"train_dataset",
",",
"eval_dataset",
",",
"checkpoint",
",",
"output_dir",
",",
"job_id",
")",
"job",
"=",
"LambdaJob",
"(",
"lambda",
":",
"p",
".",
"run",
"(",
")",
".",
"wait_until_finish",
"(",
")",
",",
"job_id",
")",
"return",
"job"
] | Preprocess data locally. | [
"Preprocess",
"data",
"locally",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_local.py#L32-L51 | train | 237,672 |
googledatalab/pydatalab | solutionbox/image_classification/mltoolbox/image/classification/_local.py | Local.train | def train(input_dir, batch_size, max_steps, output_dir, checkpoint):
"""Train model locally."""
from google.datalab.utils import LambdaJob
if checkpoint is None:
checkpoint = _util._DEFAULT_CHECKPOINT_GSURL
labels = _util.get_labels(input_dir)
model = _model.Model(labels, 0.5, checkpoint)
task_data = {'type': 'master', 'index': 0}
task = type('TaskSpec', (object,), task_data)
job = LambdaJob(lambda: _trainer.Trainer(input_dir, batch_size, max_steps, output_dir,
model, None, task).run_training(), 'training')
return job | python | def train(input_dir, batch_size, max_steps, output_dir, checkpoint):
"""Train model locally."""
from google.datalab.utils import LambdaJob
if checkpoint is None:
checkpoint = _util._DEFAULT_CHECKPOINT_GSURL
labels = _util.get_labels(input_dir)
model = _model.Model(labels, 0.5, checkpoint)
task_data = {'type': 'master', 'index': 0}
task = type('TaskSpec', (object,), task_data)
job = LambdaJob(lambda: _trainer.Trainer(input_dir, batch_size, max_steps, output_dir,
model, None, task).run_training(), 'training')
return job | [
"def",
"train",
"(",
"input_dir",
",",
"batch_size",
",",
"max_steps",
",",
"output_dir",
",",
"checkpoint",
")",
":",
"from",
"google",
".",
"datalab",
".",
"utils",
"import",
"LambdaJob",
"if",
"checkpoint",
"is",
"None",
":",
"checkpoint",
"=",
"_util",
".",
"_DEFAULT_CHECKPOINT_GSURL",
"labels",
"=",
"_util",
".",
"get_labels",
"(",
"input_dir",
")",
"model",
"=",
"_model",
".",
"Model",
"(",
"labels",
",",
"0.5",
",",
"checkpoint",
")",
"task_data",
"=",
"{",
"'type'",
":",
"'master'",
",",
"'index'",
":",
"0",
"}",
"task",
"=",
"type",
"(",
"'TaskSpec'",
",",
"(",
"object",
",",
")",
",",
"task_data",
")",
"job",
"=",
"LambdaJob",
"(",
"lambda",
":",
"_trainer",
".",
"Trainer",
"(",
"input_dir",
",",
"batch_size",
",",
"max_steps",
",",
"output_dir",
",",
"model",
",",
"None",
",",
"task",
")",
".",
"run_training",
"(",
")",
",",
"'training'",
")",
"return",
"job"
] | Train model locally. | [
"Train",
"model",
"locally",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_local.py#L54-L67 | train | 237,673 |
googledatalab/pydatalab | solutionbox/image_classification/mltoolbox/image/classification/_local.py | Local.predict | def predict(model_dir, image_files, resize, show_image):
"""Predict using an model in a local or GCS directory."""
from . import _predictor
images = _util.load_images(image_files, resize=resize)
labels_and_scores = _predictor.predict(model_dir, images)
results = zip(image_files, images, labels_and_scores)
ret = _util.process_prediction_results(results, show_image)
return ret | python | def predict(model_dir, image_files, resize, show_image):
"""Predict using an model in a local or GCS directory."""
from . import _predictor
images = _util.load_images(image_files, resize=resize)
labels_and_scores = _predictor.predict(model_dir, images)
results = zip(image_files, images, labels_and_scores)
ret = _util.process_prediction_results(results, show_image)
return ret | [
"def",
"predict",
"(",
"model_dir",
",",
"image_files",
",",
"resize",
",",
"show_image",
")",
":",
"from",
".",
"import",
"_predictor",
"images",
"=",
"_util",
".",
"load_images",
"(",
"image_files",
",",
"resize",
"=",
"resize",
")",
"labels_and_scores",
"=",
"_predictor",
".",
"predict",
"(",
"model_dir",
",",
"images",
")",
"results",
"=",
"zip",
"(",
"image_files",
",",
"images",
",",
"labels_and_scores",
")",
"ret",
"=",
"_util",
".",
"process_prediction_results",
"(",
"results",
",",
"show_image",
")",
"return",
"ret"
] | Predict using an model in a local or GCS directory. | [
"Predict",
"using",
"an",
"model",
"in",
"a",
"local",
"or",
"GCS",
"directory",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_local.py#L70-L79 | train | 237,674 |
googledatalab/pydatalab | solutionbox/image_classification/mltoolbox/image/classification/_local.py | Local.batch_predict | def batch_predict(dataset, model_dir, output_csv, output_bq_table):
"""Batch predict running locally."""
import apache_beam as beam
from google.datalab.utils import LambdaJob
from . import _predictor
if output_csv is None and output_bq_table is None:
raise ValueError('output_csv and output_bq_table cannot both be None.')
job_id = ('batch-predict-image-classification-' +
datetime.datetime.now().strftime('%y%m%d-%H%M%S'))
# Project is needed for bigquery data source, even in local run.
options = {
'project': _util.default_project(),
}
opts = beam.pipeline.PipelineOptions(flags=[], **options)
p = beam.Pipeline('DirectRunner', options=opts)
_predictor.configure_pipeline(p, dataset, model_dir, output_csv, output_bq_table)
job = LambdaJob(lambda: p.run().wait_until_finish(), job_id)
return job | python | def batch_predict(dataset, model_dir, output_csv, output_bq_table):
"""Batch predict running locally."""
import apache_beam as beam
from google.datalab.utils import LambdaJob
from . import _predictor
if output_csv is None and output_bq_table is None:
raise ValueError('output_csv and output_bq_table cannot both be None.')
job_id = ('batch-predict-image-classification-' +
datetime.datetime.now().strftime('%y%m%d-%H%M%S'))
# Project is needed for bigquery data source, even in local run.
options = {
'project': _util.default_project(),
}
opts = beam.pipeline.PipelineOptions(flags=[], **options)
p = beam.Pipeline('DirectRunner', options=opts)
_predictor.configure_pipeline(p, dataset, model_dir, output_csv, output_bq_table)
job = LambdaJob(lambda: p.run().wait_until_finish(), job_id)
return job | [
"def",
"batch_predict",
"(",
"dataset",
",",
"model_dir",
",",
"output_csv",
",",
"output_bq_table",
")",
":",
"import",
"apache_beam",
"as",
"beam",
"from",
"google",
".",
"datalab",
".",
"utils",
"import",
"LambdaJob",
"from",
".",
"import",
"_predictor",
"if",
"output_csv",
"is",
"None",
"and",
"output_bq_table",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'output_csv and output_bq_table cannot both be None.'",
")",
"job_id",
"=",
"(",
"'batch-predict-image-classification-'",
"+",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"'%y%m%d-%H%M%S'",
")",
")",
"# Project is needed for bigquery data source, even in local run.",
"options",
"=",
"{",
"'project'",
":",
"_util",
".",
"default_project",
"(",
")",
",",
"}",
"opts",
"=",
"beam",
".",
"pipeline",
".",
"PipelineOptions",
"(",
"flags",
"=",
"[",
"]",
",",
"*",
"*",
"options",
")",
"p",
"=",
"beam",
".",
"Pipeline",
"(",
"'DirectRunner'",
",",
"options",
"=",
"opts",
")",
"_predictor",
".",
"configure_pipeline",
"(",
"p",
",",
"dataset",
",",
"model_dir",
",",
"output_csv",
",",
"output_bq_table",
")",
"job",
"=",
"LambdaJob",
"(",
"lambda",
":",
"p",
".",
"run",
"(",
")",
".",
"wait_until_finish",
"(",
")",
",",
"job_id",
")",
"return",
"job"
] | Batch predict running locally. | [
"Batch",
"predict",
"running",
"locally",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_local.py#L82-L103 | train | 237,675 |
googledatalab/pydatalab | datalab/utils/_job.py | Job.result | def result(self):
""" Get the result for a job. This will block if the job is incomplete.
Returns:
The result for the Job.
Raises:
An exception if the Job resulted in an exception.
"""
self.wait()
if self._fatal_error:
raise self._fatal_error
return self._result | python | def result(self):
""" Get the result for a job. This will block if the job is incomplete.
Returns:
The result for the Job.
Raises:
An exception if the Job resulted in an exception.
"""
self.wait()
if self._fatal_error:
raise self._fatal_error
return self._result | [
"def",
"result",
"(",
"self",
")",
":",
"self",
".",
"wait",
"(",
")",
"if",
"self",
".",
"_fatal_error",
":",
"raise",
"self",
".",
"_fatal_error",
"return",
"self",
".",
"_result"
] | Get the result for a job. This will block if the job is incomplete.
Returns:
The result for the Job.
Raises:
An exception if the Job resulted in an exception. | [
"Get",
"the",
"result",
"for",
"a",
"job",
".",
"This",
"will",
"block",
"if",
"the",
"job",
"is",
"incomplete",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/_job.py#L119-L132 | train | 237,676 |
googledatalab/pydatalab | datalab/utils/_job.py | Job._refresh_state | def _refresh_state(self):
""" Get the state of a job. Must be overridden by derived Job classes
for Jobs that don't use a Future.
"""
if self._is_complete:
return
if not self._future:
raise Exception('Please implement this in the derived class')
if self._future.done():
self._is_complete = True
self._end_time = datetime.datetime.utcnow()
try:
self._result = self._future.result()
except Exception as e:
message = str(e)
self._fatal_error = JobError(location=traceback.format_exc(), message=message,
reason=str(type(e))) | python | def _refresh_state(self):
""" Get the state of a job. Must be overridden by derived Job classes
for Jobs that don't use a Future.
"""
if self._is_complete:
return
if not self._future:
raise Exception('Please implement this in the derived class')
if self._future.done():
self._is_complete = True
self._end_time = datetime.datetime.utcnow()
try:
self._result = self._future.result()
except Exception as e:
message = str(e)
self._fatal_error = JobError(location=traceback.format_exc(), message=message,
reason=str(type(e))) | [
"def",
"_refresh_state",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_complete",
":",
"return",
"if",
"not",
"self",
".",
"_future",
":",
"raise",
"Exception",
"(",
"'Please implement this in the derived class'",
")",
"if",
"self",
".",
"_future",
".",
"done",
"(",
")",
":",
"self",
".",
"_is_complete",
"=",
"True",
"self",
".",
"_end_time",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"try",
":",
"self",
".",
"_result",
"=",
"self",
".",
"_future",
".",
"result",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"message",
"=",
"str",
"(",
"e",
")",
"self",
".",
"_fatal_error",
"=",
"JobError",
"(",
"location",
"=",
"traceback",
".",
"format_exc",
"(",
")",
",",
"message",
"=",
"message",
",",
"reason",
"=",
"str",
"(",
"type",
"(",
"e",
")",
")",
")"
] | Get the state of a job. Must be overridden by derived Job classes
for Jobs that don't use a Future. | [
"Get",
"the",
"state",
"of",
"a",
"job",
".",
"Must",
"be",
"overridden",
"by",
"derived",
"Job",
"classes",
"for",
"Jobs",
"that",
"don",
"t",
"use",
"a",
"Future",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/_job.py#L151-L169 | train | 237,677 |
googledatalab/pydatalab | datalab/utils/_job.py | Job.state | def state(self):
""" Describe the state of a Job.
Returns: A string describing the job's state.
"""
state = 'in progress'
if self.is_complete:
if self.failed:
state = 'failed with error: %s' % str(self._fatal_error)
elif self._errors:
state = 'completed with some non-fatal errors'
else:
state = 'completed'
return state | python | def state(self):
""" Describe the state of a Job.
Returns: A string describing the job's state.
"""
state = 'in progress'
if self.is_complete:
if self.failed:
state = 'failed with error: %s' % str(self._fatal_error)
elif self._errors:
state = 'completed with some non-fatal errors'
else:
state = 'completed'
return state | [
"def",
"state",
"(",
"self",
")",
":",
"state",
"=",
"'in progress'",
"if",
"self",
".",
"is_complete",
":",
"if",
"self",
".",
"failed",
":",
"state",
"=",
"'failed with error: %s'",
"%",
"str",
"(",
"self",
".",
"_fatal_error",
")",
"elif",
"self",
".",
"_errors",
":",
"state",
"=",
"'completed with some non-fatal errors'",
"else",
":",
"state",
"=",
"'completed'",
"return",
"state"
] | Describe the state of a Job.
Returns: A string describing the job's state. | [
"Describe",
"the",
"state",
"of",
"a",
"Job",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/_job.py#L202-L215 | train | 237,678 |
googledatalab/pydatalab | datalab/utils/_job.py | Job.wait_any | def wait_any(jobs, timeout=None):
""" Return when at least one of the specified jobs has completed or timeout expires.
Args:
jobs: a Job or list of Jobs to wait on.
timeout: a timeout in seconds to wait for. None (the default) means no timeout.
Returns:
A list of the jobs that have now completed or None if there were no jobs.
"""
return Job._wait(jobs, timeout, concurrent.futures.FIRST_COMPLETED) | python | def wait_any(jobs, timeout=None):
""" Return when at least one of the specified jobs has completed or timeout expires.
Args:
jobs: a Job or list of Jobs to wait on.
timeout: a timeout in seconds to wait for. None (the default) means no timeout.
Returns:
A list of the jobs that have now completed or None if there were no jobs.
"""
return Job._wait(jobs, timeout, concurrent.futures.FIRST_COMPLETED) | [
"def",
"wait_any",
"(",
"jobs",
",",
"timeout",
"=",
"None",
")",
":",
"return",
"Job",
".",
"_wait",
"(",
"jobs",
",",
"timeout",
",",
"concurrent",
".",
"futures",
".",
"FIRST_COMPLETED",
")"
] | Return when at least one of the specified jobs has completed or timeout expires.
Args:
jobs: a Job or list of Jobs to wait on.
timeout: a timeout in seconds to wait for. None (the default) means no timeout.
Returns:
A list of the jobs that have now completed or None if there were no jobs. | [
"Return",
"when",
"at",
"least",
"one",
"of",
"the",
"specified",
"jobs",
"has",
"completed",
"or",
"timeout",
"expires",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/_job.py#L257-L267 | train | 237,679 |
googledatalab/pydatalab | datalab/utils/_job.py | Job.wait_all | def wait_all(jobs, timeout=None):
""" Return when at all of the specified jobs have completed or timeout expires.
Args:
jobs: a Job or list of Jobs to wait on.
timeout: a timeout in seconds to wait for. None (the default) means no timeout.
Returns:
A list of the jobs that have now completed or None if there were no jobs.
"""
return Job._wait(jobs, timeout, concurrent.futures.ALL_COMPLETED) | python | def wait_all(jobs, timeout=None):
""" Return when at all of the specified jobs have completed or timeout expires.
Args:
jobs: a Job or list of Jobs to wait on.
timeout: a timeout in seconds to wait for. None (the default) means no timeout.
Returns:
A list of the jobs that have now completed or None if there were no jobs.
"""
return Job._wait(jobs, timeout, concurrent.futures.ALL_COMPLETED) | [
"def",
"wait_all",
"(",
"jobs",
",",
"timeout",
"=",
"None",
")",
":",
"return",
"Job",
".",
"_wait",
"(",
"jobs",
",",
"timeout",
",",
"concurrent",
".",
"futures",
".",
"ALL_COMPLETED",
")"
] | Return when at all of the specified jobs have completed or timeout expires.
Args:
jobs: a Job or list of Jobs to wait on.
timeout: a timeout in seconds to wait for. None (the default) means no timeout.
Returns:
A list of the jobs that have now completed or None if there were no jobs. | [
"Return",
"when",
"at",
"all",
"of",
"the",
"specified",
"jobs",
"have",
"completed",
"or",
"timeout",
"expires",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/_job.py#L270-L279 | train | 237,680 |
googledatalab/pydatalab | solutionbox/image_classification/mltoolbox/image/classification/_trainer.py | Evaluator.evaluate | def evaluate(self, num_eval_batches=None):
"""Run one round of evaluation, return loss and accuracy."""
num_eval_batches = num_eval_batches or self.num_eval_batches
with tf.Graph().as_default() as graph:
self.tensors = self.model.build_eval_graph(self.eval_data_paths,
self.batch_size)
self.summary = tf.summary.merge_all()
self.saver = tf.train.Saver()
self.summary_writer = tf.summary.FileWriter(self.output_path)
self.sv = tf.train.Supervisor(
graph=graph,
logdir=self.output_path,
summary_op=None,
global_step=None,
saver=self.saver)
last_checkpoint = tf.train.latest_checkpoint(self.checkpoint_path)
with self.sv.managed_session(master='', start_standard_services=False) as session:
self.sv.saver.restore(session, last_checkpoint)
if not self.batch_of_examples:
self.sv.start_queue_runners(session)
for i in range(num_eval_batches):
self.batch_of_examples.append(session.run(self.tensors.examples))
for i in range(num_eval_batches):
session.run(self.tensors.metric_updates,
{self.tensors.examples: self.batch_of_examples[i]})
metric_values = session.run(self.tensors.metric_values)
global_step = tf.train.global_step(session, self.tensors.global_step)
summary = session.run(self.summary)
self.summary_writer.add_summary(summary, global_step)
self.summary_writer.flush()
return metric_values | python | def evaluate(self, num_eval_batches=None):
"""Run one round of evaluation, return loss and accuracy."""
num_eval_batches = num_eval_batches or self.num_eval_batches
with tf.Graph().as_default() as graph:
self.tensors = self.model.build_eval_graph(self.eval_data_paths,
self.batch_size)
self.summary = tf.summary.merge_all()
self.saver = tf.train.Saver()
self.summary_writer = tf.summary.FileWriter(self.output_path)
self.sv = tf.train.Supervisor(
graph=graph,
logdir=self.output_path,
summary_op=None,
global_step=None,
saver=self.saver)
last_checkpoint = tf.train.latest_checkpoint(self.checkpoint_path)
with self.sv.managed_session(master='', start_standard_services=False) as session:
self.sv.saver.restore(session, last_checkpoint)
if not self.batch_of_examples:
self.sv.start_queue_runners(session)
for i in range(num_eval_batches):
self.batch_of_examples.append(session.run(self.tensors.examples))
for i in range(num_eval_batches):
session.run(self.tensors.metric_updates,
{self.tensors.examples: self.batch_of_examples[i]})
metric_values = session.run(self.tensors.metric_values)
global_step = tf.train.global_step(session, self.tensors.global_step)
summary = session.run(self.summary)
self.summary_writer.add_summary(summary, global_step)
self.summary_writer.flush()
return metric_values | [
"def",
"evaluate",
"(",
"self",
",",
"num_eval_batches",
"=",
"None",
")",
":",
"num_eval_batches",
"=",
"num_eval_batches",
"or",
"self",
".",
"num_eval_batches",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
")",
"as",
"graph",
":",
"self",
".",
"tensors",
"=",
"self",
".",
"model",
".",
"build_eval_graph",
"(",
"self",
".",
"eval_data_paths",
",",
"self",
".",
"batch_size",
")",
"self",
".",
"summary",
"=",
"tf",
".",
"summary",
".",
"merge_all",
"(",
")",
"self",
".",
"saver",
"=",
"tf",
".",
"train",
".",
"Saver",
"(",
")",
"self",
".",
"summary_writer",
"=",
"tf",
".",
"summary",
".",
"FileWriter",
"(",
"self",
".",
"output_path",
")",
"self",
".",
"sv",
"=",
"tf",
".",
"train",
".",
"Supervisor",
"(",
"graph",
"=",
"graph",
",",
"logdir",
"=",
"self",
".",
"output_path",
",",
"summary_op",
"=",
"None",
",",
"global_step",
"=",
"None",
",",
"saver",
"=",
"self",
".",
"saver",
")",
"last_checkpoint",
"=",
"tf",
".",
"train",
".",
"latest_checkpoint",
"(",
"self",
".",
"checkpoint_path",
")",
"with",
"self",
".",
"sv",
".",
"managed_session",
"(",
"master",
"=",
"''",
",",
"start_standard_services",
"=",
"False",
")",
"as",
"session",
":",
"self",
".",
"sv",
".",
"saver",
".",
"restore",
"(",
"session",
",",
"last_checkpoint",
")",
"if",
"not",
"self",
".",
"batch_of_examples",
":",
"self",
".",
"sv",
".",
"start_queue_runners",
"(",
"session",
")",
"for",
"i",
"in",
"range",
"(",
"num_eval_batches",
")",
":",
"self",
".",
"batch_of_examples",
".",
"append",
"(",
"session",
".",
"run",
"(",
"self",
".",
"tensors",
".",
"examples",
")",
")",
"for",
"i",
"in",
"range",
"(",
"num_eval_batches",
")",
":",
"session",
".",
"run",
"(",
"self",
".",
"tensors",
".",
"metric_updates",
",",
"{",
"self",
".",
"tensors",
".",
"examples",
":",
"self",
".",
"batch_of_examples",
"[",
"i",
"]",
"}",
")",
"metric_values",
"=",
"session",
".",
"run",
"(",
"self",
".",
"tensors",
".",
"metric_values",
")",
"global_step",
"=",
"tf",
".",
"train",
".",
"global_step",
"(",
"session",
",",
"self",
".",
"tensors",
".",
"global_step",
")",
"summary",
"=",
"session",
".",
"run",
"(",
"self",
".",
"summary",
")",
"self",
".",
"summary_writer",
".",
"add_summary",
"(",
"summary",
",",
"global_step",
")",
"self",
".",
"summary_writer",
".",
"flush",
"(",
")",
"return",
"metric_values"
] | Run one round of evaluation, return loss and accuracy. | [
"Run",
"one",
"round",
"of",
"evaluation",
"return",
"loss",
"and",
"accuracy",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_trainer.py#L65-L101 | train | 237,681 |
googledatalab/pydatalab | solutionbox/image_classification/mltoolbox/image/classification/_trainer.py | Trainer.log | def log(self, session):
"""Logs training progress."""
logging.info('Train [%s/%d], step %d (%.3f sec) %.1f '
'global steps/s, %.1f local steps/s', self.task.type,
self.task.index, self.global_step,
(self.now - self.start_time),
(self.global_step - self.last_global_step) /
(self.now - self.last_global_time),
(self.local_step - self.last_local_step) /
(self.now - self.last_local_time))
self.last_log = self.now
self.last_global_step, self.last_global_time = self.global_step, self.now
self.last_local_step, self.last_local_time = self.local_step, self.now | python | def log(self, session):
"""Logs training progress."""
logging.info('Train [%s/%d], step %d (%.3f sec) %.1f '
'global steps/s, %.1f local steps/s', self.task.type,
self.task.index, self.global_step,
(self.now - self.start_time),
(self.global_step - self.last_global_step) /
(self.now - self.last_global_time),
(self.local_step - self.last_local_step) /
(self.now - self.last_local_time))
self.last_log = self.now
self.last_global_step, self.last_global_time = self.global_step, self.now
self.last_local_step, self.last_local_time = self.local_step, self.now | [
"def",
"log",
"(",
"self",
",",
"session",
")",
":",
"logging",
".",
"info",
"(",
"'Train [%s/%d], step %d (%.3f sec) %.1f '",
"'global steps/s, %.1f local steps/s'",
",",
"self",
".",
"task",
".",
"type",
",",
"self",
".",
"task",
".",
"index",
",",
"self",
".",
"global_step",
",",
"(",
"self",
".",
"now",
"-",
"self",
".",
"start_time",
")",
",",
"(",
"self",
".",
"global_step",
"-",
"self",
".",
"last_global_step",
")",
"/",
"(",
"self",
".",
"now",
"-",
"self",
".",
"last_global_time",
")",
",",
"(",
"self",
".",
"local_step",
"-",
"self",
".",
"last_local_step",
")",
"/",
"(",
"self",
".",
"now",
"-",
"self",
".",
"last_local_time",
")",
")",
"self",
".",
"last_log",
"=",
"self",
".",
"now",
"self",
".",
"last_global_step",
",",
"self",
".",
"last_global_time",
"=",
"self",
".",
"global_step",
",",
"self",
".",
"now",
"self",
".",
"last_local_step",
",",
"self",
".",
"last_local_time",
"=",
"self",
".",
"local_step",
",",
"self",
".",
"now"
] | Logs training progress. | [
"Logs",
"training",
"progress",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_trainer.py#L232-L244 | train | 237,682 |
googledatalab/pydatalab | solutionbox/image_classification/mltoolbox/image/classification/_trainer.py | Trainer.eval | def eval(self, session):
"""Runs evaluation loop."""
eval_start = time.time()
self.saver.save(session, self.sv.save_path, self.tensors.global_step)
logging.info(
'Eval, step %d:\n- on train set %s\n-- on eval set %s',
self.global_step,
self.model.format_metric_values(self.train_evaluator.evaluate()),
self.model.format_metric_values(self.evaluator.evaluate()))
now = time.time()
# Make sure eval doesn't consume too much of total time.
eval_time = now - eval_start
train_eval_rate = self.eval_interval / eval_time
if train_eval_rate < self.min_train_eval_rate and self.last_save > 0:
logging.info('Adjusting eval interval from %.2fs to %.2fs',
self.eval_interval, self.min_train_eval_rate * eval_time)
self.eval_interval = self.min_train_eval_rate * eval_time
self.last_save = now
self.last_log = now | python | def eval(self, session):
"""Runs evaluation loop."""
eval_start = time.time()
self.saver.save(session, self.sv.save_path, self.tensors.global_step)
logging.info(
'Eval, step %d:\n- on train set %s\n-- on eval set %s',
self.global_step,
self.model.format_metric_values(self.train_evaluator.evaluate()),
self.model.format_metric_values(self.evaluator.evaluate()))
now = time.time()
# Make sure eval doesn't consume too much of total time.
eval_time = now - eval_start
train_eval_rate = self.eval_interval / eval_time
if train_eval_rate < self.min_train_eval_rate and self.last_save > 0:
logging.info('Adjusting eval interval from %.2fs to %.2fs',
self.eval_interval, self.min_train_eval_rate * eval_time)
self.eval_interval = self.min_train_eval_rate * eval_time
self.last_save = now
self.last_log = now | [
"def",
"eval",
"(",
"self",
",",
"session",
")",
":",
"eval_start",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"saver",
".",
"save",
"(",
"session",
",",
"self",
".",
"sv",
".",
"save_path",
",",
"self",
".",
"tensors",
".",
"global_step",
")",
"logging",
".",
"info",
"(",
"'Eval, step %d:\\n- on train set %s\\n-- on eval set %s'",
",",
"self",
".",
"global_step",
",",
"self",
".",
"model",
".",
"format_metric_values",
"(",
"self",
".",
"train_evaluator",
".",
"evaluate",
"(",
")",
")",
",",
"self",
".",
"model",
".",
"format_metric_values",
"(",
"self",
".",
"evaluator",
".",
"evaluate",
"(",
")",
")",
")",
"now",
"=",
"time",
".",
"time",
"(",
")",
"# Make sure eval doesn't consume too much of total time.",
"eval_time",
"=",
"now",
"-",
"eval_start",
"train_eval_rate",
"=",
"self",
".",
"eval_interval",
"/",
"eval_time",
"if",
"train_eval_rate",
"<",
"self",
".",
"min_train_eval_rate",
"and",
"self",
".",
"last_save",
">",
"0",
":",
"logging",
".",
"info",
"(",
"'Adjusting eval interval from %.2fs to %.2fs'",
",",
"self",
".",
"eval_interval",
",",
"self",
".",
"min_train_eval_rate",
"*",
"eval_time",
")",
"self",
".",
"eval_interval",
"=",
"self",
".",
"min_train_eval_rate",
"*",
"eval_time",
"self",
".",
"last_save",
"=",
"now",
"self",
".",
"last_log",
"=",
"now"
] | Runs evaluation loop. | [
"Runs",
"evaluation",
"loop",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_trainer.py#L246-L266 | train | 237,683 |
googledatalab/pydatalab | google/datalab/ml/_feature_slice_view.py | FeatureSliceView.plot | def plot(self, data):
""" Plots a featire slice view on given data.
Args:
data: Can be one of:
A string of sql query.
A sql query module defined by "%%sql --module module_name".
A pandas DataFrame.
Regardless of data type, it must include the following columns:
"feature": identifies a slice of features. For example: "petal_length:4.0-4.2".
"count": number of instances in that slice of features.
All other columns are viewed as metrics for its feature slice. At least one is required.
"""
import IPython
if ((sys.version_info.major > 2 and isinstance(data, str)) or
(sys.version_info.major <= 2 and isinstance(data, basestring))):
data = bq.Query(data)
if isinstance(data, bq.Query):
df = data.execute().result().to_dataframe()
data = self._get_lantern_format(df)
elif isinstance(data, pd.core.frame.DataFrame):
data = self._get_lantern_format(data)
else:
raise Exception('data needs to be a sql query, or a pandas DataFrame.')
HTML_TEMPLATE = """<link rel="import" href="/nbextensions/gcpdatalab/extern/lantern-browser.html" >
<lantern-browser id="{html_id}"></lantern-browser>
<script>
var browser = document.querySelector('#{html_id}');
browser.metrics = {metrics};
browser.data = {data};
browser.sourceType = 'colab';
browser.weightedExamplesColumn = 'count';
browser.calibrationPlotUriFn = function(s) {{ return '/' + s; }}
</script>"""
# Serialize the data and list of metrics names to JSON string.
metrics_str = str(map(str, data[0]['metricValues'].keys()))
data_str = str([{str(k): json.dumps(v) for k, v in elem.iteritems()} for elem in data])
html_id = 'l' + datalab.utils.commands.Html.next_id()
html = HTML_TEMPLATE.format(html_id=html_id, metrics=metrics_str, data=data_str)
IPython.display.display(IPython.display.HTML(html)) | python | def plot(self, data):
""" Plots a featire slice view on given data.
Args:
data: Can be one of:
A string of sql query.
A sql query module defined by "%%sql --module module_name".
A pandas DataFrame.
Regardless of data type, it must include the following columns:
"feature": identifies a slice of features. For example: "petal_length:4.0-4.2".
"count": number of instances in that slice of features.
All other columns are viewed as metrics for its feature slice. At least one is required.
"""
import IPython
if ((sys.version_info.major > 2 and isinstance(data, str)) or
(sys.version_info.major <= 2 and isinstance(data, basestring))):
data = bq.Query(data)
if isinstance(data, bq.Query):
df = data.execute().result().to_dataframe()
data = self._get_lantern_format(df)
elif isinstance(data, pd.core.frame.DataFrame):
data = self._get_lantern_format(data)
else:
raise Exception('data needs to be a sql query, or a pandas DataFrame.')
HTML_TEMPLATE = """<link rel="import" href="/nbextensions/gcpdatalab/extern/lantern-browser.html" >
<lantern-browser id="{html_id}"></lantern-browser>
<script>
var browser = document.querySelector('#{html_id}');
browser.metrics = {metrics};
browser.data = {data};
browser.sourceType = 'colab';
browser.weightedExamplesColumn = 'count';
browser.calibrationPlotUriFn = function(s) {{ return '/' + s; }}
</script>"""
# Serialize the data and list of metrics names to JSON string.
metrics_str = str(map(str, data[0]['metricValues'].keys()))
data_str = str([{str(k): json.dumps(v) for k, v in elem.iteritems()} for elem in data])
html_id = 'l' + datalab.utils.commands.Html.next_id()
html = HTML_TEMPLATE.format(html_id=html_id, metrics=metrics_str, data=data_str)
IPython.display.display(IPython.display.HTML(html)) | [
"def",
"plot",
"(",
"self",
",",
"data",
")",
":",
"import",
"IPython",
"if",
"(",
"(",
"sys",
".",
"version_info",
".",
"major",
">",
"2",
"and",
"isinstance",
"(",
"data",
",",
"str",
")",
")",
"or",
"(",
"sys",
".",
"version_info",
".",
"major",
"<=",
"2",
"and",
"isinstance",
"(",
"data",
",",
"basestring",
")",
")",
")",
":",
"data",
"=",
"bq",
".",
"Query",
"(",
"data",
")",
"if",
"isinstance",
"(",
"data",
",",
"bq",
".",
"Query",
")",
":",
"df",
"=",
"data",
".",
"execute",
"(",
")",
".",
"result",
"(",
")",
".",
"to_dataframe",
"(",
")",
"data",
"=",
"self",
".",
"_get_lantern_format",
"(",
"df",
")",
"elif",
"isinstance",
"(",
"data",
",",
"pd",
".",
"core",
".",
"frame",
".",
"DataFrame",
")",
":",
"data",
"=",
"self",
".",
"_get_lantern_format",
"(",
"data",
")",
"else",
":",
"raise",
"Exception",
"(",
"'data needs to be a sql query, or a pandas DataFrame.'",
")",
"HTML_TEMPLATE",
"=",
"\"\"\"<link rel=\"import\" href=\"/nbextensions/gcpdatalab/extern/lantern-browser.html\" >\n <lantern-browser id=\"{html_id}\"></lantern-browser>\n <script>\n var browser = document.querySelector('#{html_id}');\n browser.metrics = {metrics};\n browser.data = {data};\n browser.sourceType = 'colab';\n browser.weightedExamplesColumn = 'count';\n browser.calibrationPlotUriFn = function(s) {{ return '/' + s; }}\n </script>\"\"\"",
"# Serialize the data and list of metrics names to JSON string.",
"metrics_str",
"=",
"str",
"(",
"map",
"(",
"str",
",",
"data",
"[",
"0",
"]",
"[",
"'metricValues'",
"]",
".",
"keys",
"(",
")",
")",
")",
"data_str",
"=",
"str",
"(",
"[",
"{",
"str",
"(",
"k",
")",
":",
"json",
".",
"dumps",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"elem",
".",
"iteritems",
"(",
")",
"}",
"for",
"elem",
"in",
"data",
"]",
")",
"html_id",
"=",
"'l'",
"+",
"datalab",
".",
"utils",
".",
"commands",
".",
"Html",
".",
"next_id",
"(",
")",
"html",
"=",
"HTML_TEMPLATE",
".",
"format",
"(",
"html_id",
"=",
"html_id",
",",
"metrics",
"=",
"metrics_str",
",",
"data",
"=",
"data_str",
")",
"IPython",
".",
"display",
".",
"display",
"(",
"IPython",
".",
"display",
".",
"HTML",
"(",
"html",
")",
")"
] | Plots a featire slice view on given data.
Args:
data: Can be one of:
A string of sql query.
A sql query module defined by "%%sql --module module_name".
A pandas DataFrame.
Regardless of data type, it must include the following columns:
"feature": identifies a slice of features. For example: "petal_length:4.0-4.2".
"count": number of instances in that slice of features.
All other columns are viewed as metrics for its feature slice. At least one is required. | [
"Plots",
"a",
"featire",
"slice",
"view",
"on",
"given",
"data",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_feature_slice_view.py#L46-L88 | train | 237,684 |
googledatalab/pydatalab | solutionbox/structured_data/mltoolbox/_structured_data/preprocess/cloud_preprocess.py | run_analysis | def run_analysis(args):
"""Builds an analysis file for training.
Uses BiqQuery tables to do the analysis.
Args:
args: command line args
Raises:
ValueError if schema contains unknown types.
"""
import google.datalab.bigquery as bq
if args.bigquery_table:
table = bq.Table(args.bigquery_table)
schema_list = table.schema._bq_schema
else:
schema_list = json.loads(
file_io.read_file_to_string(args.schema_file).decode())
table = bq.ExternalDataSource(
source=args.input_file_pattern,
schema=bq.Schema(schema_list))
# Check the schema is supported.
for col_schema in schema_list:
col_type = col_schema['type'].lower()
if col_type != 'string' and col_type != 'integer' and col_type != 'float':
raise ValueError('Schema contains an unsupported type %s.' % col_type)
run_numerical_analysis(table, schema_list, args)
run_categorical_analysis(table, schema_list, args)
# Save a copy of the schema to the output location.
file_io.write_string_to_file(
os.path.join(args.output_dir, SCHEMA_FILE),
json.dumps(schema_list, indent=2, separators=(',', ': '))) | python | def run_analysis(args):
"""Builds an analysis file for training.
Uses BiqQuery tables to do the analysis.
Args:
args: command line args
Raises:
ValueError if schema contains unknown types.
"""
import google.datalab.bigquery as bq
if args.bigquery_table:
table = bq.Table(args.bigquery_table)
schema_list = table.schema._bq_schema
else:
schema_list = json.loads(
file_io.read_file_to_string(args.schema_file).decode())
table = bq.ExternalDataSource(
source=args.input_file_pattern,
schema=bq.Schema(schema_list))
# Check the schema is supported.
for col_schema in schema_list:
col_type = col_schema['type'].lower()
if col_type != 'string' and col_type != 'integer' and col_type != 'float':
raise ValueError('Schema contains an unsupported type %s.' % col_type)
run_numerical_analysis(table, schema_list, args)
run_categorical_analysis(table, schema_list, args)
# Save a copy of the schema to the output location.
file_io.write_string_to_file(
os.path.join(args.output_dir, SCHEMA_FILE),
json.dumps(schema_list, indent=2, separators=(',', ': '))) | [
"def",
"run_analysis",
"(",
"args",
")",
":",
"import",
"google",
".",
"datalab",
".",
"bigquery",
"as",
"bq",
"if",
"args",
".",
"bigquery_table",
":",
"table",
"=",
"bq",
".",
"Table",
"(",
"args",
".",
"bigquery_table",
")",
"schema_list",
"=",
"table",
".",
"schema",
".",
"_bq_schema",
"else",
":",
"schema_list",
"=",
"json",
".",
"loads",
"(",
"file_io",
".",
"read_file_to_string",
"(",
"args",
".",
"schema_file",
")",
".",
"decode",
"(",
")",
")",
"table",
"=",
"bq",
".",
"ExternalDataSource",
"(",
"source",
"=",
"args",
".",
"input_file_pattern",
",",
"schema",
"=",
"bq",
".",
"Schema",
"(",
"schema_list",
")",
")",
"# Check the schema is supported.",
"for",
"col_schema",
"in",
"schema_list",
":",
"col_type",
"=",
"col_schema",
"[",
"'type'",
"]",
".",
"lower",
"(",
")",
"if",
"col_type",
"!=",
"'string'",
"and",
"col_type",
"!=",
"'integer'",
"and",
"col_type",
"!=",
"'float'",
":",
"raise",
"ValueError",
"(",
"'Schema contains an unsupported type %s.'",
"%",
"col_type",
")",
"run_numerical_analysis",
"(",
"table",
",",
"schema_list",
",",
"args",
")",
"run_categorical_analysis",
"(",
"table",
",",
"schema_list",
",",
"args",
")",
"# Save a copy of the schema to the output location.",
"file_io",
".",
"write_string_to_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"args",
".",
"output_dir",
",",
"SCHEMA_FILE",
")",
",",
"json",
".",
"dumps",
"(",
"schema_list",
",",
"indent",
"=",
"2",
",",
"separators",
"=",
"(",
"','",
",",
"': '",
")",
")",
")"
] | Builds an analysis file for training.
Uses BiqQuery tables to do the analysis.
Args:
args: command line args
Raises:
ValueError if schema contains unknown types. | [
"Builds",
"an",
"analysis",
"file",
"for",
"training",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/preprocess/cloud_preprocess.py#L222-L256 | train | 237,685 |
googledatalab/pydatalab | google/datalab/ml/_confusion_matrix.py | ConfusionMatrix.from_csv | def from_csv(input_csv, headers=None, schema_file=None):
"""Create a ConfusionMatrix from a csv file.
Args:
input_csv: Path to a Csv file (with no header). Can be local or GCS path.
headers: Csv headers. If present, it must include 'target' and 'predicted'.
schema_file: Path to a JSON file containing BigQuery schema. Used if "headers" is None.
If present, it must include 'target' and 'predicted' columns.
Returns:
A ConfusionMatrix that can be plotted.
Raises:
ValueError if both headers and schema_file are None, or it does not include 'target'
or 'predicted' columns.
"""
if headers is not None:
names = headers
elif schema_file is not None:
with _util.open_local_or_gcs(schema_file, mode='r') as f:
schema = json.load(f)
names = [x['name'] for x in schema]
else:
raise ValueError('Either headers or schema_file is needed')
all_files = _util.glob_files(input_csv)
all_df = []
for file_name in all_files:
with _util.open_local_or_gcs(file_name, mode='r') as f:
all_df.append(pd.read_csv(f, names=names))
df = pd.concat(all_df, ignore_index=True)
if 'target' not in df or 'predicted' not in df:
raise ValueError('Cannot find "target" or "predicted" column')
labels = sorted(set(df['target']) | set(df['predicted']))
cm = confusion_matrix(df['target'], df['predicted'], labels=labels)
return ConfusionMatrix(cm, labels) | python | def from_csv(input_csv, headers=None, schema_file=None):
"""Create a ConfusionMatrix from a csv file.
Args:
input_csv: Path to a Csv file (with no header). Can be local or GCS path.
headers: Csv headers. If present, it must include 'target' and 'predicted'.
schema_file: Path to a JSON file containing BigQuery schema. Used if "headers" is None.
If present, it must include 'target' and 'predicted' columns.
Returns:
A ConfusionMatrix that can be plotted.
Raises:
ValueError if both headers and schema_file are None, or it does not include 'target'
or 'predicted' columns.
"""
if headers is not None:
names = headers
elif schema_file is not None:
with _util.open_local_or_gcs(schema_file, mode='r') as f:
schema = json.load(f)
names = [x['name'] for x in schema]
else:
raise ValueError('Either headers or schema_file is needed')
all_files = _util.glob_files(input_csv)
all_df = []
for file_name in all_files:
with _util.open_local_or_gcs(file_name, mode='r') as f:
all_df.append(pd.read_csv(f, names=names))
df = pd.concat(all_df, ignore_index=True)
if 'target' not in df or 'predicted' not in df:
raise ValueError('Cannot find "target" or "predicted" column')
labels = sorted(set(df['target']) | set(df['predicted']))
cm = confusion_matrix(df['target'], df['predicted'], labels=labels)
return ConfusionMatrix(cm, labels) | [
"def",
"from_csv",
"(",
"input_csv",
",",
"headers",
"=",
"None",
",",
"schema_file",
"=",
"None",
")",
":",
"if",
"headers",
"is",
"not",
"None",
":",
"names",
"=",
"headers",
"elif",
"schema_file",
"is",
"not",
"None",
":",
"with",
"_util",
".",
"open_local_or_gcs",
"(",
"schema_file",
",",
"mode",
"=",
"'r'",
")",
"as",
"f",
":",
"schema",
"=",
"json",
".",
"load",
"(",
"f",
")",
"names",
"=",
"[",
"x",
"[",
"'name'",
"]",
"for",
"x",
"in",
"schema",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"'Either headers or schema_file is needed'",
")",
"all_files",
"=",
"_util",
".",
"glob_files",
"(",
"input_csv",
")",
"all_df",
"=",
"[",
"]",
"for",
"file_name",
"in",
"all_files",
":",
"with",
"_util",
".",
"open_local_or_gcs",
"(",
"file_name",
",",
"mode",
"=",
"'r'",
")",
"as",
"f",
":",
"all_df",
".",
"append",
"(",
"pd",
".",
"read_csv",
"(",
"f",
",",
"names",
"=",
"names",
")",
")",
"df",
"=",
"pd",
".",
"concat",
"(",
"all_df",
",",
"ignore_index",
"=",
"True",
")",
"if",
"'target'",
"not",
"in",
"df",
"or",
"'predicted'",
"not",
"in",
"df",
":",
"raise",
"ValueError",
"(",
"'Cannot find \"target\" or \"predicted\" column'",
")",
"labels",
"=",
"sorted",
"(",
"set",
"(",
"df",
"[",
"'target'",
"]",
")",
"|",
"set",
"(",
"df",
"[",
"'predicted'",
"]",
")",
")",
"cm",
"=",
"confusion_matrix",
"(",
"df",
"[",
"'target'",
"]",
",",
"df",
"[",
"'predicted'",
"]",
",",
"labels",
"=",
"labels",
")",
"return",
"ConfusionMatrix",
"(",
"cm",
",",
"labels",
")"
] | Create a ConfusionMatrix from a csv file.
Args:
input_csv: Path to a Csv file (with no header). Can be local or GCS path.
headers: Csv headers. If present, it must include 'target' and 'predicted'.
schema_file: Path to a JSON file containing BigQuery schema. Used if "headers" is None.
If present, it must include 'target' and 'predicted' columns.
Returns:
A ConfusionMatrix that can be plotted.
Raises:
ValueError if both headers and schema_file are None, or it does not include 'target'
or 'predicted' columns. | [
"Create",
"a",
"ConfusionMatrix",
"from",
"a",
"csv",
"file",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_confusion_matrix.py#L41-L77 | train | 237,686 |
googledatalab/pydatalab | google/datalab/ml/_confusion_matrix.py | ConfusionMatrix.from_bigquery | def from_bigquery(sql):
"""Create a ConfusionMatrix from a BigQuery table or query.
Args:
sql: Can be one of:
A SQL query string.
A Bigquery table string.
A Query object defined with '%%bq query --name [query_name]'.
The query results or table must include "target", "predicted" columns.
Returns:
A ConfusionMatrix that can be plotted.
Raises:
ValueError if query results or table does not include 'target' or 'predicted' columns.
"""
if isinstance(sql, bq.Query):
sql = sql._expanded_sql()
parts = sql.split('.')
if len(parts) == 1 or len(parts) > 3 or any(' ' in x for x in parts):
sql = '(' + sql + ')' # query, not a table name
else:
sql = '`' + sql + '`' # table name
query = bq.Query(
'SELECT target, predicted, count(*) as count FROM %s group by target, predicted' % sql)
df = query.execute().result().to_dataframe()
labels = sorted(set(df['target']) | set(df['predicted']))
labels_count = len(labels)
df['target'] = [labels.index(x) for x in df['target']]
df['predicted'] = [labels.index(x) for x in df['predicted']]
cm = [[0] * labels_count for i in range(labels_count)]
for index, row in df.iterrows():
cm[row['target']][row['predicted']] = row['count']
return ConfusionMatrix(cm, labels) | python | def from_bigquery(sql):
"""Create a ConfusionMatrix from a BigQuery table or query.
Args:
sql: Can be one of:
A SQL query string.
A Bigquery table string.
A Query object defined with '%%bq query --name [query_name]'.
The query results or table must include "target", "predicted" columns.
Returns:
A ConfusionMatrix that can be plotted.
Raises:
ValueError if query results or table does not include 'target' or 'predicted' columns.
"""
if isinstance(sql, bq.Query):
sql = sql._expanded_sql()
parts = sql.split('.')
if len(parts) == 1 or len(parts) > 3 or any(' ' in x for x in parts):
sql = '(' + sql + ')' # query, not a table name
else:
sql = '`' + sql + '`' # table name
query = bq.Query(
'SELECT target, predicted, count(*) as count FROM %s group by target, predicted' % sql)
df = query.execute().result().to_dataframe()
labels = sorted(set(df['target']) | set(df['predicted']))
labels_count = len(labels)
df['target'] = [labels.index(x) for x in df['target']]
df['predicted'] = [labels.index(x) for x in df['predicted']]
cm = [[0] * labels_count for i in range(labels_count)]
for index, row in df.iterrows():
cm[row['target']][row['predicted']] = row['count']
return ConfusionMatrix(cm, labels) | [
"def",
"from_bigquery",
"(",
"sql",
")",
":",
"if",
"isinstance",
"(",
"sql",
",",
"bq",
".",
"Query",
")",
":",
"sql",
"=",
"sql",
".",
"_expanded_sql",
"(",
")",
"parts",
"=",
"sql",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"1",
"or",
"len",
"(",
"parts",
")",
">",
"3",
"or",
"any",
"(",
"' '",
"in",
"x",
"for",
"x",
"in",
"parts",
")",
":",
"sql",
"=",
"'('",
"+",
"sql",
"+",
"')'",
"# query, not a table name",
"else",
":",
"sql",
"=",
"'`'",
"+",
"sql",
"+",
"'`'",
"# table name",
"query",
"=",
"bq",
".",
"Query",
"(",
"'SELECT target, predicted, count(*) as count FROM %s group by target, predicted'",
"%",
"sql",
")",
"df",
"=",
"query",
".",
"execute",
"(",
")",
".",
"result",
"(",
")",
".",
"to_dataframe",
"(",
")",
"labels",
"=",
"sorted",
"(",
"set",
"(",
"df",
"[",
"'target'",
"]",
")",
"|",
"set",
"(",
"df",
"[",
"'predicted'",
"]",
")",
")",
"labels_count",
"=",
"len",
"(",
"labels",
")",
"df",
"[",
"'target'",
"]",
"=",
"[",
"labels",
".",
"index",
"(",
"x",
")",
"for",
"x",
"in",
"df",
"[",
"'target'",
"]",
"]",
"df",
"[",
"'predicted'",
"]",
"=",
"[",
"labels",
".",
"index",
"(",
"x",
")",
"for",
"x",
"in",
"df",
"[",
"'predicted'",
"]",
"]",
"cm",
"=",
"[",
"[",
"0",
"]",
"*",
"labels_count",
"for",
"i",
"in",
"range",
"(",
"labels_count",
")",
"]",
"for",
"index",
",",
"row",
"in",
"df",
".",
"iterrows",
"(",
")",
":",
"cm",
"[",
"row",
"[",
"'target'",
"]",
"]",
"[",
"row",
"[",
"'predicted'",
"]",
"]",
"=",
"row",
"[",
"'count'",
"]",
"return",
"ConfusionMatrix",
"(",
"cm",
",",
"labels",
")"
] | Create a ConfusionMatrix from a BigQuery table or query.
Args:
sql: Can be one of:
A SQL query string.
A Bigquery table string.
A Query object defined with '%%bq query --name [query_name]'.
The query results or table must include "target", "predicted" columns.
Returns:
A ConfusionMatrix that can be plotted.
Raises:
ValueError if query results or table does not include 'target' or 'predicted' columns. | [
"Create",
"a",
"ConfusionMatrix",
"from",
"a",
"BigQuery",
"table",
"or",
"query",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_confusion_matrix.py#L80-L113 | train | 237,687 |
googledatalab/pydatalab | google/datalab/ml/_confusion_matrix.py | ConfusionMatrix.to_dataframe | def to_dataframe(self):
"""Convert the confusion matrix to a dataframe.
Returns:
A DataFrame with "target", "predicted", "count" columns.
"""
data = []
for target_index, target_row in enumerate(self._cm):
for predicted_index, count in enumerate(target_row):
data.append((self._labels[target_index], self._labels[predicted_index], count))
return pd.DataFrame(data, columns=['target', 'predicted', 'count']) | python | def to_dataframe(self):
"""Convert the confusion matrix to a dataframe.
Returns:
A DataFrame with "target", "predicted", "count" columns.
"""
data = []
for target_index, target_row in enumerate(self._cm):
for predicted_index, count in enumerate(target_row):
data.append((self._labels[target_index], self._labels[predicted_index], count))
return pd.DataFrame(data, columns=['target', 'predicted', 'count']) | [
"def",
"to_dataframe",
"(",
"self",
")",
":",
"data",
"=",
"[",
"]",
"for",
"target_index",
",",
"target_row",
"in",
"enumerate",
"(",
"self",
".",
"_cm",
")",
":",
"for",
"predicted_index",
",",
"count",
"in",
"enumerate",
"(",
"target_row",
")",
":",
"data",
".",
"append",
"(",
"(",
"self",
".",
"_labels",
"[",
"target_index",
"]",
",",
"self",
".",
"_labels",
"[",
"predicted_index",
"]",
",",
"count",
")",
")",
"return",
"pd",
".",
"DataFrame",
"(",
"data",
",",
"columns",
"=",
"[",
"'target'",
",",
"'predicted'",
",",
"'count'",
"]",
")"
] | Convert the confusion matrix to a dataframe.
Returns:
A DataFrame with "target", "predicted", "count" columns. | [
"Convert",
"the",
"confusion",
"matrix",
"to",
"a",
"dataframe",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_confusion_matrix.py#L115-L127 | train | 237,688 |
googledatalab/pydatalab | google/datalab/ml/_confusion_matrix.py | ConfusionMatrix.plot | def plot(self, figsize=None, rotation=45):
"""Plot the confusion matrix.
Args:
figsize: tuple (x, y) of ints. Sets the size of the figure
rotation: the rotation angle of the labels on the x-axis.
"""
fig, ax = plt.subplots(figsize=figsize)
plt.imshow(self._cm, interpolation='nearest', cmap=plt.cm.Blues, aspect='auto')
plt.title('Confusion matrix')
plt.colorbar()
tick_marks = np.arange(len(self._labels))
plt.xticks(tick_marks, self._labels, rotation=rotation)
plt.yticks(tick_marks, self._labels)
if isinstance(self._cm, list):
# If cm is created from BigQuery then it is a list.
thresh = max(max(self._cm)) / 2.
for i, j in itertools.product(range(len(self._labels)), range(len(self._labels))):
plt.text(j, i, self._cm[i][j], horizontalalignment="center",
color="white" if self._cm[i][j] > thresh else "black")
else:
# If cm is created from csv then it is a sklearn's confusion_matrix.
thresh = self._cm.max() / 2.
for i, j in itertools.product(range(len(self._labels)), range(len(self._labels))):
plt.text(j, i, self._cm[i, j], horizontalalignment="center",
color="white" if self._cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label') | python | def plot(self, figsize=None, rotation=45):
"""Plot the confusion matrix.
Args:
figsize: tuple (x, y) of ints. Sets the size of the figure
rotation: the rotation angle of the labels on the x-axis.
"""
fig, ax = plt.subplots(figsize=figsize)
plt.imshow(self._cm, interpolation='nearest', cmap=plt.cm.Blues, aspect='auto')
plt.title('Confusion matrix')
plt.colorbar()
tick_marks = np.arange(len(self._labels))
plt.xticks(tick_marks, self._labels, rotation=rotation)
plt.yticks(tick_marks, self._labels)
if isinstance(self._cm, list):
# If cm is created from BigQuery then it is a list.
thresh = max(max(self._cm)) / 2.
for i, j in itertools.product(range(len(self._labels)), range(len(self._labels))):
plt.text(j, i, self._cm[i][j], horizontalalignment="center",
color="white" if self._cm[i][j] > thresh else "black")
else:
# If cm is created from csv then it is a sklearn's confusion_matrix.
thresh = self._cm.max() / 2.
for i, j in itertools.product(range(len(self._labels)), range(len(self._labels))):
plt.text(j, i, self._cm[i, j], horizontalalignment="center",
color="white" if self._cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label') | [
"def",
"plot",
"(",
"self",
",",
"figsize",
"=",
"None",
",",
"rotation",
"=",
"45",
")",
":",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"figsize",
"=",
"figsize",
")",
"plt",
".",
"imshow",
"(",
"self",
".",
"_cm",
",",
"interpolation",
"=",
"'nearest'",
",",
"cmap",
"=",
"plt",
".",
"cm",
".",
"Blues",
",",
"aspect",
"=",
"'auto'",
")",
"plt",
".",
"title",
"(",
"'Confusion matrix'",
")",
"plt",
".",
"colorbar",
"(",
")",
"tick_marks",
"=",
"np",
".",
"arange",
"(",
"len",
"(",
"self",
".",
"_labels",
")",
")",
"plt",
".",
"xticks",
"(",
"tick_marks",
",",
"self",
".",
"_labels",
",",
"rotation",
"=",
"rotation",
")",
"plt",
".",
"yticks",
"(",
"tick_marks",
",",
"self",
".",
"_labels",
")",
"if",
"isinstance",
"(",
"self",
".",
"_cm",
",",
"list",
")",
":",
"# If cm is created from BigQuery then it is a list.",
"thresh",
"=",
"max",
"(",
"max",
"(",
"self",
".",
"_cm",
")",
")",
"/",
"2.",
"for",
"i",
",",
"j",
"in",
"itertools",
".",
"product",
"(",
"range",
"(",
"len",
"(",
"self",
".",
"_labels",
")",
")",
",",
"range",
"(",
"len",
"(",
"self",
".",
"_labels",
")",
")",
")",
":",
"plt",
".",
"text",
"(",
"j",
",",
"i",
",",
"self",
".",
"_cm",
"[",
"i",
"]",
"[",
"j",
"]",
",",
"horizontalalignment",
"=",
"\"center\"",
",",
"color",
"=",
"\"white\"",
"if",
"self",
".",
"_cm",
"[",
"i",
"]",
"[",
"j",
"]",
">",
"thresh",
"else",
"\"black\"",
")",
"else",
":",
"# If cm is created from csv then it is a sklearn's confusion_matrix.",
"thresh",
"=",
"self",
".",
"_cm",
".",
"max",
"(",
")",
"/",
"2.",
"for",
"i",
",",
"j",
"in",
"itertools",
".",
"product",
"(",
"range",
"(",
"len",
"(",
"self",
".",
"_labels",
")",
")",
",",
"range",
"(",
"len",
"(",
"self",
".",
"_labels",
")",
")",
")",
":",
"plt",
".",
"text",
"(",
"j",
",",
"i",
",",
"self",
".",
"_cm",
"[",
"i",
",",
"j",
"]",
",",
"horizontalalignment",
"=",
"\"center\"",
",",
"color",
"=",
"\"white\"",
"if",
"self",
".",
"_cm",
"[",
"i",
",",
"j",
"]",
">",
"thresh",
"else",
"\"black\"",
")",
"plt",
".",
"tight_layout",
"(",
")",
"plt",
".",
"ylabel",
"(",
"'True label'",
")",
"plt",
".",
"xlabel",
"(",
"'Predicted label'",
")"
] | Plot the confusion matrix.
Args:
figsize: tuple (x, y) of ints. Sets the size of the figure
rotation: the rotation angle of the labels on the x-axis. | [
"Plot",
"the",
"confusion",
"matrix",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_confusion_matrix.py#L129-L159 | train | 237,689 |
googledatalab/pydatalab | google/datalab/contrib/pipeline/composer/_api.py | Api.get_environment_details | def get_environment_details(zone, environment):
""" Issues a request to Composer to get the environment details.
Args:
zone: GCP zone of the composer environment
environment: name of the Composer environment
Returns:
A parsed result object.
Raises:
Exception if there is an error performing the operation.
"""
default_context = google.datalab.Context.default()
url = (Api._ENDPOINT + (Api._ENVIRONMENTS_PATH_FORMAT % (default_context.project_id, zone,
environment)))
return google.datalab.utils.Http.request(url, credentials=default_context.credentials) | python | def get_environment_details(zone, environment):
""" Issues a request to Composer to get the environment details.
Args:
zone: GCP zone of the composer environment
environment: name of the Composer environment
Returns:
A parsed result object.
Raises:
Exception if there is an error performing the operation.
"""
default_context = google.datalab.Context.default()
url = (Api._ENDPOINT + (Api._ENVIRONMENTS_PATH_FORMAT % (default_context.project_id, zone,
environment)))
return google.datalab.utils.Http.request(url, credentials=default_context.credentials) | [
"def",
"get_environment_details",
"(",
"zone",
",",
"environment",
")",
":",
"default_context",
"=",
"google",
".",
"datalab",
".",
"Context",
".",
"default",
"(",
")",
"url",
"=",
"(",
"Api",
".",
"_ENDPOINT",
"+",
"(",
"Api",
".",
"_ENVIRONMENTS_PATH_FORMAT",
"%",
"(",
"default_context",
".",
"project_id",
",",
"zone",
",",
"environment",
")",
")",
")",
"return",
"google",
".",
"datalab",
".",
"utils",
".",
"Http",
".",
"request",
"(",
"url",
",",
"credentials",
"=",
"default_context",
".",
"credentials",
")"
] | Issues a request to Composer to get the environment details.
Args:
zone: GCP zone of the composer environment
environment: name of the Composer environment
Returns:
A parsed result object.
Raises:
Exception if there is an error performing the operation. | [
"Issues",
"a",
"request",
"to",
"Composer",
"to",
"get",
"the",
"environment",
"details",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/pipeline/composer/_api.py#L24-L39 | train | 237,690 |
googledatalab/pydatalab | google/datalab/storage/_api.py | Api.buckets_delete | def buckets_delete(self, bucket):
"""Issues a request to delete a bucket.
Args:
bucket: the name of the bucket.
Raises:
Exception if there is an error performing the operation.
"""
url = Api._ENDPOINT + (Api._BUCKET_PATH % bucket)
google.datalab.utils.Http.request(url, method='DELETE', credentials=self._credentials,
raw_response=True) | python | def buckets_delete(self, bucket):
"""Issues a request to delete a bucket.
Args:
bucket: the name of the bucket.
Raises:
Exception if there is an error performing the operation.
"""
url = Api._ENDPOINT + (Api._BUCKET_PATH % bucket)
google.datalab.utils.Http.request(url, method='DELETE', credentials=self._credentials,
raw_response=True) | [
"def",
"buckets_delete",
"(",
"self",
",",
"bucket",
")",
":",
"url",
"=",
"Api",
".",
"_ENDPOINT",
"+",
"(",
"Api",
".",
"_BUCKET_PATH",
"%",
"bucket",
")",
"google",
".",
"datalab",
".",
"utils",
".",
"Http",
".",
"request",
"(",
"url",
",",
"method",
"=",
"'DELETE'",
",",
"credentials",
"=",
"self",
".",
"_credentials",
",",
"raw_response",
"=",
"True",
")"
] | Issues a request to delete a bucket.
Args:
bucket: the name of the bucket.
Raises:
Exception if there is an error performing the operation. | [
"Issues",
"a",
"request",
"to",
"delete",
"a",
"bucket",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_api.py#L72-L82 | train | 237,691 |
googledatalab/pydatalab | google/datalab/storage/_api.py | Api.buckets_get | def buckets_get(self, bucket, projection='noAcl'):
"""Issues a request to retrieve information about a bucket.
Args:
bucket: the name of the bucket.
projection: the projection of the bucket information to retrieve.
Returns:
A parsed bucket information dictionary.
Raises:
Exception if there is an error performing the operation.
"""
args = {'projection': projection}
url = Api._ENDPOINT + (Api._BUCKET_PATH % bucket)
return google.datalab.utils.Http.request(url, credentials=self._credentials, args=args) | python | def buckets_get(self, bucket, projection='noAcl'):
"""Issues a request to retrieve information about a bucket.
Args:
bucket: the name of the bucket.
projection: the projection of the bucket information to retrieve.
Returns:
A parsed bucket information dictionary.
Raises:
Exception if there is an error performing the operation.
"""
args = {'projection': projection}
url = Api._ENDPOINT + (Api._BUCKET_PATH % bucket)
return google.datalab.utils.Http.request(url, credentials=self._credentials, args=args) | [
"def",
"buckets_get",
"(",
"self",
",",
"bucket",
",",
"projection",
"=",
"'noAcl'",
")",
":",
"args",
"=",
"{",
"'projection'",
":",
"projection",
"}",
"url",
"=",
"Api",
".",
"_ENDPOINT",
"+",
"(",
"Api",
".",
"_BUCKET_PATH",
"%",
"bucket",
")",
"return",
"google",
".",
"datalab",
".",
"utils",
".",
"Http",
".",
"request",
"(",
"url",
",",
"credentials",
"=",
"self",
".",
"_credentials",
",",
"args",
"=",
"args",
")"
] | Issues a request to retrieve information about a bucket.
Args:
bucket: the name of the bucket.
projection: the projection of the bucket information to retrieve.
Returns:
A parsed bucket information dictionary.
Raises:
Exception if there is an error performing the operation. | [
"Issues",
"a",
"request",
"to",
"retrieve",
"information",
"about",
"a",
"bucket",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_api.py#L84-L97 | train | 237,692 |
googledatalab/pydatalab | google/datalab/storage/_api.py | Api.buckets_list | def buckets_list(self, projection='noAcl', max_results=0, page_token=None, project_id=None):
"""Issues a request to retrieve the list of buckets.
Args:
projection: the projection of the bucket information to retrieve.
max_results: an optional maximum number of objects to retrieve.
page_token: an optional token to continue the retrieval.
project_id: the project whose buckets should be listed.
Returns:
A parsed list of bucket information dictionaries.
Raises:
Exception if there is an error performing the operation.
"""
if max_results == 0:
max_results = Api._MAX_RESULTS
args = {'project': project_id if project_id else self._project_id, 'maxResults': max_results}
if projection is not None:
args['projection'] = projection
if page_token is not None:
args['pageToken'] = page_token
url = Api._ENDPOINT + (Api._BUCKET_PATH % '')
return google.datalab.utils.Http.request(url, args=args, credentials=self._credentials) | python | def buckets_list(self, projection='noAcl', max_results=0, page_token=None, project_id=None):
"""Issues a request to retrieve the list of buckets.
Args:
projection: the projection of the bucket information to retrieve.
max_results: an optional maximum number of objects to retrieve.
page_token: an optional token to continue the retrieval.
project_id: the project whose buckets should be listed.
Returns:
A parsed list of bucket information dictionaries.
Raises:
Exception if there is an error performing the operation.
"""
if max_results == 0:
max_results = Api._MAX_RESULTS
args = {'project': project_id if project_id else self._project_id, 'maxResults': max_results}
if projection is not None:
args['projection'] = projection
if page_token is not None:
args['pageToken'] = page_token
url = Api._ENDPOINT + (Api._BUCKET_PATH % '')
return google.datalab.utils.Http.request(url, args=args, credentials=self._credentials) | [
"def",
"buckets_list",
"(",
"self",
",",
"projection",
"=",
"'noAcl'",
",",
"max_results",
"=",
"0",
",",
"page_token",
"=",
"None",
",",
"project_id",
"=",
"None",
")",
":",
"if",
"max_results",
"==",
"0",
":",
"max_results",
"=",
"Api",
".",
"_MAX_RESULTS",
"args",
"=",
"{",
"'project'",
":",
"project_id",
"if",
"project_id",
"else",
"self",
".",
"_project_id",
",",
"'maxResults'",
":",
"max_results",
"}",
"if",
"projection",
"is",
"not",
"None",
":",
"args",
"[",
"'projection'",
"]",
"=",
"projection",
"if",
"page_token",
"is",
"not",
"None",
":",
"args",
"[",
"'pageToken'",
"]",
"=",
"page_token",
"url",
"=",
"Api",
".",
"_ENDPOINT",
"+",
"(",
"Api",
".",
"_BUCKET_PATH",
"%",
"''",
")",
"return",
"google",
".",
"datalab",
".",
"utils",
".",
"Http",
".",
"request",
"(",
"url",
",",
"args",
"=",
"args",
",",
"credentials",
"=",
"self",
".",
"_credentials",
")"
] | Issues a request to retrieve the list of buckets.
Args:
projection: the projection of the bucket information to retrieve.
max_results: an optional maximum number of objects to retrieve.
page_token: an optional token to continue the retrieval.
project_id: the project whose buckets should be listed.
Returns:
A parsed list of bucket information dictionaries.
Raises:
Exception if there is an error performing the operation. | [
"Issues",
"a",
"request",
"to",
"retrieve",
"the",
"list",
"of",
"buckets",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_api.py#L99-L122 | train | 237,693 |
googledatalab/pydatalab | google/datalab/storage/_api.py | Api.object_download | def object_download(self, bucket, key, start_offset=0, byte_count=None):
"""Reads the contents of an object as text.
Args:
bucket: the name of the bucket containing the object.
key: the key of the object to be read.
start_offset: the start offset of bytes to read.
byte_count: the number of bytes to read. If None, it reads to the end.
Returns:
The text content within the object.
Raises:
Exception if the object could not be read from.
"""
args = {'alt': 'media'}
headers = {}
if start_offset > 0 or byte_count is not None:
header = 'bytes=%d-' % start_offset
if byte_count is not None:
header += '%d' % byte_count
headers['Range'] = header
url = Api._DOWNLOAD_ENDPOINT + (Api._OBJECT_PATH % (bucket, Api._escape_key(key)))
return google.datalab.utils.Http.request(url, args=args, headers=headers,
credentials=self._credentials, raw_response=True) | python | def object_download(self, bucket, key, start_offset=0, byte_count=None):
"""Reads the contents of an object as text.
Args:
bucket: the name of the bucket containing the object.
key: the key of the object to be read.
start_offset: the start offset of bytes to read.
byte_count: the number of bytes to read. If None, it reads to the end.
Returns:
The text content within the object.
Raises:
Exception if the object could not be read from.
"""
args = {'alt': 'media'}
headers = {}
if start_offset > 0 or byte_count is not None:
header = 'bytes=%d-' % start_offset
if byte_count is not None:
header += '%d' % byte_count
headers['Range'] = header
url = Api._DOWNLOAD_ENDPOINT + (Api._OBJECT_PATH % (bucket, Api._escape_key(key)))
return google.datalab.utils.Http.request(url, args=args, headers=headers,
credentials=self._credentials, raw_response=True) | [
"def",
"object_download",
"(",
"self",
",",
"bucket",
",",
"key",
",",
"start_offset",
"=",
"0",
",",
"byte_count",
"=",
"None",
")",
":",
"args",
"=",
"{",
"'alt'",
":",
"'media'",
"}",
"headers",
"=",
"{",
"}",
"if",
"start_offset",
">",
"0",
"or",
"byte_count",
"is",
"not",
"None",
":",
"header",
"=",
"'bytes=%d-'",
"%",
"start_offset",
"if",
"byte_count",
"is",
"not",
"None",
":",
"header",
"+=",
"'%d'",
"%",
"byte_count",
"headers",
"[",
"'Range'",
"]",
"=",
"header",
"url",
"=",
"Api",
".",
"_DOWNLOAD_ENDPOINT",
"+",
"(",
"Api",
".",
"_OBJECT_PATH",
"%",
"(",
"bucket",
",",
"Api",
".",
"_escape_key",
"(",
"key",
")",
")",
")",
"return",
"google",
".",
"datalab",
".",
"utils",
".",
"Http",
".",
"request",
"(",
"url",
",",
"args",
"=",
"args",
",",
"headers",
"=",
"headers",
",",
"credentials",
"=",
"self",
".",
"_credentials",
",",
"raw_response",
"=",
"True",
")"
] | Reads the contents of an object as text.
Args:
bucket: the name of the bucket containing the object.
key: the key of the object to be read.
start_offset: the start offset of bytes to read.
byte_count: the number of bytes to read. If None, it reads to the end.
Returns:
The text content within the object.
Raises:
Exception if the object could not be read from. | [
"Reads",
"the",
"contents",
"of",
"an",
"object",
"as",
"text",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_api.py#L124-L146 | train | 237,694 |
googledatalab/pydatalab | google/datalab/storage/_api.py | Api.object_upload | def object_upload(self, bucket, key, content, content_type):
"""Writes text content to the object.
Args:
bucket: the name of the bucket containing the object.
key: the key of the object to be written.
content: the text content to be written.
content_type: the type of text content.
Raises:
Exception if the object could not be written to.
"""
args = {'uploadType': 'media', 'name': key}
headers = {'Content-Type': content_type}
url = Api._UPLOAD_ENDPOINT + (Api._OBJECT_PATH % (bucket, ''))
return google.datalab.utils.Http.request(url, args=args, data=content, headers=headers,
credentials=self._credentials, raw_response=True) | python | def object_upload(self, bucket, key, content, content_type):
"""Writes text content to the object.
Args:
bucket: the name of the bucket containing the object.
key: the key of the object to be written.
content: the text content to be written.
content_type: the type of text content.
Raises:
Exception if the object could not be written to.
"""
args = {'uploadType': 'media', 'name': key}
headers = {'Content-Type': content_type}
url = Api._UPLOAD_ENDPOINT + (Api._OBJECT_PATH % (bucket, ''))
return google.datalab.utils.Http.request(url, args=args, data=content, headers=headers,
credentials=self._credentials, raw_response=True) | [
"def",
"object_upload",
"(",
"self",
",",
"bucket",
",",
"key",
",",
"content",
",",
"content_type",
")",
":",
"args",
"=",
"{",
"'uploadType'",
":",
"'media'",
",",
"'name'",
":",
"key",
"}",
"headers",
"=",
"{",
"'Content-Type'",
":",
"content_type",
"}",
"url",
"=",
"Api",
".",
"_UPLOAD_ENDPOINT",
"+",
"(",
"Api",
".",
"_OBJECT_PATH",
"%",
"(",
"bucket",
",",
"''",
")",
")",
"return",
"google",
".",
"datalab",
".",
"utils",
".",
"Http",
".",
"request",
"(",
"url",
",",
"args",
"=",
"args",
",",
"data",
"=",
"content",
",",
"headers",
"=",
"headers",
",",
"credentials",
"=",
"self",
".",
"_credentials",
",",
"raw_response",
"=",
"True",
")"
] | Writes text content to the object.
Args:
bucket: the name of the bucket containing the object.
key: the key of the object to be written.
content: the text content to be written.
content_type: the type of text content.
Raises:
Exception if the object could not be written to. | [
"Writes",
"text",
"content",
"to",
"the",
"object",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_api.py#L148-L164 | train | 237,695 |
googledatalab/pydatalab | solutionbox/image_classification/mltoolbox/image/classification/_api.py | preprocess_async | def preprocess_async(train_dataset, output_dir, eval_dataset=None, checkpoint=None, cloud=None):
"""Preprocess data. Produce output that can be used by training efficiently.
Args:
train_dataset: training data source to preprocess. Can be CsvDataset or BigQueryDataSet.
If eval_dataset is None, the pipeline will randomly split train_dataset into
train/eval set with 7:3 ratio.
output_dir: The output directory to use. Preprocessing will create a sub directory under
it for each run, and also update "latest" file which points to the latest preprocessed
directory. Users are responsible for cleanup. Can be local or GCS path.
eval_dataset: evaluation data source to preprocess. Can be CsvDataset or BigQueryDataSet.
If specified, it will be used for evaluation during training, and train_dataset will be
completely used for training.
checkpoint: the Inception checkpoint to use. If None, a default checkpoint is used.
cloud: a DataFlow pipeline option dictionary such as {'num_workers': 3}. If anything but
not None, it will run in cloud. Otherwise, it runs locally.
Returns:
A google.datalab.utils.Job object that can be used to query state from or wait.
"""
with warnings.catch_warnings():
warnings.simplefilter("ignore")
if cloud is None:
return _local.Local.preprocess(train_dataset, output_dir, eval_dataset, checkpoint)
if not isinstance(cloud, dict):
cloud = {}
return _cloud.Cloud.preprocess(train_dataset, output_dir, eval_dataset, checkpoint, cloud) | python | def preprocess_async(train_dataset, output_dir, eval_dataset=None, checkpoint=None, cloud=None):
"""Preprocess data. Produce output that can be used by training efficiently.
Args:
train_dataset: training data source to preprocess. Can be CsvDataset or BigQueryDataSet.
If eval_dataset is None, the pipeline will randomly split train_dataset into
train/eval set with 7:3 ratio.
output_dir: The output directory to use. Preprocessing will create a sub directory under
it for each run, and also update "latest" file which points to the latest preprocessed
directory. Users are responsible for cleanup. Can be local or GCS path.
eval_dataset: evaluation data source to preprocess. Can be CsvDataset or BigQueryDataSet.
If specified, it will be used for evaluation during training, and train_dataset will be
completely used for training.
checkpoint: the Inception checkpoint to use. If None, a default checkpoint is used.
cloud: a DataFlow pipeline option dictionary such as {'num_workers': 3}. If anything but
not None, it will run in cloud. Otherwise, it runs locally.
Returns:
A google.datalab.utils.Job object that can be used to query state from or wait.
"""
with warnings.catch_warnings():
warnings.simplefilter("ignore")
if cloud is None:
return _local.Local.preprocess(train_dataset, output_dir, eval_dataset, checkpoint)
if not isinstance(cloud, dict):
cloud = {}
return _cloud.Cloud.preprocess(train_dataset, output_dir, eval_dataset, checkpoint, cloud) | [
"def",
"preprocess_async",
"(",
"train_dataset",
",",
"output_dir",
",",
"eval_dataset",
"=",
"None",
",",
"checkpoint",
"=",
"None",
",",
"cloud",
"=",
"None",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"simplefilter",
"(",
"\"ignore\"",
")",
"if",
"cloud",
"is",
"None",
":",
"return",
"_local",
".",
"Local",
".",
"preprocess",
"(",
"train_dataset",
",",
"output_dir",
",",
"eval_dataset",
",",
"checkpoint",
")",
"if",
"not",
"isinstance",
"(",
"cloud",
",",
"dict",
")",
":",
"cloud",
"=",
"{",
"}",
"return",
"_cloud",
".",
"Cloud",
".",
"preprocess",
"(",
"train_dataset",
",",
"output_dir",
",",
"eval_dataset",
",",
"checkpoint",
",",
"cloud",
")"
] | Preprocess data. Produce output that can be used by training efficiently.
Args:
train_dataset: training data source to preprocess. Can be CsvDataset or BigQueryDataSet.
If eval_dataset is None, the pipeline will randomly split train_dataset into
train/eval set with 7:3 ratio.
output_dir: The output directory to use. Preprocessing will create a sub directory under
it for each run, and also update "latest" file which points to the latest preprocessed
directory. Users are responsible for cleanup. Can be local or GCS path.
eval_dataset: evaluation data source to preprocess. Can be CsvDataset or BigQueryDataSet.
If specified, it will be used for evaluation during training, and train_dataset will be
completely used for training.
checkpoint: the Inception checkpoint to use. If None, a default checkpoint is used.
cloud: a DataFlow pipeline option dictionary such as {'num_workers': 3}. If anything but
not None, it will run in cloud. Otherwise, it runs locally.
Returns:
A google.datalab.utils.Job object that can be used to query state from or wait. | [
"Preprocess",
"data",
".",
"Produce",
"output",
"that",
"can",
"be",
"used",
"by",
"training",
"efficiently",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_api.py#L25-L52 | train | 237,696 |
googledatalab/pydatalab | solutionbox/image_classification/mltoolbox/image/classification/_api.py | train_async | def train_async(input_dir, batch_size, max_steps, output_dir, checkpoint=None, cloud=None):
"""Train model. The output can be used for batch prediction or online deployment.
Args:
input_dir: A directory path containing preprocessed results. Can be local or GCS path.
batch_size: size of batch used for training.
max_steps: number of steps to train.
output_dir: The output directory to use. Can be local or GCS path.
checkpoint: the Inception checkpoint to use. If None, a default checkpoint is used.
cloud: a google.datalab.ml.CloudTrainingConfig object to let it run in cloud.
If None, it runs locally.
Returns:
A google.datalab.utils.Job object that can be used to query state from or wait.
"""
with warnings.catch_warnings():
warnings.simplefilter("ignore")
if cloud is None:
return _local.Local.train(input_dir, batch_size, max_steps, output_dir, checkpoint)
return _cloud.Cloud.train(input_dir, batch_size, max_steps, output_dir, checkpoint, cloud) | python | def train_async(input_dir, batch_size, max_steps, output_dir, checkpoint=None, cloud=None):
"""Train model. The output can be used for batch prediction or online deployment.
Args:
input_dir: A directory path containing preprocessed results. Can be local or GCS path.
batch_size: size of batch used for training.
max_steps: number of steps to train.
output_dir: The output directory to use. Can be local or GCS path.
checkpoint: the Inception checkpoint to use. If None, a default checkpoint is used.
cloud: a google.datalab.ml.CloudTrainingConfig object to let it run in cloud.
If None, it runs locally.
Returns:
A google.datalab.utils.Job object that can be used to query state from or wait.
"""
with warnings.catch_warnings():
warnings.simplefilter("ignore")
if cloud is None:
return _local.Local.train(input_dir, batch_size, max_steps, output_dir, checkpoint)
return _cloud.Cloud.train(input_dir, batch_size, max_steps, output_dir, checkpoint, cloud) | [
"def",
"train_async",
"(",
"input_dir",
",",
"batch_size",
",",
"max_steps",
",",
"output_dir",
",",
"checkpoint",
"=",
"None",
",",
"cloud",
"=",
"None",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"simplefilter",
"(",
"\"ignore\"",
")",
"if",
"cloud",
"is",
"None",
":",
"return",
"_local",
".",
"Local",
".",
"train",
"(",
"input_dir",
",",
"batch_size",
",",
"max_steps",
",",
"output_dir",
",",
"checkpoint",
")",
"return",
"_cloud",
".",
"Cloud",
".",
"train",
"(",
"input_dir",
",",
"batch_size",
",",
"max_steps",
",",
"output_dir",
",",
"checkpoint",
",",
"cloud",
")"
] | Train model. The output can be used for batch prediction or online deployment.
Args:
input_dir: A directory path containing preprocessed results. Can be local or GCS path.
batch_size: size of batch used for training.
max_steps: number of steps to train.
output_dir: The output directory to use. Can be local or GCS path.
checkpoint: the Inception checkpoint to use. If None, a default checkpoint is used.
cloud: a google.datalab.ml.CloudTrainingConfig object to let it run in cloud.
If None, it runs locally.
Returns:
A google.datalab.utils.Job object that can be used to query state from or wait. | [
"Train",
"model",
".",
"The",
"output",
"can",
"be",
"used",
"for",
"batch",
"prediction",
"or",
"online",
"deployment",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_api.py#L66-L86 | train | 237,697 |
googledatalab/pydatalab | solutionbox/image_classification/mltoolbox/image/classification/_api.py | batch_predict_async | def batch_predict_async(dataset, model_dir, output_csv=None, output_bq_table=None, cloud=None):
"""Batch prediction with an offline model.
Args:
dataset: CsvDataSet or BigQueryDataSet for batch prediction input. Can contain either
one column 'image_url', or two columns with another being 'label'.
model_dir: The directory of a trained inception model. Can be local or GCS paths.
output_csv: The output csv file for prediction results. If specified,
it will also output a csv schema file with the name output_csv + '.schema.json'.
output_bq_table: if specified, the output BigQuery table for prediction results.
output_csv and output_bq_table can both be set.
cloud: a DataFlow pipeline option dictionary such as {'num_workers': 3}. If anything but
not None, it will run in cloud. Otherwise, it runs locally.
If specified, it must include 'temp_location' with value being a GCS path, because cloud
run requires a staging GCS directory.
Raises:
ValueError if both output_csv and output_bq_table are None, or if cloud is not None
but it does not include 'temp_location'.
Returns:
A google.datalab.utils.Job object that can be used to query state from or wait.
"""
with warnings.catch_warnings():
warnings.simplefilter("ignore")
if cloud is None:
return _local.Local.batch_predict(dataset, model_dir, output_csv, output_bq_table)
if not isinstance(cloud, dict):
cloud = {}
return _cloud.Cloud.batch_predict(dataset, model_dir, output_csv, output_bq_table, cloud) | python | def batch_predict_async(dataset, model_dir, output_csv=None, output_bq_table=None, cloud=None):
"""Batch prediction with an offline model.
Args:
dataset: CsvDataSet or BigQueryDataSet for batch prediction input. Can contain either
one column 'image_url', or two columns with another being 'label'.
model_dir: The directory of a trained inception model. Can be local or GCS paths.
output_csv: The output csv file for prediction results. If specified,
it will also output a csv schema file with the name output_csv + '.schema.json'.
output_bq_table: if specified, the output BigQuery table for prediction results.
output_csv and output_bq_table can both be set.
cloud: a DataFlow pipeline option dictionary such as {'num_workers': 3}. If anything but
not None, it will run in cloud. Otherwise, it runs locally.
If specified, it must include 'temp_location' with value being a GCS path, because cloud
run requires a staging GCS directory.
Raises:
ValueError if both output_csv and output_bq_table are None, or if cloud is not None
but it does not include 'temp_location'.
Returns:
A google.datalab.utils.Job object that can be used to query state from or wait.
"""
with warnings.catch_warnings():
warnings.simplefilter("ignore")
if cloud is None:
return _local.Local.batch_predict(dataset, model_dir, output_csv, output_bq_table)
if not isinstance(cloud, dict):
cloud = {}
return _cloud.Cloud.batch_predict(dataset, model_dir, output_csv, output_bq_table, cloud) | [
"def",
"batch_predict_async",
"(",
"dataset",
",",
"model_dir",
",",
"output_csv",
"=",
"None",
",",
"output_bq_table",
"=",
"None",
",",
"cloud",
"=",
"None",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"simplefilter",
"(",
"\"ignore\"",
")",
"if",
"cloud",
"is",
"None",
":",
"return",
"_local",
".",
"Local",
".",
"batch_predict",
"(",
"dataset",
",",
"model_dir",
",",
"output_csv",
",",
"output_bq_table",
")",
"if",
"not",
"isinstance",
"(",
"cloud",
",",
"dict",
")",
":",
"cloud",
"=",
"{",
"}",
"return",
"_cloud",
".",
"Cloud",
".",
"batch_predict",
"(",
"dataset",
",",
"model_dir",
",",
"output_csv",
",",
"output_bq_table",
",",
"cloud",
")"
] | Batch prediction with an offline model.
Args:
dataset: CsvDataSet or BigQueryDataSet for batch prediction input. Can contain either
one column 'image_url', or two columns with another being 'label'.
model_dir: The directory of a trained inception model. Can be local or GCS paths.
output_csv: The output csv file for prediction results. If specified,
it will also output a csv schema file with the name output_csv + '.schema.json'.
output_bq_table: if specified, the output BigQuery table for prediction results.
output_csv and output_bq_table can both be set.
cloud: a DataFlow pipeline option dictionary such as {'num_workers': 3}. If anything but
not None, it will run in cloud. Otherwise, it runs locally.
If specified, it must include 'temp_location' with value being a GCS path, because cloud
run requires a staging GCS directory.
Raises:
ValueError if both output_csv and output_bq_table are None, or if cloud is not None
but it does not include 'temp_location'.
Returns:
A google.datalab.utils.Job object that can be used to query state from or wait. | [
"Batch",
"prediction",
"with",
"an",
"offline",
"model",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_api.py#L126-L156 | train | 237,698 |
googledatalab/pydatalab | google/datalab/bigquery/_job.py | Job._refresh_state | def _refresh_state(self):
""" Get the state of a job. If the job is complete this does nothing;
otherwise it gets a refreshed copy of the job resource.
"""
# TODO(gram): should we put a choke on refreshes? E.g. if the last call was less than
# a second ago should we return the cached value?
if self._is_complete:
return
try:
response = self._api.jobs_get(self._job_id)
except Exception as e:
raise e
if 'status' in response:
status = response['status']
if 'state' in status and status['state'] == 'DONE':
self._end_time = datetime.datetime.utcnow()
self._is_complete = True
self._process_job_status(status)
if 'statistics' in response:
statistics = response['statistics']
start_time = statistics.get('creationTime', None)
end_time = statistics.get('endTime', None)
if start_time and end_time and end_time >= start_time:
self._start_time = datetime.datetime.fromtimestamp(float(start_time) / 1000.0)
self._end_time = datetime.datetime.fromtimestamp(float(end_time) / 1000.0) | python | def _refresh_state(self):
""" Get the state of a job. If the job is complete this does nothing;
otherwise it gets a refreshed copy of the job resource.
"""
# TODO(gram): should we put a choke on refreshes? E.g. if the last call was less than
# a second ago should we return the cached value?
if self._is_complete:
return
try:
response = self._api.jobs_get(self._job_id)
except Exception as e:
raise e
if 'status' in response:
status = response['status']
if 'state' in status and status['state'] == 'DONE':
self._end_time = datetime.datetime.utcnow()
self._is_complete = True
self._process_job_status(status)
if 'statistics' in response:
statistics = response['statistics']
start_time = statistics.get('creationTime', None)
end_time = statistics.get('endTime', None)
if start_time and end_time and end_time >= start_time:
self._start_time = datetime.datetime.fromtimestamp(float(start_time) / 1000.0)
self._end_time = datetime.datetime.fromtimestamp(float(end_time) / 1000.0) | [
"def",
"_refresh_state",
"(",
"self",
")",
":",
"# TODO(gram): should we put a choke on refreshes? E.g. if the last call was less than",
"# a second ago should we return the cached value?",
"if",
"self",
".",
"_is_complete",
":",
"return",
"try",
":",
"response",
"=",
"self",
".",
"_api",
".",
"jobs_get",
"(",
"self",
".",
"_job_id",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"e",
"if",
"'status'",
"in",
"response",
":",
"status",
"=",
"response",
"[",
"'status'",
"]",
"if",
"'state'",
"in",
"status",
"and",
"status",
"[",
"'state'",
"]",
"==",
"'DONE'",
":",
"self",
".",
"_end_time",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"self",
".",
"_is_complete",
"=",
"True",
"self",
".",
"_process_job_status",
"(",
"status",
")",
"if",
"'statistics'",
"in",
"response",
":",
"statistics",
"=",
"response",
"[",
"'statistics'",
"]",
"start_time",
"=",
"statistics",
".",
"get",
"(",
"'creationTime'",
",",
"None",
")",
"end_time",
"=",
"statistics",
".",
"get",
"(",
"'endTime'",
",",
"None",
")",
"if",
"start_time",
"and",
"end_time",
"and",
"end_time",
">=",
"start_time",
":",
"self",
".",
"_start_time",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"float",
"(",
"start_time",
")",
"/",
"1000.0",
")",
"self",
".",
"_end_time",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"float",
"(",
"end_time",
")",
"/",
"1000.0",
")"
] | Get the state of a job. If the job is complete this does nothing;
otherwise it gets a refreshed copy of the job resource. | [
"Get",
"the",
"state",
"of",
"a",
"job",
".",
"If",
"the",
"job",
"is",
"complete",
"this",
"does",
"nothing",
";",
"otherwise",
"it",
"gets",
"a",
"refreshed",
"copy",
"of",
"the",
"job",
"resource",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_job.py#L43-L70 | train | 237,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.