Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line after this snippet: <|code_start|> agent_type='OTHER',
agent_role='CREATOR',
othertype='SOFTWARE'))
else:
agents = [mets.agent(attributes["organization_name"],
agent_role='CREATOR')]
# Create mets header
metshdr = mets.metshdr(attributes["create_date"],
attributes["last_moddate"],
attributes["record_status"],
agents)
# Collect elements from workspace XML files
elements = []
for entry in scandir(attributes["workspace"]):
if entry.name.endswith(('-amd.xml', 'dmdsec.xml',
'structmap.xml', 'filesec.xml',
'rightsmd.xml')) and entry.is_file():
element = lxml.etree.parse(entry.path).getroot()[0]
elements.append(element)
elements = mets.merge_elements('{%s}amdSec' % NAMESPACES['mets'], elements)
elements.sort(key=mets.order)
# Create METS element
mets_element = mets.mets(METS_PROFILE[attributes["mets_profile"]],
objid=attributes["objid"],
label=attributes["label"],
namespaces=NAMESPACES)
<|code_end|>
using the current file's imports:
import datetime
import os
import sys
import uuid
import six
import click
import lxml.etree
import mets
import xml_helpers.utils as xml_utils
from shutil import copyfile
from siptools.utils import get_objectlist, read_md_references
from siptools.xml.mets import (METS_CATALOG, METS_PROFILE, METS_SPECIFICATION,
NAMESPACES, RECORD_STATUS_TYPES, mets_extend)
from scandir import scandir # Python 2
from os import scandir # Python 3+
and any relevant context from other files:
# Path: siptools/utils.py
# def get_objectlist(refs_dict, file_path=None):
# """Get unique and sorted list of files or streams.
#
# Files or streasm are read from md-references.jsonl
#
# :refs_dict: Dictionary of objects
# :file_path: If given, finds streams of the given file.
# If None, finds a sorted list all file paths.
# :returns: Sorted list of files, or streams of a given file
# """
# objectset = set()
# if file_path is not None:
# for stream in refs_dict[file_path]['streams']:
# objectset.add(stream)
# elif refs_dict:
# for key, value in six.iteritems(refs_dict):
# if value['path_type'] == 'file':
# objectset.add(key)
#
# return sorted(objectset)
#
# def read_md_references(workspace, ref_file):
# """Read all the MD IDs as a dictionary.
#
# :workspace: path to workspace directory
# :ref_file: Metadata reference file
# :returns: A dict of references or None if reference file doesn't
# exist
# """
# reference_file = os.path.join(workspace, ref_file)
#
# if os.path.isfile(reference_file):
# references = {}
# with open(reference_file) as in_file:
# for line in in_file:
# references.update(json.loads(line))
# return references
# return None
#
# Path: siptools/xml/mets.py
# METS_CATALOG = "1.7.3"
#
# METS_PROFILE = {
# 'ch': 'http://digitalpreservation.fi/mets-profiles/cultural-heritage',
# 'tpas': 'http://digitalpreservation.fi/mets-profiles/research-data',
# }
#
# METS_SPECIFICATION = "1.7.3"
#
# NAMESPACES = {
# 'mets': 'http://www.loc.gov/METS/',
# 'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
# 'premis': 'info:lc/xmlns/premis-v2',
# 'fi': 'http://digitalpreservation.fi/schemas/mets/fi-extensions',
# 'xlink': 'http://www.w3.org/1999/xlink',
# 'mix': 'http://www.loc.gov/mix/v20',
# 'ead3': 'http://ead3.archivists.org/schema/',
# 'addml': 'http://www.arkivverket.no/standarder/addml',
# 'audiomd': 'http://www.loc.gov/audioMD/',
# 'videomd': 'http://www.loc.gov/videoMD/'
# }
#
# RECORD_STATUS_TYPES = [
# 'submission',
# 'update',
# 'dissemination'
# ]
#
# def mets_extend(mets_root, catalog=METS_CATALOG,
# specification=METS_SPECIFICATION, contentid=None,
# contractid=None):
# """Create METS ElementTree"""
#
# del mets_root.attrib['{%s}schemaLocation' % XSI_NS]
# mets_root.set('{%s}schemaLocation' % XSI_NS,
# NAMESPACES['mets'] + ' ' + METS_SCHEMA)
# mets_root.set('{%s}CATALOG' % FI_NS, catalog)
# mets_root.set('{%s}SPECIFICATION' % FI_NS, specification)
# if contentid:
# mets_root.set('{%s}CONTENTID' % FI_NS, contentid)
# if contractid:
# contractstr = six.text_type(contractid)
# mets_root.set('{%s}CONTRACTID' % FI_NS, contractstr)
#
# return mets_root
. Output only the next line. | mets_element = mets_extend(mets_element, |
Next line prediction: <|code_start|> # define trainable parameters
self._params = [self.X2Y, self.y_bias]
def train(self, a_ts, a_dev_data=None):
"""Method for training the model.
Args:
a_ts (list(2-tuple(x, y))):
list of training JSON data
a_dev_data (2-tuple(dict, dict) or None):
list of development JSON data
Returns:
(void)
"""
# gold vector
y_gold = TT.dvector(name="y_gold")
# define cost and optimization function
cost = TT.sum((self.y_pred - y_gold) ** 2)
# predict = theano.function([self.x, y_gold], [self.y_pred, cost],
# name="predict")
gradients = TT.grad(cost, wrt=self._params)
f_grad_shared, f_update, _ = rmsprop(self._params, gradients,
[self.x], y_gold, cost)
# perform actual training
min_cost = INF
best_params = []
start_time = end_time = None
time_delta = prev_icost = icost = 0.
<|code_end|>
. Use current file imports:
(from dsenser.theano_utils import floatX, rmsprop, \
CONV_EPS, HE_UNIFORM, MAX_ITERS
from datetime import datetime
from lasagne.init import HeUniform, Orthogonal
from theano import config, tensor as TT
import numpy as np
import sys
import theano)
and context including class names, function names, or small code snippets from other files:
# Path: dsenser/theano_utils.py
# def floatX(a_data, a_dtype=config.floatX):
# """Return numpy array populated with the given data.
#
# Args:
# data (np.array):
# input tensor
# dtype (class):
# digit type
#
# Returns:
# np.array:
# array populated with the given data
#
# """
# return np.asarray(a_data, dtype=a_dtype)
#
# def rmsprop(tparams, grads, x, y, cost):
# """A variant of SGD that automatically scales the step size.
#
# Args:
# tpramas (Theano SharedVariable):
# Model parameters
# grads (Theano variable):
# Gradients of cost w.r.t to parameres
# x (list):
# Model inputs
# y (Theano variable):
# Targets
# cost (Theano variable):
# Objective fucntion to minimize
#
# Notes:
# For more information, see [Hint2014]_.
#
# .. [Hint2014] Geoff Hinton, *Neural Networks for Machine Learning*,
# lecture 6a,
# http://cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf
#
# """
# zipped_grads = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
# running_grads = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
# running_grads2 = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
#
# zgup = [(zg, g) for zg, g in zip(zipped_grads, grads)]
# rgup = [(rg, 0.95 * rg + 0.05 * g) for rg, g in zip(running_grads, grads)]
# rg2up = [(rg2, 0.95 * rg2 + 0.05 * (g ** 2))
# for rg2, g in zip(running_grads2, grads)]
#
# f_grad_shared = theano.function(x + [y], cost,
# updates=zgup + rgup + rg2up,
# name='rmsprop_f_grad_shared')
# updir = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
# updir_new = [(ud, 0.9 * ud - 1e-4 * zg / TT.sqrt(rg2 - rg ** 2 + 1e-4))
# for ud, zg, rg, rg2 in zip(updir, zipped_grads, running_grads,
# running_grads2)]
# param_up = [(p, p + udn[1])
# for p, udn in zip(tparams, updir_new)]
# f_update = theano.function([], [], updates=updir_new + param_up,
# on_unused_input='ignore',
# name='rmsprop_f_update')
# params = [zipped_grads, running_grads, running_grads2, updir]
# return (f_grad_shared, f_update, params)
#
# CONV_EPS = 1e-5
#
# HE_UNIFORM = lambda x: floatX(_HE_UNIFORM.sample(x))
#
# MAX_ITERS = 150 # 450
. Output only the next line. | a_ts = [(floatX(x), floatX(y)) for x, y in a_ts] |
Using the snippet: <|code_start|> self.y_pred = TT.nnet.softmax(
TT.tensordot(self.x, self.X2Y, ((1, 0), (2, 1))) + self.y_bias)
# predicted label
self.y_lbl = TT.argmax(self.y_pred, axis=1)[0]
self._predict = theano.function([self.x],
[self.y_lbl, self.y_pred],
name="predict")
# define trainable parameters
self._params = [self.X2Y, self.y_bias]
def train(self, a_ts, a_dev_data=None):
"""Method for training the model.
Args:
a_ts (list(2-tuple(x, y))):
list of training JSON data
a_dev_data (2-tuple(dict, dict) or None):
list of development JSON data
Returns:
(void)
"""
# gold vector
y_gold = TT.dvector(name="y_gold")
# define cost and optimization function
cost = TT.sum((self.y_pred - y_gold) ** 2)
# predict = theano.function([self.x, y_gold], [self.y_pred, cost],
# name="predict")
gradients = TT.grad(cost, wrt=self._params)
<|code_end|>
, determine the next line of code. You have imports:
from dsenser.theano_utils import floatX, rmsprop, \
CONV_EPS, HE_UNIFORM, MAX_ITERS
from datetime import datetime
from lasagne.init import HeUniform, Orthogonal
from theano import config, tensor as TT
import numpy as np
import sys
import theano
and context (class names, function names, or code) available:
# Path: dsenser/theano_utils.py
# def floatX(a_data, a_dtype=config.floatX):
# """Return numpy array populated with the given data.
#
# Args:
# data (np.array):
# input tensor
# dtype (class):
# digit type
#
# Returns:
# np.array:
# array populated with the given data
#
# """
# return np.asarray(a_data, dtype=a_dtype)
#
# def rmsprop(tparams, grads, x, y, cost):
# """A variant of SGD that automatically scales the step size.
#
# Args:
# tpramas (Theano SharedVariable):
# Model parameters
# grads (Theano variable):
# Gradients of cost w.r.t to parameres
# x (list):
# Model inputs
# y (Theano variable):
# Targets
# cost (Theano variable):
# Objective fucntion to minimize
#
# Notes:
# For more information, see [Hint2014]_.
#
# .. [Hint2014] Geoff Hinton, *Neural Networks for Machine Learning*,
# lecture 6a,
# http://cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf
#
# """
# zipped_grads = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
# running_grads = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
# running_grads2 = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
#
# zgup = [(zg, g) for zg, g in zip(zipped_grads, grads)]
# rgup = [(rg, 0.95 * rg + 0.05 * g) for rg, g in zip(running_grads, grads)]
# rg2up = [(rg2, 0.95 * rg2 + 0.05 * (g ** 2))
# for rg2, g in zip(running_grads2, grads)]
#
# f_grad_shared = theano.function(x + [y], cost,
# updates=zgup + rgup + rg2up,
# name='rmsprop_f_grad_shared')
# updir = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
# updir_new = [(ud, 0.9 * ud - 1e-4 * zg / TT.sqrt(rg2 - rg ** 2 + 1e-4))
# for ud, zg, rg, rg2 in zip(updir, zipped_grads, running_grads,
# running_grads2)]
# param_up = [(p, p + udn[1])
# for p, udn in zip(tparams, updir_new)]
# f_update = theano.function([], [], updates=updir_new + param_up,
# on_unused_input='ignore',
# name='rmsprop_f_update')
# params = [zipped_grads, running_grads, running_grads2, updir]
# return (f_grad_shared, f_update, params)
#
# CONV_EPS = 1e-5
#
# HE_UNIFORM = lambda x: floatX(_HE_UNIFORM.sample(x))
#
# MAX_ITERS = 150 # 450
. Output only the next line. | f_grad_shared, f_update, _ = rmsprop(self._params, gradients, |
Continue the code snippet: <|code_start|> # name="predict")
gradients = TT.grad(cost, wrt=self._params)
f_grad_shared, f_update, _ = rmsprop(self._params, gradients,
[self.x], y_gold, cost)
# perform actual training
min_cost = INF
best_params = []
start_time = end_time = None
time_delta = prev_icost = icost = 0.
a_ts = [(floatX(x), floatX(y)) for x, y in a_ts]
for i in xrange(MAX_ITERS):
icost = 0.
np.random.shuffle(a_ts)
start_time = datetime.utcnow()
for x_i, y_i in a_ts:
try:
icost += f_grad_shared(x_i, y_i)
f_update()
except Exception as e:
raise e
if icost < min_cost:
best_params = [p.get_value() for p in self._params]
min_cost = icost
end_time = datetime.utcnow()
time_delta = (end_time - start_time).seconds
print(
"Iteration #{:d}: cost = {:f} ({:.2f} sec)".format(i,
icost,
time_delta),
file=sys.stderr)
<|code_end|>
. Use current file imports:
from dsenser.theano_utils import floatX, rmsprop, \
CONV_EPS, HE_UNIFORM, MAX_ITERS
from datetime import datetime
from lasagne.init import HeUniform, Orthogonal
from theano import config, tensor as TT
import numpy as np
import sys
import theano
and context (classes, functions, or code) from other files:
# Path: dsenser/theano_utils.py
# def floatX(a_data, a_dtype=config.floatX):
# """Return numpy array populated with the given data.
#
# Args:
# data (np.array):
# input tensor
# dtype (class):
# digit type
#
# Returns:
# np.array:
# array populated with the given data
#
# """
# return np.asarray(a_data, dtype=a_dtype)
#
# def rmsprop(tparams, grads, x, y, cost):
# """A variant of SGD that automatically scales the step size.
#
# Args:
# tpramas (Theano SharedVariable):
# Model parameters
# grads (Theano variable):
# Gradients of cost w.r.t to parameres
# x (list):
# Model inputs
# y (Theano variable):
# Targets
# cost (Theano variable):
# Objective fucntion to minimize
#
# Notes:
# For more information, see [Hint2014]_.
#
# .. [Hint2014] Geoff Hinton, *Neural Networks for Machine Learning*,
# lecture 6a,
# http://cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf
#
# """
# zipped_grads = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
# running_grads = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
# running_grads2 = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
#
# zgup = [(zg, g) for zg, g in zip(zipped_grads, grads)]
# rgup = [(rg, 0.95 * rg + 0.05 * g) for rg, g in zip(running_grads, grads)]
# rg2up = [(rg2, 0.95 * rg2 + 0.05 * (g ** 2))
# for rg2, g in zip(running_grads2, grads)]
#
# f_grad_shared = theano.function(x + [y], cost,
# updates=zgup + rgup + rg2up,
# name='rmsprop_f_grad_shared')
# updir = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
# updir_new = [(ud, 0.9 * ud - 1e-4 * zg / TT.sqrt(rg2 - rg ** 2 + 1e-4))
# for ud, zg, rg, rg2 in zip(updir, zipped_grads, running_grads,
# running_grads2)]
# param_up = [(p, p + udn[1])
# for p, udn in zip(tparams, updir_new)]
# f_update = theano.function([], [], updates=updir_new + param_up,
# on_unused_input='ignore',
# name='rmsprop_f_update')
# params = [zipped_grads, running_grads, running_grads2, updir]
# return (f_grad_shared, f_update, params)
#
# CONV_EPS = 1e-5
#
# HE_UNIFORM = lambda x: floatX(_HE_UNIFORM.sample(x))
#
# MAX_ITERS = 150 # 450
. Output only the next line. | if abs(prev_icost - icost) < CONV_EPS: |
Given snippet: <|code_start|># Class
class BaseJudge(object):
"""Meta-classifier.
This classifier unites decisions of other multiple independent classifiers.
Attrs:
Methods:
"""
def __init__(self, a_n_x, a_n_y):
"""Class constructor.
Args:
a_n_x (int):
number of underlying cassifiers
a_n_y (int):
number of classes to predict
"""
self.n_x = a_n_x
self.n_y = a_n_y
# define the network
# input matrix
self.x = TT.dmatrix(name="x")
# mapping from input to output vector
self.X2Y = self._init_X2Y()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from dsenser.theano_utils import floatX, rmsprop, \
CONV_EPS, HE_UNIFORM, MAX_ITERS
from datetime import datetime
from lasagne.init import HeUniform, Orthogonal
from theano import config, tensor as TT
import numpy as np
import sys
import theano
and context:
# Path: dsenser/theano_utils.py
# def floatX(a_data, a_dtype=config.floatX):
# """Return numpy array populated with the given data.
#
# Args:
# data (np.array):
# input tensor
# dtype (class):
# digit type
#
# Returns:
# np.array:
# array populated with the given data
#
# """
# return np.asarray(a_data, dtype=a_dtype)
#
# def rmsprop(tparams, grads, x, y, cost):
# """A variant of SGD that automatically scales the step size.
#
# Args:
# tpramas (Theano SharedVariable):
# Model parameters
# grads (Theano variable):
# Gradients of cost w.r.t to parameres
# x (list):
# Model inputs
# y (Theano variable):
# Targets
# cost (Theano variable):
# Objective fucntion to minimize
#
# Notes:
# For more information, see [Hint2014]_.
#
# .. [Hint2014] Geoff Hinton, *Neural Networks for Machine Learning*,
# lecture 6a,
# http://cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf
#
# """
# zipped_grads = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
# running_grads = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
# running_grads2 = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
#
# zgup = [(zg, g) for zg, g in zip(zipped_grads, grads)]
# rgup = [(rg, 0.95 * rg + 0.05 * g) for rg, g in zip(running_grads, grads)]
# rg2up = [(rg2, 0.95 * rg2 + 0.05 * (g ** 2))
# for rg2, g in zip(running_grads2, grads)]
#
# f_grad_shared = theano.function(x + [y], cost,
# updates=zgup + rgup + rg2up,
# name='rmsprop_f_grad_shared')
# updir = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
# updir_new = [(ud, 0.9 * ud - 1e-4 * zg / TT.sqrt(rg2 - rg ** 2 + 1e-4))
# for ud, zg, rg, rg2 in zip(updir, zipped_grads, running_grads,
# running_grads2)]
# param_up = [(p, p + udn[1])
# for p, udn in zip(tparams, updir_new)]
# f_update = theano.function([], [], updates=updir_new + param_up,
# on_unused_input='ignore',
# name='rmsprop_f_update')
# params = [zipped_grads, running_grads, running_grads2, updir]
# return (f_grad_shared, f_update, params)
#
# CONV_EPS = 1e-5
#
# HE_UNIFORM = lambda x: floatX(_HE_UNIFORM.sample(x))
#
# MAX_ITERS = 150 # 450
which might include code, classes, or functions. Output only the next line. | self.y_bias = theano.shared(value=HE_UNIFORM((1, self.n_y)), |
Predict the next line for this snippet: <|code_start|> self._params = [self.X2Y, self.y_bias]
def train(self, a_ts, a_dev_data=None):
"""Method for training the model.
Args:
a_ts (list(2-tuple(x, y))):
list of training JSON data
a_dev_data (2-tuple(dict, dict) or None):
list of development JSON data
Returns:
(void)
"""
# gold vector
y_gold = TT.dvector(name="y_gold")
# define cost and optimization function
cost = TT.sum((self.y_pred - y_gold) ** 2)
# predict = theano.function([self.x, y_gold], [self.y_pred, cost],
# name="predict")
gradients = TT.grad(cost, wrt=self._params)
f_grad_shared, f_update, _ = rmsprop(self._params, gradients,
[self.x], y_gold, cost)
# perform actual training
min_cost = INF
best_params = []
start_time = end_time = None
time_delta = prev_icost = icost = 0.
a_ts = [(floatX(x), floatX(y)) for x, y in a_ts]
<|code_end|>
with the help of current file imports:
from dsenser.theano_utils import floatX, rmsprop, \
CONV_EPS, HE_UNIFORM, MAX_ITERS
from datetime import datetime
from lasagne.init import HeUniform, Orthogonal
from theano import config, tensor as TT
import numpy as np
import sys
import theano
and context from other files:
# Path: dsenser/theano_utils.py
# def floatX(a_data, a_dtype=config.floatX):
# """Return numpy array populated with the given data.
#
# Args:
# data (np.array):
# input tensor
# dtype (class):
# digit type
#
# Returns:
# np.array:
# array populated with the given data
#
# """
# return np.asarray(a_data, dtype=a_dtype)
#
# def rmsprop(tparams, grads, x, y, cost):
# """A variant of SGD that automatically scales the step size.
#
# Args:
# tpramas (Theano SharedVariable):
# Model parameters
# grads (Theano variable):
# Gradients of cost w.r.t to parameres
# x (list):
# Model inputs
# y (Theano variable):
# Targets
# cost (Theano variable):
# Objective fucntion to minimize
#
# Notes:
# For more information, see [Hint2014]_.
#
# .. [Hint2014] Geoff Hinton, *Neural Networks for Machine Learning*,
# lecture 6a,
# http://cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf
#
# """
# zipped_grads = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
# running_grads = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
# running_grads2 = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
#
# zgup = [(zg, g) for zg, g in zip(zipped_grads, grads)]
# rgup = [(rg, 0.95 * rg + 0.05 * g) for rg, g in zip(running_grads, grads)]
# rg2up = [(rg2, 0.95 * rg2 + 0.05 * (g ** 2))
# for rg2, g in zip(running_grads2, grads)]
#
# f_grad_shared = theano.function(x + [y], cost,
# updates=zgup + rgup + rg2up,
# name='rmsprop_f_grad_shared')
# updir = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
# updir_new = [(ud, 0.9 * ud - 1e-4 * zg / TT.sqrt(rg2 - rg ** 2 + 1e-4))
# for ud, zg, rg, rg2 in zip(updir, zipped_grads, running_grads,
# running_grads2)]
# param_up = [(p, p + udn[1])
# for p, udn in zip(tparams, updir_new)]
# f_update = theano.function([], [], updates=updir_new + param_up,
# on_unused_input='ignore',
# name='rmsprop_f_update')
# params = [zipped_grads, running_grads, running_grads2, updir]
# return (f_grad_shared, f_update, params)
#
# CONV_EPS = 1e-5
#
# HE_UNIFORM = lambda x: floatX(_HE_UNIFORM.sample(x))
#
# MAX_ITERS = 150 # 450
, which may contain function names, class names, or code. Output only the next line. | for i in xrange(MAX_ITERS): |
Here is a snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
"""Module providing class for generic word embeddings.
Attributes:
WEMB (class):
class for fast retrieval and adjustment of the Google word embeddings
"""
##################################################################
# Imports
from __future__ import absolute_import, print_function
##################################################################
# Class
@singleton
class Word2Vec(object):
"""Class for cached retrieval of word embeddings.
"""
<|code_end|>
. Write the next line using the current file imports:
from dsenser.resources import W2V
from dsenser.utils import singleton
import numpy as np
and context from other files:
# Path: dsenser/resources.py
# W2V = LoadOnDemand(load_W2V, DFLT_W2V_PATH)
#
# Path: dsenser/utils.py
# def singleton(cls):
# """Make `cls` instance unique across all calls.
#
# Args:
# cls (class):
# class to be decorated
#
# Retuns:
# object:
# singleton instance of the decorated class
#
# """
# instance = cls()
# instance.__call__ = lambda: instance
# return instance
, which may include functions, classes, or code. Output only the next line. | def __init__(self, a_w2v=W2V): |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
"""Module providing class for generic word embeddings.
Attributes:
WEMB (class):
class for fast retrieval and adjustment of the Google word embeddings
"""
##################################################################
# Imports
from __future__ import absolute_import, print_function
##################################################################
# Class
<|code_end|>
using the current file's imports:
from dsenser.resources import W2V
from dsenser.utils import singleton
import numpy as np
and any relevant context from other files:
# Path: dsenser/resources.py
# W2V = LoadOnDemand(load_W2V, DFLT_W2V_PATH)
#
# Path: dsenser/utils.py
# def singleton(cls):
# """Make `cls` instance unique across all calls.
#
# Args:
# cls (class):
# class to be decorated
#
# Retuns:
# object:
# singleton instance of the decorated class
#
# """
# instance = cls()
# instance.__call__ = lambda: instance
# return instance
. Output only the next line. | @singleton |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import
##################################################################
# Constants
##################################################################
# Test Classes
class TestLSTMImplict(TestCase):
def test_train(self):
with patch("dsenser.lstm.lstmbase.LSTMBaseSenser.train",
autospec=True):
<|code_end|>
. Use current file imports:
from dsenser.lstm.implicit import LSTMImplicitSenser
from mock import patch
from unittest import TestCase
import dsenser
and context (classes, functions, or code) from other files:
# Path: dsenser/lstm/implicit.py
# class LSTMImplicitSenser(LSTMBaseSenser):
# """Class for disambiguating explicit connectives.
#
# """
#
# @timeit("Training implicit LSTM classifier...")
# def train(self, *args, **kwargs):
# super(LSTMImplicitSenser, self).train(*args, **kwargs)
. Output only the next line. | lstm = LSTMImplicitSenser() |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import, print_function
##################################################################
# Constants
N_Y = 5
EPS = 0.499
TRG_CLS = 1
IV = np.zeros((1, 5)) + EPS / N_Y
IV[0, TRG_CLS] = 1. - EPS
##################################################################
# Test Classes
class TestXGBoostBaseSenser(TestCase):
@fixture(autouse=True)
def set_ds(self):
<|code_end|>
, generate the next line using the imports in this file:
from dsenser.xgboost.xgboostbase import XGBoostBaseSenser
from mock import patch, MagicMock
from pytest import fixture
from unittest import TestCase
import numpy as np
import xgboost
import sklearn
and context (functions, classes, or occasionally code) from other files:
# Path: dsenser/xgboost/xgboostbase.py
# class XGBoostBaseSenser(object):
# """Base sense classifier using XGBoost.
#
# """
#
# def __init__(self, a_clf=None, a_grid_search=False):
# """Class constructor.
#
# Args:
# a_clf (classifier or None):
# classifier to use or None for default
# a_grid_search (bool): use grid search for estimating
# hyper-parameters
#
# """
# classifier = a_clf
# self._gs = a_grid_search
# if a_clf is None:
# classifier = XGBClassifier(max_depth=MAX_DEPTH,
# n_estimators=NTREES,
# learning_rate=ALPHA,
# objective="multi:softprob")
# self._clf = classifier
# # latest version of XGBoost cannot deal with non-sparse feature vectors
# self._model = Pipeline([("vect", DictVectorizer()),
# ("clf", classifier)])
#
# def _predict(self, a_feats, a_ret, a_i):
# """Method for predicting sense of single relation.
#
# Args:
# a_feats (dict):
# features of the input instance
# a_ret (np.array):
# output prediction vector
# a_i (int):
# row index in the output vector
#
# Returns:
# void:
#
# Note:
# updates ``a_ret`` in place
#
# """
# ret = self._model.predict_proba(a_feats)[0]
# if self._clf is None:
# a_ret[a_i] += ret
# else:
# for i, j in enumerate(ret):
# a_ret[a_i][self._clf._le.inverse_transform(i)] += j
. Output only the next line. | self.xgb = XGBoostBaseSenser() |
Based on the snippet: <|code_start|>
Returns:
method: wrapped method
"""
def _wrapper(*args, **kwargs):
print(self.msg + " started", file=sys.stderr)
start_time = datetime.utcnow()
a_func(*args, **kwargs)
end_time = datetime.utcnow()
time_delta = (end_time - start_time).total_seconds()
print(self.msg + " finished ({:.2f} sec)".format(time_delta),
file=sys.stderr)
return wraps(a_func)(_wrapper)
##################################################################
# Methods
def is_explicit(a_rel):
"""Check whether given relation is explicit.
Args:
a_rel (dict):
discourse relation to classify
Returns:
bool:
``True`` if the relation is explicit, ``False`` otherwise
"""
<|code_end|>
, predict the immediate next line with the help of imports:
from dsenser.constants import CONNECTIVE, TOK_LIST
from datetime import datetime
from functools import wraps
import sys
and context (classes, functions, sometimes code) from other files:
# Path: dsenser/constants.py
# CONNECTIVE = "Connective"
#
# TOK_LIST = "TokenList"
. Output only the next line. | return bool(a_rel[CONNECTIVE][TOK_LIST]) |
Next line prediction: <|code_start|>
Returns:
method: wrapped method
"""
def _wrapper(*args, **kwargs):
print(self.msg + " started", file=sys.stderr)
start_time = datetime.utcnow()
a_func(*args, **kwargs)
end_time = datetime.utcnow()
time_delta = (end_time - start_time).total_seconds()
print(self.msg + " finished ({:.2f} sec)".format(time_delta),
file=sys.stderr)
return wraps(a_func)(_wrapper)
##################################################################
# Methods
def is_explicit(a_rel):
"""Check whether given relation is explicit.
Args:
a_rel (dict):
discourse relation to classify
Returns:
bool:
``True`` if the relation is explicit, ``False`` otherwise
"""
<|code_end|>
. Use current file imports:
(from dsenser.constants import CONNECTIVE, TOK_LIST
from datetime import datetime
from functools import wraps
import sys)
and context including class names, function names, or small code snippets from other files:
# Path: dsenser/constants.py
# CONNECTIVE = "Connective"
#
# TOK_LIST = "TokenList"
. Output only the next line. | return bool(a_rel[CONNECTIVE][TOK_LIST]) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import
##################################################################
# Constants
##################################################################
# Test Classes
class TestXGBoostImplict(TestCase):
def test_train(self):
with patch("dsenser.wang.wangbase.WangBaseSenser.train",
autospec=True):
<|code_end|>
. Use current file imports:
import dsenser
from dsenser.xgboost.implicit import XGBoostImplicitSenser
from mock import patch
from unittest import TestCase
and context (classes, functions, or code) from other files:
# Path: dsenser/xgboost/implicit.py
# class XGBoostImplicitSenser(XGBoostBaseSenser, WangImplicitSenser):
# """Subclass of implicit WangSenser using XGBoost.
#
# """
# PARAM_GRID = BASE_PARAM_GRID
# N_JOBS = BASE_N_JOBS
#
# @timeit("Training implicit XGBoost classifier...")
# def train(self, *args, **kwargs):
# super(WangImplicitSenser, self).train(*args, **kwargs)
. Output only the next line. | xgb = XGBoostImplicitSenser() |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import
##################################################################
# Constants
##################################################################
# Test Classes
class TestSVDImplict(TestCase):
def test_train(self):
with patch("dsenser.svd.svdbase.SVDBaseSenser.train",
autospec=True):
<|code_end|>
, predict the immediate next line with the help of imports:
from dsenser.svd.implicit import SVDImplicitSenser
from mock import patch
from unittest import TestCase
import dsenser
and context (classes, functions, sometimes code) from other files:
# Path: dsenser/svd/implicit.py
# class SVDImplicitSenser(SVDBaseSenser):
# """Class for disambiguating implicit discourse relations.
#
# """
#
# @timeit("Training implicit SVD classifier...")
# def train(self, *args, **kwargs):
# super(SVDImplicitSenser, self).train(*args, **kwargs)
. Output only the next line. | svd = SVDImplicitSenser() |
Next line prediction: <|code_start|> ["authorization", {"PartOfSpeech": "NN"}],
[".", {"PartOfSpeech": "."}]]}]}}
REL1 = {"DocID": "wsj_2200",
"Arg1": {"CharacterSpanList": [[517, 564]],
"RawText": "to restrict the RTC to Treasury"
" borrowings only",
"TokenList": [[517, 519, 85, 2, 3], [520, 528, 86, 2, 4],
[529, 532, 87, 2, 5], [533, 536, 88, 2, 6],
[537, 539, 89, 2, 7], [540, 548, 90, 2, 8],
[549, 559, 91, 2, 9], [560, 564, 92, 2, 10]]},
"Arg2": {"CharacterSpanList": [[573, 629]], "RawText": "the agency"
" receives specific congressional authorization",
"TokenList": [[573, 576, 95, 2, 13], [577, 583, 96, 2, 14],
[584, 592, 97, 2, 15], [593, 601, 98, 2, 16],
[602, 615, 99, 2, 17], [616, 629, 100, 2, 18]]},
CONNECTIVE: {"CharacterSpanList": [[566, 572]], RAW_TEXT: "unless",
"TokenList": [[566, 572, 94, 2, 12]]},
"Sense": [], "Type": "", "ID": 35709}
VEC0 = np.array([0, 0, 0, 0])
VEC1 = np.array([0, 1, 2, 3])
VEC2 = np.array([4, 5, 6, 7])
VEC3 = np.array([8, 9, 10, 11])
##################################################################
# Test Methods
def test_norm_vec():
a = np.ones(10)
<|code_end|>
. Use current file imports:
(from dsenser.nnbase import _norm_vec, _norm_word, NNBaseSenser, DFLT_VDIM
from dsenser.constants import CONNECTIVE, WORDS, SENTENCES, RAW_TEXT
from pytest import fixture
from mock import patch, MagicMock, Mock
from unittest import TestCase
import dsenser
import dsenser.nnbase
import numpy as np
import pytest
import theano)
and context including class names, function names, or small code snippets from other files:
# Path: dsenser/nnbase.py
# MAX = 1e10
# INF = float('inf')
# UNK_PROB = lambda: np.random.binomial(1, 0.05)
# DIG_RE = re.compile(r"^[\d.]*\d[\d.]*$")
# def _norm_vec(a_x):
# def _norm_word(a_word):
# def __init__(self, a_w2v=False, a_lstsq=False, a_max_iters=MAX_ITERS):
# def train(self, a_train_data, a_dev_data=None, a_n_y=-1,
# a_i=-1, a_train_out=None, a_dev_out=None):
# def _init_nn(self):
# def predict(self, a_rel, a_data, a_ret, a_i):
# def _predict(self, a_args, a_ret, a_i):
# def _free(self):
# def _cleanup(self, a_vars):
# def _generate_ts(self, a_data, a_get_w_emb_i, a_get_c_emb_i):
# def _rel2x(self, a_rel, a_parses, a_get_w_emb_i, a_get_c_emb_i):
# def _arg2emb_idx(self, a_parses, a_rel, a_arg, a_get_emb_i):
# def _init_w_emb(self):
# def _init_w2v_emb(self):
# def _init_w2emb(self):
# def _get_train_w_emb_i(self, a_word):
# def _get_test_w_emb_i(self, a_word):
# def _get_train_w2v_emb_i(self, a_word):
# def _get_test_w2v_emb_i(self, a_word):
# def _get_test_w2v_lstsq_emb_i(self, a_word):
# def _init_conn_emb(self):
# def get_train_c_emb_i(self, a_conn):
# def get_test_c_emb_i(self, a_conn):
# def _init_dropout(self, a_input):
# def _init_funcs(self, a_grads=None):
# def _init_wemb_funcs(self):
# def _reset_funcs(self):
# def _compute_w_stat(self, a_parses):
# class NNBaseSenser(BaseSenser):
#
# Path: dsenser/constants.py
# CONNECTIVE = "Connective"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# RAW_TEXT = "RawText"
. Output only the next line. | b = _norm_vec(a) |
Continue the code snippet: <|code_start|> "RawText": "to restrict the RTC to Treasury"
" borrowings only",
"TokenList": [[517, 519, 85, 2, 3], [520, 528, 86, 2, 4],
[529, 532, 87, 2, 5], [533, 536, 88, 2, 6],
[537, 539, 89, 2, 7], [540, 548, 90, 2, 8],
[549, 559, 91, 2, 9], [560, 564, 92, 2, 10]]},
"Arg2": {"CharacterSpanList": [[573, 629]], "RawText": "the agency"
" receives specific congressional authorization",
"TokenList": [[573, 576, 95, 2, 13], [577, 583, 96, 2, 14],
[584, 592, 97, 2, 15], [593, 601, 98, 2, 16],
[602, 615, 99, 2, 17], [616, 629, 100, 2, 18]]},
CONNECTIVE: {"CharacterSpanList": [[566, 572]], RAW_TEXT: "unless",
"TokenList": [[566, 572, 94, 2, 12]]},
"Sense": [], "Type": "", "ID": 35709}
VEC0 = np.array([0, 0, 0, 0])
VEC1 = np.array([0, 1, 2, 3])
VEC2 = np.array([4, 5, 6, 7])
VEC3 = np.array([8, 9, 10, 11])
##################################################################
# Test Methods
def test_norm_vec():
a = np.ones(10)
b = _norm_vec(a)
assert np.sqrt(np.sum(b**2)) == 1.
def test_norm_word():
<|code_end|>
. Use current file imports:
from dsenser.nnbase import _norm_vec, _norm_word, NNBaseSenser, DFLT_VDIM
from dsenser.constants import CONNECTIVE, WORDS, SENTENCES, RAW_TEXT
from pytest import fixture
from mock import patch, MagicMock, Mock
from unittest import TestCase
import dsenser
import dsenser.nnbase
import numpy as np
import pytest
import theano
and context (classes, functions, or code) from other files:
# Path: dsenser/nnbase.py
# MAX = 1e10
# INF = float('inf')
# UNK_PROB = lambda: np.random.binomial(1, 0.05)
# DIG_RE = re.compile(r"^[\d.]*\d[\d.]*$")
# def _norm_vec(a_x):
# def _norm_word(a_word):
# def __init__(self, a_w2v=False, a_lstsq=False, a_max_iters=MAX_ITERS):
# def train(self, a_train_data, a_dev_data=None, a_n_y=-1,
# a_i=-1, a_train_out=None, a_dev_out=None):
# def _init_nn(self):
# def predict(self, a_rel, a_data, a_ret, a_i):
# def _predict(self, a_args, a_ret, a_i):
# def _free(self):
# def _cleanup(self, a_vars):
# def _generate_ts(self, a_data, a_get_w_emb_i, a_get_c_emb_i):
# def _rel2x(self, a_rel, a_parses, a_get_w_emb_i, a_get_c_emb_i):
# def _arg2emb_idx(self, a_parses, a_rel, a_arg, a_get_emb_i):
# def _init_w_emb(self):
# def _init_w2v_emb(self):
# def _init_w2emb(self):
# def _get_train_w_emb_i(self, a_word):
# def _get_test_w_emb_i(self, a_word):
# def _get_train_w2v_emb_i(self, a_word):
# def _get_test_w2v_emb_i(self, a_word):
# def _get_test_w2v_lstsq_emb_i(self, a_word):
# def _init_conn_emb(self):
# def get_train_c_emb_i(self, a_conn):
# def get_test_c_emb_i(self, a_conn):
# def _init_dropout(self, a_input):
# def _init_funcs(self, a_grads=None):
# def _init_wemb_funcs(self):
# def _reset_funcs(self):
# def _compute_w_stat(self, a_parses):
# class NNBaseSenser(BaseSenser):
#
# Path: dsenser/constants.py
# CONNECTIVE = "Connective"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# RAW_TEXT = "RawText"
. Output only the next line. | assert _norm_word("124345") == "1" |
Given the code snippet: <|code_start|> "Arg2": {"CharacterSpanList": [[573, 629]], "RawText": "the agency"
" receives specific congressional authorization",
"TokenList": [[573, 576, 95, 2, 13], [577, 583, 96, 2, 14],
[584, 592, 97, 2, 15], [593, 601, 98, 2, 16],
[602, 615, 99, 2, 17], [616, 629, 100, 2, 18]]},
CONNECTIVE: {"CharacterSpanList": [[566, 572]], RAW_TEXT: "unless",
"TokenList": [[566, 572, 94, 2, 12]]},
"Sense": [], "Type": "", "ID": 35709}
VEC0 = np.array([0, 0, 0, 0])
VEC1 = np.array([0, 1, 2, 3])
VEC2 = np.array([4, 5, 6, 7])
VEC3 = np.array([8, 9, 10, 11])
##################################################################
# Test Methods
def test_norm_vec():
a = np.ones(10)
b = _norm_vec(a)
assert np.sqrt(np.sum(b**2)) == 1.
def test_norm_word():
assert _norm_word("124345") == "1"
assert _norm_word("ABCDEF") == "abcdef"
##################################################################
# Test Classes
<|code_end|>
, generate the next line using the imports in this file:
from dsenser.nnbase import _norm_vec, _norm_word, NNBaseSenser, DFLT_VDIM
from dsenser.constants import CONNECTIVE, WORDS, SENTENCES, RAW_TEXT
from pytest import fixture
from mock import patch, MagicMock, Mock
from unittest import TestCase
import dsenser
import dsenser.nnbase
import numpy as np
import pytest
import theano
and context (functions, classes, or occasionally code) from other files:
# Path: dsenser/nnbase.py
# MAX = 1e10
# INF = float('inf')
# UNK_PROB = lambda: np.random.binomial(1, 0.05)
# DIG_RE = re.compile(r"^[\d.]*\d[\d.]*$")
# def _norm_vec(a_x):
# def _norm_word(a_word):
# def __init__(self, a_w2v=False, a_lstsq=False, a_max_iters=MAX_ITERS):
# def train(self, a_train_data, a_dev_data=None, a_n_y=-1,
# a_i=-1, a_train_out=None, a_dev_out=None):
# def _init_nn(self):
# def predict(self, a_rel, a_data, a_ret, a_i):
# def _predict(self, a_args, a_ret, a_i):
# def _free(self):
# def _cleanup(self, a_vars):
# def _generate_ts(self, a_data, a_get_w_emb_i, a_get_c_emb_i):
# def _rel2x(self, a_rel, a_parses, a_get_w_emb_i, a_get_c_emb_i):
# def _arg2emb_idx(self, a_parses, a_rel, a_arg, a_get_emb_i):
# def _init_w_emb(self):
# def _init_w2v_emb(self):
# def _init_w2emb(self):
# def _get_train_w_emb_i(self, a_word):
# def _get_test_w_emb_i(self, a_word):
# def _get_train_w2v_emb_i(self, a_word):
# def _get_test_w2v_emb_i(self, a_word):
# def _get_test_w2v_lstsq_emb_i(self, a_word):
# def _init_conn_emb(self):
# def get_train_c_emb_i(self, a_conn):
# def get_test_c_emb_i(self, a_conn):
# def _init_dropout(self, a_input):
# def _init_funcs(self, a_grads=None):
# def _init_wemb_funcs(self):
# def _reset_funcs(self):
# def _compute_w_stat(self, a_parses):
# class NNBaseSenser(BaseSenser):
#
# Path: dsenser/constants.py
# CONNECTIVE = "Connective"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# RAW_TEXT = "RawText"
. Output only the next line. | class NNBase(NNBaseSenser): |
Predict the next line after this snippet: <|code_start|> w2v=word2vec, _trained=True,
_predict_func_emb=fmock):
self.nnbs._init_wemb_funcs()
assert word2vec.load.called
assert self.nnbs.ndim == word2vec.ndim
assert self.nnbs.get_train_w_emb_i == \
self.nnbs._get_train_w2v_emb_i
assert self.nnbs.get_test_w_emb_i == \
self.nnbs._get_test_w2v_emb_i
assert self.nnbs._predict_func == fmock
def test_init_wemb_funcs_1(self):
word2vec = Mock()
with patch.multiple(self.nnbs, _plain_w2v=True, w2v=None,
_trained=False):
with patch.object(dsenser.nnbase, "Word2Vec", word2vec):
self.nnbs._init_wemb_funcs()
assert self.nnbs.get_test_w_emb_i == \
self.nnbs._get_train_w2v_emb_i
def test_init_wemb_funcs_2(self):
word2vec = Mock()
word2vec.load = MagicMock()
word2vec.ndim = 2
fmock = MagicMock()
with patch.multiple(self.nnbs, _plain_w2v=False, lstsq=True,
ndim=8, w2v=None, _trained=True,
_predict_func_emb=fmock):
with patch.object(dsenser.nnbase, "Word2Vec", word2vec):
self.nnbs._init_wemb_funcs()
<|code_end|>
using the current file's imports:
from dsenser.nnbase import _norm_vec, _norm_word, NNBaseSenser, DFLT_VDIM
from dsenser.constants import CONNECTIVE, WORDS, SENTENCES, RAW_TEXT
from pytest import fixture
from mock import patch, MagicMock, Mock
from unittest import TestCase
import dsenser
import dsenser.nnbase
import numpy as np
import pytest
import theano
and any relevant context from other files:
# Path: dsenser/nnbase.py
# MAX = 1e10
# INF = float('inf')
# UNK_PROB = lambda: np.random.binomial(1, 0.05)
# DIG_RE = re.compile(r"^[\d.]*\d[\d.]*$")
# def _norm_vec(a_x):
# def _norm_word(a_word):
# def __init__(self, a_w2v=False, a_lstsq=False, a_max_iters=MAX_ITERS):
# def train(self, a_train_data, a_dev_data=None, a_n_y=-1,
# a_i=-1, a_train_out=None, a_dev_out=None):
# def _init_nn(self):
# def predict(self, a_rel, a_data, a_ret, a_i):
# def _predict(self, a_args, a_ret, a_i):
# def _free(self):
# def _cleanup(self, a_vars):
# def _generate_ts(self, a_data, a_get_w_emb_i, a_get_c_emb_i):
# def _rel2x(self, a_rel, a_parses, a_get_w_emb_i, a_get_c_emb_i):
# def _arg2emb_idx(self, a_parses, a_rel, a_arg, a_get_emb_i):
# def _init_w_emb(self):
# def _init_w2v_emb(self):
# def _init_w2emb(self):
# def _get_train_w_emb_i(self, a_word):
# def _get_test_w_emb_i(self, a_word):
# def _get_train_w2v_emb_i(self, a_word):
# def _get_test_w2v_emb_i(self, a_word):
# def _get_test_w2v_lstsq_emb_i(self, a_word):
# def _init_conn_emb(self):
# def get_train_c_emb_i(self, a_conn):
# def get_test_c_emb_i(self, a_conn):
# def _init_dropout(self, a_input):
# def _init_funcs(self, a_grads=None):
# def _init_wemb_funcs(self):
# def _reset_funcs(self):
# def _compute_w_stat(self, a_parses):
# class NNBaseSenser(BaseSenser):
#
# Path: dsenser/constants.py
# CONNECTIVE = "Connective"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# RAW_TEXT = "RawText"
. Output only the next line. | assert self.nnbs.ndim == DFLT_VDIM |
Given snippet: <|code_start|> ["restrict", {"PartOfSpeech": "VB"}],
["the", {"PartOfSpeech": "DT"}],
["RTC", {"PartOfSpeech": "NNP"}],
["to", {"PartOfSpeech": "TO"}],
["Treasury", {"PartOfSpeech": "NNP"}],
["borrowings", {"PartOfSpeech": "NNS"}],
["only", {"PartOfSpeech": "RB"}],
[",", {"PartOfSpeech": ","}],
["unless", {"PartOfSpeech": "IN"}],
["the", {"PartOfSpeech": "DT"}],
["agency", {"PartOfSpeech": "NN"}],
["receives", {"PartOfSpeech": "VBZ"}],
["specific", {"PartOfSpeech": "JJ"}],
["congressional", {"PartOfSpeech": "JJ"}],
["authorization", {"PartOfSpeech": "NN"}],
[".", {"PartOfSpeech": "."}]]}]}}
REL1 = {"DocID": "wsj_2200",
"Arg1": {"CharacterSpanList": [[517, 564]],
"RawText": "to restrict the RTC to Treasury"
" borrowings only",
"TokenList": [[517, 519, 85, 2, 3], [520, 528, 86, 2, 4],
[529, 532, 87, 2, 5], [533, 536, 88, 2, 6],
[537, 539, 89, 2, 7], [540, 548, 90, 2, 8],
[549, 559, 91, 2, 9], [560, 564, 92, 2, 10]]},
"Arg2": {"CharacterSpanList": [[573, 629]], "RawText": "the agency"
" receives specific congressional authorization",
"TokenList": [[573, 576, 95, 2, 13], [577, 583, 96, 2, 14],
[584, 592, 97, 2, 15], [593, 601, 98, 2, 16],
[602, 615, 99, 2, 17], [616, 629, 100, 2, 18]]},
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from dsenser.nnbase import _norm_vec, _norm_word, NNBaseSenser, DFLT_VDIM
from dsenser.constants import CONNECTIVE, WORDS, SENTENCES, RAW_TEXT
from pytest import fixture
from mock import patch, MagicMock, Mock
from unittest import TestCase
import dsenser
import dsenser.nnbase
import numpy as np
import pytest
import theano
and context:
# Path: dsenser/nnbase.py
# MAX = 1e10
# INF = float('inf')
# UNK_PROB = lambda: np.random.binomial(1, 0.05)
# DIG_RE = re.compile(r"^[\d.]*\d[\d.]*$")
# def _norm_vec(a_x):
# def _norm_word(a_word):
# def __init__(self, a_w2v=False, a_lstsq=False, a_max_iters=MAX_ITERS):
# def train(self, a_train_data, a_dev_data=None, a_n_y=-1,
# a_i=-1, a_train_out=None, a_dev_out=None):
# def _init_nn(self):
# def predict(self, a_rel, a_data, a_ret, a_i):
# def _predict(self, a_args, a_ret, a_i):
# def _free(self):
# def _cleanup(self, a_vars):
# def _generate_ts(self, a_data, a_get_w_emb_i, a_get_c_emb_i):
# def _rel2x(self, a_rel, a_parses, a_get_w_emb_i, a_get_c_emb_i):
# def _arg2emb_idx(self, a_parses, a_rel, a_arg, a_get_emb_i):
# def _init_w_emb(self):
# def _init_w2v_emb(self):
# def _init_w2emb(self):
# def _get_train_w_emb_i(self, a_word):
# def _get_test_w_emb_i(self, a_word):
# def _get_train_w2v_emb_i(self, a_word):
# def _get_test_w2v_emb_i(self, a_word):
# def _get_test_w2v_lstsq_emb_i(self, a_word):
# def _init_conn_emb(self):
# def get_train_c_emb_i(self, a_conn):
# def get_test_c_emb_i(self, a_conn):
# def _init_dropout(self, a_input):
# def _init_funcs(self, a_grads=None):
# def _init_wemb_funcs(self):
# def _reset_funcs(self):
# def _compute_w_stat(self, a_parses):
# class NNBaseSenser(BaseSenser):
#
# Path: dsenser/constants.py
# CONNECTIVE = "Connective"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# RAW_TEXT = "RawText"
which might include code, classes, or functions. Output only the next line. | CONNECTIVE: {"CharacterSpanList": [[566, 572]], RAW_TEXT: "unless", |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import
##################################################################
# Constants
DOC_ID = "wsj_2200"
PARSE1 = {DOC_ID: {
<|code_end|>
with the help of current file imports:
from dsenser.nnbase import _norm_vec, _norm_word, NNBaseSenser, DFLT_VDIM
from dsenser.constants import CONNECTIVE, WORDS, SENTENCES, RAW_TEXT
from pytest import fixture
from mock import patch, MagicMock, Mock
from unittest import TestCase
import dsenser
import dsenser.nnbase
import numpy as np
import pytest
import theano
and context from other files:
# Path: dsenser/nnbase.py
# MAX = 1e10
# INF = float('inf')
# UNK_PROB = lambda: np.random.binomial(1, 0.05)
# DIG_RE = re.compile(r"^[\d.]*\d[\d.]*$")
# def _norm_vec(a_x):
# def _norm_word(a_word):
# def __init__(self, a_w2v=False, a_lstsq=False, a_max_iters=MAX_ITERS):
# def train(self, a_train_data, a_dev_data=None, a_n_y=-1,
# a_i=-1, a_train_out=None, a_dev_out=None):
# def _init_nn(self):
# def predict(self, a_rel, a_data, a_ret, a_i):
# def _predict(self, a_args, a_ret, a_i):
# def _free(self):
# def _cleanup(self, a_vars):
# def _generate_ts(self, a_data, a_get_w_emb_i, a_get_c_emb_i):
# def _rel2x(self, a_rel, a_parses, a_get_w_emb_i, a_get_c_emb_i):
# def _arg2emb_idx(self, a_parses, a_rel, a_arg, a_get_emb_i):
# def _init_w_emb(self):
# def _init_w2v_emb(self):
# def _init_w2emb(self):
# def _get_train_w_emb_i(self, a_word):
# def _get_test_w_emb_i(self, a_word):
# def _get_train_w2v_emb_i(self, a_word):
# def _get_test_w2v_emb_i(self, a_word):
# def _get_test_w2v_lstsq_emb_i(self, a_word):
# def _init_conn_emb(self):
# def get_train_c_emb_i(self, a_conn):
# def get_test_c_emb_i(self, a_conn):
# def _init_dropout(self, a_input):
# def _init_funcs(self, a_grads=None):
# def _init_wemb_funcs(self):
# def _reset_funcs(self):
# def _compute_w_stat(self, a_parses):
# class NNBaseSenser(BaseSenser):
#
# Path: dsenser/constants.py
# CONNECTIVE = "Connective"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# RAW_TEXT = "RawText"
, which may contain function names, class names, or code. Output only the next line. | SENTENCES: [{WORDS: []}, {WORDS: []}, |
Given snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import
##################################################################
# Constants
DOC_ID = "wsj_2200"
PARSE1 = {DOC_ID: {
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from dsenser.nnbase import _norm_vec, _norm_word, NNBaseSenser, DFLT_VDIM
from dsenser.constants import CONNECTIVE, WORDS, SENTENCES, RAW_TEXT
from pytest import fixture
from mock import patch, MagicMock, Mock
from unittest import TestCase
import dsenser
import dsenser.nnbase
import numpy as np
import pytest
import theano
and context:
# Path: dsenser/nnbase.py
# MAX = 1e10
# INF = float('inf')
# UNK_PROB = lambda: np.random.binomial(1, 0.05)
# DIG_RE = re.compile(r"^[\d.]*\d[\d.]*$")
# def _norm_vec(a_x):
# def _norm_word(a_word):
# def __init__(self, a_w2v=False, a_lstsq=False, a_max_iters=MAX_ITERS):
# def train(self, a_train_data, a_dev_data=None, a_n_y=-1,
# a_i=-1, a_train_out=None, a_dev_out=None):
# def _init_nn(self):
# def predict(self, a_rel, a_data, a_ret, a_i):
# def _predict(self, a_args, a_ret, a_i):
# def _free(self):
# def _cleanup(self, a_vars):
# def _generate_ts(self, a_data, a_get_w_emb_i, a_get_c_emb_i):
# def _rel2x(self, a_rel, a_parses, a_get_w_emb_i, a_get_c_emb_i):
# def _arg2emb_idx(self, a_parses, a_rel, a_arg, a_get_emb_i):
# def _init_w_emb(self):
# def _init_w2v_emb(self):
# def _init_w2emb(self):
# def _get_train_w_emb_i(self, a_word):
# def _get_test_w_emb_i(self, a_word):
# def _get_train_w2v_emb_i(self, a_word):
# def _get_test_w2v_emb_i(self, a_word):
# def _get_test_w2v_lstsq_emb_i(self, a_word):
# def _init_conn_emb(self):
# def get_train_c_emb_i(self, a_conn):
# def get_test_c_emb_i(self, a_conn):
# def _init_dropout(self, a_input):
# def _init_funcs(self, a_grads=None):
# def _init_wemb_funcs(self):
# def _reset_funcs(self):
# def _compute_w_stat(self, a_parses):
# class NNBaseSenser(BaseSenser):
#
# Path: dsenser/constants.py
# CONNECTIVE = "Connective"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# RAW_TEXT = "RawText"
which might include code, classes, or functions. Output only the next line. | SENTENCES: [{WORDS: []}, {WORDS: []}, |
Using the snippet: <|code_start|> ["restrict", {"PartOfSpeech": "VB"}],
["the", {"PartOfSpeech": "DT"}],
["RTC", {"PartOfSpeech": "NNP"}],
["to", {"PartOfSpeech": "TO"}],
["Treasury", {"PartOfSpeech": "NNP"}],
["borrowings", {"PartOfSpeech": "NNS"}],
["only", {"PartOfSpeech": "RB"}],
[",", {"PartOfSpeech": ","}],
["unless", {"PartOfSpeech": "IN"}],
["the", {"PartOfSpeech": "DT"}],
["agency", {"PartOfSpeech": "NN"}],
["receives", {"PartOfSpeech": "VBZ"}],
["specific", {"PartOfSpeech": "JJ"}],
["congressional", {"PartOfSpeech": "JJ"}],
["authorization", {"PartOfSpeech": "NN"}],
[".", {"PartOfSpeech": "."}]]}]}}
REL1 = {"DocID": "wsj_2200",
"Arg1": {"CharacterSpanList": [[517, 564]],
"RawText": "to restrict the RTC to Treasury"
" borrowings only",
"TokenList": [[517, 519, 85, 2, 3], [520, 528, 86, 2, 4],
[529, 532, 87, 2, 5], [533, 536, 88, 2, 6],
[537, 539, 89, 2, 7], [540, 548, 90, 2, 8],
[549, 559, 91, 2, 9], [560, 564, 92, 2, 10]]},
"Arg2": {"CharacterSpanList": [[573, 629]], "RawText": "the agency"
" receives specific congressional authorization",
"TokenList": [[573, 576, 95, 2, 13], [577, 583, 96, 2, 14],
[584, 592, 97, 2, 15], [593, 601, 98, 2, 16],
[602, 615, 99, 2, 17], [616, 629, 100, 2, 18]]},
<|code_end|>
, determine the next line of code. You have imports:
from dsenser.nnbase import _norm_vec, _norm_word, NNBaseSenser, DFLT_VDIM
from dsenser.constants import CONNECTIVE, WORDS, SENTENCES, RAW_TEXT
from pytest import fixture
from mock import patch, MagicMock, Mock
from unittest import TestCase
import dsenser
import dsenser.nnbase
import numpy as np
import pytest
import theano
and context (class names, function names, or code) available:
# Path: dsenser/nnbase.py
# MAX = 1e10
# INF = float('inf')
# UNK_PROB = lambda: np.random.binomial(1, 0.05)
# DIG_RE = re.compile(r"^[\d.]*\d[\d.]*$")
# def _norm_vec(a_x):
# def _norm_word(a_word):
# def __init__(self, a_w2v=False, a_lstsq=False, a_max_iters=MAX_ITERS):
# def train(self, a_train_data, a_dev_data=None, a_n_y=-1,
# a_i=-1, a_train_out=None, a_dev_out=None):
# def _init_nn(self):
# def predict(self, a_rel, a_data, a_ret, a_i):
# def _predict(self, a_args, a_ret, a_i):
# def _free(self):
# def _cleanup(self, a_vars):
# def _generate_ts(self, a_data, a_get_w_emb_i, a_get_c_emb_i):
# def _rel2x(self, a_rel, a_parses, a_get_w_emb_i, a_get_c_emb_i):
# def _arg2emb_idx(self, a_parses, a_rel, a_arg, a_get_emb_i):
# def _init_w_emb(self):
# def _init_w2v_emb(self):
# def _init_w2emb(self):
# def _get_train_w_emb_i(self, a_word):
# def _get_test_w_emb_i(self, a_word):
# def _get_train_w2v_emb_i(self, a_word):
# def _get_test_w2v_emb_i(self, a_word):
# def _get_test_w2v_lstsq_emb_i(self, a_word):
# def _init_conn_emb(self):
# def get_train_c_emb_i(self, a_conn):
# def get_test_c_emb_i(self, a_conn):
# def _init_dropout(self, a_input):
# def _init_funcs(self, a_grads=None):
# def _init_wemb_funcs(self):
# def _reset_funcs(self):
# def _compute_w_stat(self, a_parses):
# class NNBaseSenser(BaseSenser):
#
# Path: dsenser/constants.py
# CONNECTIVE = "Connective"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# RAW_TEXT = "RawText"
. Output only the next line. | CONNECTIVE: {"CharacterSpanList": [[566, 572]], RAW_TEXT: "unless", |
Here is a snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import, unicode_literals, print_function
##################################################################
# Constants
##################################################################
# Test Classes
class TestSVDBaseSenser(TestCase):
@fixture(autouse=True)
def set_svd(self):
with patch.object(dsenser.nnbase, "Word2Vec",
MagicMock(ndim=300)):
<|code_end|>
. Write the next line using the current file imports:
from dsenser.svd.svdbase import SVDBaseSenser, MIN_DIM
from dsenser.theano_utils import HE_UNIFORM, TT, floatX
from mock import patch, MagicMock
from pytest import fixture
from unittest import TestCase
from theano.tensor.var import TensorVariable
import dsenser
import numpy as np
import theano
import sys
and context from other files:
# Path: dsenser/svd/svdbase.py
# class SVDBaseSenser(NNBaseSenser):
# """Abstract class for disambiguating relation senses.
#
# Attributes:
# n_y (int): number of distinct classes
#
# """
#
# def _init_nn(self):
# """Initialize neural network.
#
# """
# self.intm_dim = max(MIN_DIM, self.ndim - (self.ndim - self.n_y) / 2)
# # indices of word embeddings
# self.W_INDICES_ARG1 = TT.ivector(name="W_INDICES_ARG1")
# self.W_INDICES_ARG2 = TT.ivector(name="W_INDICES_ARG2")
# # connective's index
# self.CONN_INDEX = TT.iscalar(name="CONN_INDEX")
# # initialize the matrix of word embeddings
# self.init_w_emb()
# # word embeddings of the arguments
# self.EMB_ARG1 = self.W_EMB[self.W_INDICES_ARG1]
# self.EMB_ARG2 = self.W_EMB[self.W_INDICES_ARG2]
# # connective's embedding
# self._init_conn_emb()
# self.EMB_CONN = self.CONN_EMB[self.CONN_INDEX]
# # perform matrix decomposition
# _, _, self.ARG1 = TT.nlinalg.svd(self.EMB_ARG1,
# full_matrices=True)
# _, _, self.ARG2 = TT.nlinalg.svd(self.EMB_ARG2,
# full_matrices=True)
# self.ARG_DIFF = self.ARG1 - self.ARG2
# # map decomposed matrices to the intermediate level
# self.ARG_DIFF2I = theano.shared(value=HE_UNIFORM((self.ndim, 1)),
# name="ARG_DIFF2I")
# self.arg_diff_bias = theano.shared(value=HE_UNIFORM((1, self.ndim)),
# name="arg_diff_bias")
# self._params.extend([self.ARG_DIFF2I, self.arg_diff_bias])
# self.ARGS = (TT.dot(self.ARG_DIFF, self.ARG_DIFF2I).T +
# self.arg_diff_bias).flatten()
# # define final units
# self.I = TT.concatenate((self.ARGS, self.EMB_CONN))
# self.I2Y = theano.shared(value=HE_UNIFORM((self.n_y,
# self.ndim + self.intm_dim)),
# name="I2Y")
# self.y_bias = theano.shared(value=HE_UNIFORM((1, self.n_y)),
# name="y_bias")
# self._params.extend([self.I2Y, self.y_bias])
# self.Y_pred = TT.nnet.softmax(TT.dot(self.I2Y, self.I).T + self.y_bias)
# # initialize cost and optimization functions
# self.Y_gold = TT.vector(name="Y_gold")
# self._cost = TT.sum((self.Y_pred - self.Y_gold) ** 2)
# self._dev_cost = TT.sum((self.Y_pred - self.Y_gold) ** 2)
# self._pred_class = TT.argmax(self.Y_pred)
# grads = TT.grad(self._cost, wrt=self._params)
# self._init_funcs(grads)
#
# MIN_DIM = 50
#
# Path: dsenser/theano_utils.py
# def floatX(a_data, a_dtype=config.floatX):
# def rmsprop(tparams, grads, x, y, cost):
# MAX_ITERS = 150 # 450
# CONV_EPS = 1e-5
# DFLT_VDIM = 100
# _HE_NORMAL = HeNormal()
# HE_NORMAL = lambda x: floatX(_HE_NORMAL.sample(x))
# _HE_UNIFORM = HeUniform()
# HE_UNIFORM = lambda x: floatX(_HE_UNIFORM.sample(x))
# _HE_UNIFORM_RELU = HeUniform(gain=np.sqrt(2))
# HE_UNIFORM_RELU = lambda x: floatX(_HE_UNIFORM_RELU.sample(x))
# _RELU_ALPHA = 0.
# _HE_UNIFORM_LEAKY_RELU = HeUniform(
# gain=np.sqrt(2. / (1 + (_RELU_ALPHA or 1e-6)**2)))
# HE_UNIFORM_LEAKY_RELU = lambda x: \
# floatX(_HE_UNIFORM_LEAKY_RELU.sample(x))
# _ORTHOGONAL = Orthogonal()
# ORTHOGONAL = lambda x: floatX(_ORTHOGONAL.sample(x))
# TRNG = RandomStreams()
, which may include functions, classes, or code. Output only the next line. | self.svd = SVDBaseSenser(a_w2v=True) |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import, unicode_literals, print_function
##################################################################
# Constants
##################################################################
# Test Classes
class TestSVDBaseSenser(TestCase):
@fixture(autouse=True)
def set_svd(self):
with patch.object(dsenser.nnbase, "Word2Vec",
MagicMock(ndim=300)):
self.svd = SVDBaseSenser(a_w2v=True)
self.svd.w_i = 50
self.svd.n_y = 20
self.svd._init_nn()
def test_svd_0(self):
# check that the variables are of the right size
<|code_end|>
, predict the next line using imports from the current file:
from dsenser.svd.svdbase import SVDBaseSenser, MIN_DIM
from dsenser.theano_utils import HE_UNIFORM, TT, floatX
from mock import patch, MagicMock
from pytest import fixture
from unittest import TestCase
from theano.tensor.var import TensorVariable
import dsenser
import numpy as np
import theano
import sys
and context including class names, function names, and sometimes code from other files:
# Path: dsenser/svd/svdbase.py
# class SVDBaseSenser(NNBaseSenser):
# """Abstract class for disambiguating relation senses.
#
# Attributes:
# n_y (int): number of distinct classes
#
# """
#
# def _init_nn(self):
# """Initialize neural network.
#
# """
# self.intm_dim = max(MIN_DIM, self.ndim - (self.ndim - self.n_y) / 2)
# # indices of word embeddings
# self.W_INDICES_ARG1 = TT.ivector(name="W_INDICES_ARG1")
# self.W_INDICES_ARG2 = TT.ivector(name="W_INDICES_ARG2")
# # connective's index
# self.CONN_INDEX = TT.iscalar(name="CONN_INDEX")
# # initialize the matrix of word embeddings
# self.init_w_emb()
# # word embeddings of the arguments
# self.EMB_ARG1 = self.W_EMB[self.W_INDICES_ARG1]
# self.EMB_ARG2 = self.W_EMB[self.W_INDICES_ARG2]
# # connective's embedding
# self._init_conn_emb()
# self.EMB_CONN = self.CONN_EMB[self.CONN_INDEX]
# # perform matrix decomposition
# _, _, self.ARG1 = TT.nlinalg.svd(self.EMB_ARG1,
# full_matrices=True)
# _, _, self.ARG2 = TT.nlinalg.svd(self.EMB_ARG2,
# full_matrices=True)
# self.ARG_DIFF = self.ARG1 - self.ARG2
# # map decomposed matrices to the intermediate level
# self.ARG_DIFF2I = theano.shared(value=HE_UNIFORM((self.ndim, 1)),
# name="ARG_DIFF2I")
# self.arg_diff_bias = theano.shared(value=HE_UNIFORM((1, self.ndim)),
# name="arg_diff_bias")
# self._params.extend([self.ARG_DIFF2I, self.arg_diff_bias])
# self.ARGS = (TT.dot(self.ARG_DIFF, self.ARG_DIFF2I).T +
# self.arg_diff_bias).flatten()
# # define final units
# self.I = TT.concatenate((self.ARGS, self.EMB_CONN))
# self.I2Y = theano.shared(value=HE_UNIFORM((self.n_y,
# self.ndim + self.intm_dim)),
# name="I2Y")
# self.y_bias = theano.shared(value=HE_UNIFORM((1, self.n_y)),
# name="y_bias")
# self._params.extend([self.I2Y, self.y_bias])
# self.Y_pred = TT.nnet.softmax(TT.dot(self.I2Y, self.I).T + self.y_bias)
# # initialize cost and optimization functions
# self.Y_gold = TT.vector(name="Y_gold")
# self._cost = TT.sum((self.Y_pred - self.Y_gold) ** 2)
# self._dev_cost = TT.sum((self.Y_pred - self.Y_gold) ** 2)
# self._pred_class = TT.argmax(self.Y_pred)
# grads = TT.grad(self._cost, wrt=self._params)
# self._init_funcs(grads)
#
# MIN_DIM = 50
#
# Path: dsenser/theano_utils.py
# def floatX(a_data, a_dtype=config.floatX):
# def rmsprop(tparams, grads, x, y, cost):
# MAX_ITERS = 150 # 450
# CONV_EPS = 1e-5
# DFLT_VDIM = 100
# _HE_NORMAL = HeNormal()
# HE_NORMAL = lambda x: floatX(_HE_NORMAL.sample(x))
# _HE_UNIFORM = HeUniform()
# HE_UNIFORM = lambda x: floatX(_HE_UNIFORM.sample(x))
# _HE_UNIFORM_RELU = HeUniform(gain=np.sqrt(2))
# HE_UNIFORM_RELU = lambda x: floatX(_HE_UNIFORM_RELU.sample(x))
# _RELU_ALPHA = 0.
# _HE_UNIFORM_LEAKY_RELU = HeUniform(
# gain=np.sqrt(2. / (1 + (_RELU_ALPHA or 1e-6)**2)))
# HE_UNIFORM_LEAKY_RELU = lambda x: \
# floatX(_HE_UNIFORM_LEAKY_RELU.sample(x))
# _ORTHOGONAL = Orthogonal()
# ORTHOGONAL = lambda x: floatX(_ORTHOGONAL.sample(x))
# TRNG = RandomStreams()
. Output only the next line. | assert self.svd.intm_dim >= MIN_DIM |
Given the code snippet: <|code_start|>##################################################################
# Constants
##################################################################
# Test Classes
class TestSVDBaseSenser(TestCase):
@fixture(autouse=True)
def set_svd(self):
with patch.object(dsenser.nnbase, "Word2Vec",
MagicMock(ndim=300)):
self.svd = SVDBaseSenser(a_w2v=True)
self.svd.w_i = 50
self.svd.n_y = 20
self.svd._init_nn()
def test_svd_0(self):
# check that the variables are of the right size
assert self.svd.intm_dim >= MIN_DIM
assert isinstance(self.svd.W_INDICES_ARG1,
TensorVariable)
assert self.svd.W_INDICES_ARG1.type.ndim == 1
assert isinstance(self.svd.W_INDICES_ARG2,
TensorVariable)
assert self.svd.CONN_INDEX.type.ndim == 0
def test_svd_1(self):
# compile function that takes preliminary inout and outputs SVD
get_svd = theano.function([self.svd.EMB_ARG1], self.svd.ARG1,
name="get_svd")
<|code_end|>
, generate the next line using the imports in this file:
from dsenser.svd.svdbase import SVDBaseSenser, MIN_DIM
from dsenser.theano_utils import HE_UNIFORM, TT, floatX
from mock import patch, MagicMock
from pytest import fixture
from unittest import TestCase
from theano.tensor.var import TensorVariable
import dsenser
import numpy as np
import theano
import sys
and context (functions, classes, or occasionally code) from other files:
# Path: dsenser/svd/svdbase.py
# class SVDBaseSenser(NNBaseSenser):
# """Abstract class for disambiguating relation senses.
#
# Attributes:
# n_y (int): number of distinct classes
#
# """
#
# def _init_nn(self):
# """Initialize neural network.
#
# """
# self.intm_dim = max(MIN_DIM, self.ndim - (self.ndim - self.n_y) / 2)
# # indices of word embeddings
# self.W_INDICES_ARG1 = TT.ivector(name="W_INDICES_ARG1")
# self.W_INDICES_ARG2 = TT.ivector(name="W_INDICES_ARG2")
# # connective's index
# self.CONN_INDEX = TT.iscalar(name="CONN_INDEX")
# # initialize the matrix of word embeddings
# self.init_w_emb()
# # word embeddings of the arguments
# self.EMB_ARG1 = self.W_EMB[self.W_INDICES_ARG1]
# self.EMB_ARG2 = self.W_EMB[self.W_INDICES_ARG2]
# # connective's embedding
# self._init_conn_emb()
# self.EMB_CONN = self.CONN_EMB[self.CONN_INDEX]
# # perform matrix decomposition
# _, _, self.ARG1 = TT.nlinalg.svd(self.EMB_ARG1,
# full_matrices=True)
# _, _, self.ARG2 = TT.nlinalg.svd(self.EMB_ARG2,
# full_matrices=True)
# self.ARG_DIFF = self.ARG1 - self.ARG2
# # map decomposed matrices to the intermediate level
# self.ARG_DIFF2I = theano.shared(value=HE_UNIFORM((self.ndim, 1)),
# name="ARG_DIFF2I")
# self.arg_diff_bias = theano.shared(value=HE_UNIFORM((1, self.ndim)),
# name="arg_diff_bias")
# self._params.extend([self.ARG_DIFF2I, self.arg_diff_bias])
# self.ARGS = (TT.dot(self.ARG_DIFF, self.ARG_DIFF2I).T +
# self.arg_diff_bias).flatten()
# # define final units
# self.I = TT.concatenate((self.ARGS, self.EMB_CONN))
# self.I2Y = theano.shared(value=HE_UNIFORM((self.n_y,
# self.ndim + self.intm_dim)),
# name="I2Y")
# self.y_bias = theano.shared(value=HE_UNIFORM((1, self.n_y)),
# name="y_bias")
# self._params.extend([self.I2Y, self.y_bias])
# self.Y_pred = TT.nnet.softmax(TT.dot(self.I2Y, self.I).T + self.y_bias)
# # initialize cost and optimization functions
# self.Y_gold = TT.vector(name="Y_gold")
# self._cost = TT.sum((self.Y_pred - self.Y_gold) ** 2)
# self._dev_cost = TT.sum((self.Y_pred - self.Y_gold) ** 2)
# self._pred_class = TT.argmax(self.Y_pred)
# grads = TT.grad(self._cost, wrt=self._params)
# self._init_funcs(grads)
#
# MIN_DIM = 50
#
# Path: dsenser/theano_utils.py
# def floatX(a_data, a_dtype=config.floatX):
# def rmsprop(tparams, grads, x, y, cost):
# MAX_ITERS = 150 # 450
# CONV_EPS = 1e-5
# DFLT_VDIM = 100
# _HE_NORMAL = HeNormal()
# HE_NORMAL = lambda x: floatX(_HE_NORMAL.sample(x))
# _HE_UNIFORM = HeUniform()
# HE_UNIFORM = lambda x: floatX(_HE_UNIFORM.sample(x))
# _HE_UNIFORM_RELU = HeUniform(gain=np.sqrt(2))
# HE_UNIFORM_RELU = lambda x: floatX(_HE_UNIFORM_RELU.sample(x))
# _RELU_ALPHA = 0.
# _HE_UNIFORM_LEAKY_RELU = HeUniform(
# gain=np.sqrt(2. / (1 + (_RELU_ALPHA or 1e-6)**2)))
# HE_UNIFORM_LEAKY_RELU = lambda x: \
# floatX(_HE_UNIFORM_LEAKY_RELU.sample(x))
# _ORTHOGONAL = Orthogonal()
# ORTHOGONAL = lambda x: floatX(_ORTHOGONAL.sample(x))
# TRNG = RandomStreams()
. Output only the next line. | ret = get_svd(floatX(np.random.randn(20, 30))) |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import
##################################################################
# Constants
##################################################################
# Test Classes
class TestLSTMExplict(TestCase):
def test_train(self):
with patch("dsenser.lstm.lstmbase.LSTMBaseSenser.train",
autospec=True):
<|code_end|>
, predict the next line using imports from the current file:
from dsenser.lstm.explicit import LSTMExplicitSenser
from mock import patch
from unittest import TestCase
import dsenser
and context including class names, function names, and sometimes code from other files:
# Path: dsenser/lstm/explicit.py
# class LSTMExplicitSenser(LSTMBaseSenser):
# """Class for LSTM disambiguation of explicit discourse relations.
#
# """
#
# @timeit("Training explicit LSTM classifier...")
# def train(self, *args, **kwargs):
# super(LSTMExplicitSenser, self).train(*args, **kwargs)
. Output only the next line. | lstm = LSTMExplicitSenser() |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import
##################################################################
# Constants
##################################################################
# Test Classes
class TestWangSenser(TestCase):
def test_init(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from unittest import TestCase
from dsenser.wang import WangSenser
and context (classes, functions, sometimes code) from other files:
# Path: dsenser/wang/wang.py
# class WangSenser(BaseSenser):
# """Class using Wang classification for disambiguating connectives.
#
# Attributes:
# explicit (:class:`dsenser.wang.explicit.WangExplicitSenser`):
# classifier for explicit discourse relations
# implicit (:class:`dsenser.wang.implicit.WangImplicitSenser`):
# classifier for implicit discourse relations
# n_y (int): number of distinct classes
#
# """
#
# def __init__(self, **kwargs):
# """Class constructor.
#
# Args:
# kwargs (dict): keyword arguments to be forwarded
#
# """
# explicit_clf = LinearSVC(C=DFLT_EXP_C, **DFLT_PARAMS)
# self.explicit = WangExplicitSenser(a_clf=explicit_clf, **kwargs)
# implicit_clf = LinearSVC(C=DFLT_IMP_C, **DFLT_PARAMS)
# self.implicit = WangImplicitSenser(a_clf=implicit_clf, **kwargs)
. Output only the next line. | wang = WangSenser() |
Using the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import
##################################################################
# Auxiliary Class
@singleton
class Aux(object):
m1 = 3
##################################################################
# Test Classes
def test_singleton():
a1 = Aux
a2 = Aux
assert a1.m1 == 3
assert a2.m1 == 3
assert a1 is a2
def test_is_explicit():
<|code_end|>
, determine the next line of code. You have imports:
from dsenser.constants import CONNECTIVE, TOK_LIST
from dsenser.utils import singleton, is_explicit
and context (class names, function names, or code) available:
# Path: dsenser/constants.py
# CONNECTIVE = "Connective"
#
# TOK_LIST = "TokenList"
#
# Path: dsenser/utils.py
# def singleton(cls):
# """Make `cls` instance unique across all calls.
#
# Args:
# cls (class):
# class to be decorated
#
# Retuns:
# object:
# singleton instance of the decorated class
#
# """
# instance = cls()
# instance.__call__ = lambda: instance
# return instance
#
# def is_explicit(a_rel):
# """Check whether given relation is explicit.
#
# Args:
# a_rel (dict):
# discourse relation to classify
#
# Returns:
# bool:
# ``True`` if the relation is explicit, ``False`` otherwise
#
# """
# return bool(a_rel[CONNECTIVE][TOK_LIST])
. Output only the next line. | assert is_explicit({CONNECTIVE: {TOK_LIST: [1, 2, 3]}}) |
Given snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import
##################################################################
# Auxiliary Class
@singleton
class Aux(object):
m1 = 3
##################################################################
# Test Classes
def test_singleton():
a1 = Aux
a2 = Aux
assert a1.m1 == 3
assert a2.m1 == 3
assert a1 is a2
def test_is_explicit():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from dsenser.constants import CONNECTIVE, TOK_LIST
from dsenser.utils import singleton, is_explicit
and context:
# Path: dsenser/constants.py
# CONNECTIVE = "Connective"
#
# TOK_LIST = "TokenList"
#
# Path: dsenser/utils.py
# def singleton(cls):
# """Make `cls` instance unique across all calls.
#
# Args:
# cls (class):
# class to be decorated
#
# Retuns:
# object:
# singleton instance of the decorated class
#
# """
# instance = cls()
# instance.__call__ = lambda: instance
# return instance
#
# def is_explicit(a_rel):
# """Check whether given relation is explicit.
#
# Args:
# a_rel (dict):
# discourse relation to classify
#
# Returns:
# bool:
# ``True`` if the relation is explicit, ``False`` otherwise
#
# """
# return bool(a_rel[CONNECTIVE][TOK_LIST])
which might include code, classes, or functions. Output only the next line. | assert is_explicit({CONNECTIVE: {TOK_LIST: [1, 2, 3]}}) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import
##################################################################
# Auxiliary Class
@singleton
class Aux(object):
m1 = 3
##################################################################
# Test Classes
def test_singleton():
a1 = Aux
a2 = Aux
assert a1.m1 == 3
assert a2.m1 == 3
assert a1 is a2
def test_is_explicit():
<|code_end|>
. Use current file imports:
from dsenser.constants import CONNECTIVE, TOK_LIST
from dsenser.utils import singleton, is_explicit
and context (classes, functions, or code) from other files:
# Path: dsenser/constants.py
# CONNECTIVE = "Connective"
#
# TOK_LIST = "TokenList"
#
# Path: dsenser/utils.py
# def singleton(cls):
# """Make `cls` instance unique across all calls.
#
# Args:
# cls (class):
# class to be decorated
#
# Retuns:
# object:
# singleton instance of the decorated class
#
# """
# instance = cls()
# instance.__call__ = lambda: instance
# return instance
#
# def is_explicit(a_rel):
# """Check whether given relation is explicit.
#
# Args:
# a_rel (dict):
# discourse relation to classify
#
# Returns:
# bool:
# ``True`` if the relation is explicit, ``False`` otherwise
#
# """
# return bool(a_rel[CONNECTIVE][TOK_LIST])
. Output only the next line. | assert is_explicit({CONNECTIVE: {TOK_LIST: [1, 2, 3]}}) |
Given snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
"""Module providing class for XGBoost sense disambiguation.
Attributes:
XGBoostSenser (class):
class for XGBoost sense classification of explicit and implicit relations
"""
##################################################################
# Imports
from __future__ import absolute_import, print_function, \
unicode_literals
##################################################################
# Constants
##################################################################
# Class
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from dsenser.wang import WangSenser
from dsenser.xgboost.explicit import XGBoostExplicitSenser
from dsenser.xgboost.implicit import XGBoostImplicitSenser
and context:
# Path: dsenser/wang/wang.py
# class WangSenser(BaseSenser):
# """Class using Wang classification for disambiguating connectives.
#
# Attributes:
# explicit (:class:`dsenser.wang.explicit.WangExplicitSenser`):
# classifier for explicit discourse relations
# implicit (:class:`dsenser.wang.implicit.WangImplicitSenser`):
# classifier for implicit discourse relations
# n_y (int): number of distinct classes
#
# """
#
# def __init__(self, **kwargs):
# """Class constructor.
#
# Args:
# kwargs (dict): keyword arguments to be forwarded
#
# """
# explicit_clf = LinearSVC(C=DFLT_EXP_C, **DFLT_PARAMS)
# self.explicit = WangExplicitSenser(a_clf=explicit_clf, **kwargs)
# implicit_clf = LinearSVC(C=DFLT_IMP_C, **DFLT_PARAMS)
# self.implicit = WangImplicitSenser(a_clf=implicit_clf, **kwargs)
#
# Path: dsenser/xgboost/explicit.py
# class XGBoostExplicitSenser(XGBoostBaseSenser, WangExplicitSenser):
# """Subclass of explicit WangSenser using XGBoost.
#
# """
# PARAM_GRID = BASE_PARAM_GRID
# N_JOBS = BASE_N_JOBS
#
# @timeit("Training explicit XGBoost classifier...")
# def train(self, *args, **kwargs):
# super(WangExplicitSenser, self).train(*args, **kwargs)
#
# Path: dsenser/xgboost/implicit.py
# class XGBoostImplicitSenser(XGBoostBaseSenser, WangImplicitSenser):
# """Subclass of implicit WangSenser using XGBoost.
#
# """
# PARAM_GRID = BASE_PARAM_GRID
# N_JOBS = BASE_N_JOBS
#
# @timeit("Training implicit XGBoost classifier...")
# def train(self, *args, **kwargs):
# super(WangImplicitSenser, self).train(*args, **kwargs)
which might include code, classes, or functions. Output only the next line. | class XGBoostSenser(WangSenser): |
Next line prediction: <|code_start|># Imports
from __future__ import absolute_import, print_function, \
unicode_literals
##################################################################
# Constants
##################################################################
# Class
class XGBoostSenser(WangSenser):
"""Class for XGBoost classification of discourse relations.
Attributes:
explicit (:class:`dsenser.xgboost.explicit.XGBoostExplicitSenser`):
classifier for explicit discourse relations
implicit (:class:`dsenser.xgboost.implicit.XGBoostImplicitSenser`):
classifier for implicit discourse relations
n_y (int): number of distinct classes
"""
def __init__(self, **kwargs):
"""Class constructor.
Args:
kwargs (dict): keyword arguments to be forwarded
"""
<|code_end|>
. Use current file imports:
(from dsenser.wang import WangSenser
from dsenser.xgboost.explicit import XGBoostExplicitSenser
from dsenser.xgboost.implicit import XGBoostImplicitSenser)
and context including class names, function names, or small code snippets from other files:
# Path: dsenser/wang/wang.py
# class WangSenser(BaseSenser):
# """Class using Wang classification for disambiguating connectives.
#
# Attributes:
# explicit (:class:`dsenser.wang.explicit.WangExplicitSenser`):
# classifier for explicit discourse relations
# implicit (:class:`dsenser.wang.implicit.WangImplicitSenser`):
# classifier for implicit discourse relations
# n_y (int): number of distinct classes
#
# """
#
# def __init__(self, **kwargs):
# """Class constructor.
#
# Args:
# kwargs (dict): keyword arguments to be forwarded
#
# """
# explicit_clf = LinearSVC(C=DFLT_EXP_C, **DFLT_PARAMS)
# self.explicit = WangExplicitSenser(a_clf=explicit_clf, **kwargs)
# implicit_clf = LinearSVC(C=DFLT_IMP_C, **DFLT_PARAMS)
# self.implicit = WangImplicitSenser(a_clf=implicit_clf, **kwargs)
#
# Path: dsenser/xgboost/explicit.py
# class XGBoostExplicitSenser(XGBoostBaseSenser, WangExplicitSenser):
# """Subclass of explicit WangSenser using XGBoost.
#
# """
# PARAM_GRID = BASE_PARAM_GRID
# N_JOBS = BASE_N_JOBS
#
# @timeit("Training explicit XGBoost classifier...")
# def train(self, *args, **kwargs):
# super(WangExplicitSenser, self).train(*args, **kwargs)
#
# Path: dsenser/xgboost/implicit.py
# class XGBoostImplicitSenser(XGBoostBaseSenser, WangImplicitSenser):
# """Subclass of implicit WangSenser using XGBoost.
#
# """
# PARAM_GRID = BASE_PARAM_GRID
# N_JOBS = BASE_N_JOBS
#
# @timeit("Training implicit XGBoost classifier...")
# def train(self, *args, **kwargs):
# super(WangImplicitSenser, self).train(*args, **kwargs)
. Output only the next line. | self.explicit = XGBoostExplicitSenser(**kwargs) |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import absolute_import, print_function, \
unicode_literals
##################################################################
# Constants
##################################################################
# Class
class XGBoostSenser(WangSenser):
"""Class for XGBoost classification of discourse relations.
Attributes:
explicit (:class:`dsenser.xgboost.explicit.XGBoostExplicitSenser`):
classifier for explicit discourse relations
implicit (:class:`dsenser.xgboost.implicit.XGBoostImplicitSenser`):
classifier for implicit discourse relations
n_y (int): number of distinct classes
"""
def __init__(self, **kwargs):
"""Class constructor.
Args:
kwargs (dict): keyword arguments to be forwarded
"""
self.explicit = XGBoostExplicitSenser(**kwargs)
<|code_end|>
, predict the next line using imports from the current file:
from dsenser.wang import WangSenser
from dsenser.xgboost.explicit import XGBoostExplicitSenser
from dsenser.xgboost.implicit import XGBoostImplicitSenser
and context including class names, function names, and sometimes code from other files:
# Path: dsenser/wang/wang.py
# class WangSenser(BaseSenser):
# """Class using Wang classification for disambiguating connectives.
#
# Attributes:
# explicit (:class:`dsenser.wang.explicit.WangExplicitSenser`):
# classifier for explicit discourse relations
# implicit (:class:`dsenser.wang.implicit.WangImplicitSenser`):
# classifier for implicit discourse relations
# n_y (int): number of distinct classes
#
# """
#
# def __init__(self, **kwargs):
# """Class constructor.
#
# Args:
# kwargs (dict): keyword arguments to be forwarded
#
# """
# explicit_clf = LinearSVC(C=DFLT_EXP_C, **DFLT_PARAMS)
# self.explicit = WangExplicitSenser(a_clf=explicit_clf, **kwargs)
# implicit_clf = LinearSVC(C=DFLT_IMP_C, **DFLT_PARAMS)
# self.implicit = WangImplicitSenser(a_clf=implicit_clf, **kwargs)
#
# Path: dsenser/xgboost/explicit.py
# class XGBoostExplicitSenser(XGBoostBaseSenser, WangExplicitSenser):
# """Subclass of explicit WangSenser using XGBoost.
#
# """
# PARAM_GRID = BASE_PARAM_GRID
# N_JOBS = BASE_N_JOBS
#
# @timeit("Training explicit XGBoost classifier...")
# def train(self, *args, **kwargs):
# super(WangExplicitSenser, self).train(*args, **kwargs)
#
# Path: dsenser/xgboost/implicit.py
# class XGBoostImplicitSenser(XGBoostBaseSenser, WangImplicitSenser):
# """Subclass of implicit WangSenser using XGBoost.
#
# """
# PARAM_GRID = BASE_PARAM_GRID
# N_JOBS = BASE_N_JOBS
#
# @timeit("Training implicit XGBoost classifier...")
# def train(self, *args, **kwargs):
# super(WangImplicitSenser, self).train(*args, **kwargs)
. Output only the next line. | self.implicit = XGBoostImplicitSenser(**kwargs) |
Here is a snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import
##################################################################
# Constants
ON_THE_CONTRARY = (("on", "the", "contrary"),)
NEITHER_NOT = (("neither", ), ("nor",))
EMPTY = ((), )
<|code_end|>
. Write the next line using the current file imports:
from conftest import TEST_BROWN_PATH
from dsenser.resources import LoadOnDemand, load_BROWN, CONNS, DFLT_W2V_PATH, \
INQUIRER, LCSI, MPQA, STEMMED_INQUIRER, W2V, conn2str
from unittest import TestCase
from mock import patch
import gensim
and context from other files:
# Path: dsenser/resources.py
# BAR_RE = re.compile(r'\|')
# CHM = ConnHeadMapper()
# ELLIPSIS_RE = re.compile(r"[.][.]+")
# EQ_RE = re.compile("=+")
# HASH_RE = re.compile("\s*#\s*")
# SPACE_RE = re.compile("\s+")
# TAB_RE = re.compile("\t+")
# PSTEMMER = PorterStemmer()
# WORD1 = "word1"
# POL = "priorpolarity"
# POL_IDX = 0
# INTENS = "type"
# INTENS_IDX = 1
# POS = "pos1"
# POS_IDX = 2
# NEGATIONS = set(["cannot", "not", "none", "nothing",
# "nowhere", "neither", "nor", "nobody",
# "hardly", "scarcely", "barely", "never",
# "n't", "noone", "havent", "hasnt",
# "hadnt", "cant", "couldnt", "shouldnt",
# "wont", "wouldnt", "dont", "doesnt",
# "didnt", "isnt", "arent", "aint", "no"
# ])
# LCSI = load_LCSI(DFLT_LCSI_PATH)
# BROWN_CLUSTERS = LoadOnDemand(load_BROWN, DFLT_BROWN_PATH)
# CONNS = load_conns(DFLT_ECONN_PATH)
# CONNTOK2CONN = defaultdict(list)
# CONNTOKS = set(CONNTOK2CONN.keys())
# INQUIRER, STEMMED_INQUIRER = load_INQUIRER(DFLT_INQUIRER_PATH)
# MPQA = load_MPQA(DFLT_MPQA_PATH)
# W2V = LoadOnDemand(load_W2V, DFLT_W2V_PATH)
# def load_conns(a_fname):
# def conn2str(a_conn):
# def load_LCSI(a_fname):
# def load_BROWN(a_fname):
# def load_INQUIRER(a_fname):
# def load_MPQA(a_fname):
# def load_W2V(a_fname):
# def __init__(self, a_cmd, *a_args, **a_kwargs):
# def __contains__(self, a_name):
# def __getitem__(self, a_name):
# def load(self):
# def unload(self):
# class LoadOnDemand(object):
, which may include functions, classes, or code. Output only the next line. | BROWN_CLUSTERS = LoadOnDemand(load_BROWN, TEST_BROWN_PATH) |
Given snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import
##################################################################
# Constants
ON_THE_CONTRARY = (("on", "the", "contrary"),)
NEITHER_NOT = (("neither", ), ("nor",))
EMPTY = ((), )
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from conftest import TEST_BROWN_PATH
from dsenser.resources import LoadOnDemand, load_BROWN, CONNS, DFLT_W2V_PATH, \
INQUIRER, LCSI, MPQA, STEMMED_INQUIRER, W2V, conn2str
from unittest import TestCase
from mock import patch
import gensim
and context:
# Path: dsenser/resources.py
# BAR_RE = re.compile(r'\|')
# CHM = ConnHeadMapper()
# ELLIPSIS_RE = re.compile(r"[.][.]+")
# EQ_RE = re.compile("=+")
# HASH_RE = re.compile("\s*#\s*")
# SPACE_RE = re.compile("\s+")
# TAB_RE = re.compile("\t+")
# PSTEMMER = PorterStemmer()
# WORD1 = "word1"
# POL = "priorpolarity"
# POL_IDX = 0
# INTENS = "type"
# INTENS_IDX = 1
# POS = "pos1"
# POS_IDX = 2
# NEGATIONS = set(["cannot", "not", "none", "nothing",
# "nowhere", "neither", "nor", "nobody",
# "hardly", "scarcely", "barely", "never",
# "n't", "noone", "havent", "hasnt",
# "hadnt", "cant", "couldnt", "shouldnt",
# "wont", "wouldnt", "dont", "doesnt",
# "didnt", "isnt", "arent", "aint", "no"
# ])
# LCSI = load_LCSI(DFLT_LCSI_PATH)
# BROWN_CLUSTERS = LoadOnDemand(load_BROWN, DFLT_BROWN_PATH)
# CONNS = load_conns(DFLT_ECONN_PATH)
# CONNTOK2CONN = defaultdict(list)
# CONNTOKS = set(CONNTOK2CONN.keys())
# INQUIRER, STEMMED_INQUIRER = load_INQUIRER(DFLT_INQUIRER_PATH)
# MPQA = load_MPQA(DFLT_MPQA_PATH)
# W2V = LoadOnDemand(load_W2V, DFLT_W2V_PATH)
# def load_conns(a_fname):
# def conn2str(a_conn):
# def load_LCSI(a_fname):
# def load_BROWN(a_fname):
# def load_INQUIRER(a_fname):
# def load_MPQA(a_fname):
# def load_W2V(a_fname):
# def __init__(self, a_cmd, *a_args, **a_kwargs):
# def __contains__(self, a_name):
# def __getitem__(self, a_name):
# def load(self):
# def unload(self):
# class LoadOnDemand(object):
which might include code, classes, or functions. Output only the next line. | BROWN_CLUSTERS = LoadOnDemand(load_BROWN, TEST_BROWN_PATH) |
Given snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import
##################################################################
# Constants
ON_THE_CONTRARY = (("on", "the", "contrary"),)
NEITHER_NOT = (("neither", ), ("nor",))
EMPTY = ((), )
BROWN_CLUSTERS = LoadOnDemand(load_BROWN, TEST_BROWN_PATH)
##################################################################
# Test Classes
class TestResources(TestCase):
def test_BROWN_CLUSTERS(self):
assert BROWN_CLUSTERS["jasper"] == "1100011110"
assert BROWN_CLUSTERS["un"] == "1100011110|1110110010|1011010110"
assert "" not in BROWN_CLUSTERS
def test_CONNS(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from conftest import TEST_BROWN_PATH
from dsenser.resources import LoadOnDemand, load_BROWN, CONNS, DFLT_W2V_PATH, \
INQUIRER, LCSI, MPQA, STEMMED_INQUIRER, W2V, conn2str
from unittest import TestCase
from mock import patch
import gensim
and context:
# Path: dsenser/resources.py
# BAR_RE = re.compile(r'\|')
# CHM = ConnHeadMapper()
# ELLIPSIS_RE = re.compile(r"[.][.]+")
# EQ_RE = re.compile("=+")
# HASH_RE = re.compile("\s*#\s*")
# SPACE_RE = re.compile("\s+")
# TAB_RE = re.compile("\t+")
# PSTEMMER = PorterStemmer()
# WORD1 = "word1"
# POL = "priorpolarity"
# POL_IDX = 0
# INTENS = "type"
# INTENS_IDX = 1
# POS = "pos1"
# POS_IDX = 2
# NEGATIONS = set(["cannot", "not", "none", "nothing",
# "nowhere", "neither", "nor", "nobody",
# "hardly", "scarcely", "barely", "never",
# "n't", "noone", "havent", "hasnt",
# "hadnt", "cant", "couldnt", "shouldnt",
# "wont", "wouldnt", "dont", "doesnt",
# "didnt", "isnt", "arent", "aint", "no"
# ])
# LCSI = load_LCSI(DFLT_LCSI_PATH)
# BROWN_CLUSTERS = LoadOnDemand(load_BROWN, DFLT_BROWN_PATH)
# CONNS = load_conns(DFLT_ECONN_PATH)
# CONNTOK2CONN = defaultdict(list)
# CONNTOKS = set(CONNTOK2CONN.keys())
# INQUIRER, STEMMED_INQUIRER = load_INQUIRER(DFLT_INQUIRER_PATH)
# MPQA = load_MPQA(DFLT_MPQA_PATH)
# W2V = LoadOnDemand(load_W2V, DFLT_W2V_PATH)
# def load_conns(a_fname):
# def conn2str(a_conn):
# def load_LCSI(a_fname):
# def load_BROWN(a_fname):
# def load_INQUIRER(a_fname):
# def load_MPQA(a_fname):
# def load_W2V(a_fname):
# def __init__(self, a_cmd, *a_args, **a_kwargs):
# def __contains__(self, a_name):
# def __getitem__(self, a_name):
# def load(self):
# def unload(self):
# class LoadOnDemand(object):
which might include code, classes, or functions. Output only the next line. | assert ON_THE_CONTRARY in CONNS |
Next line prediction: <|code_start|>
def test_INQUIRER(self):
assert "" not in INQUIRER
assert INQUIRER["won"] == [False, False, False, False, True,
False, True, False, False, False,
False, False, False, False, True,
False, False, False, False, False,
False, False, False, False, True,
False, False, False, False, False,
False, False, False, False, False,
False, False, False, False, False,
False, False, False, False, False]
assert INQUIRER["won"] == STEMMED_INQUIRER["won"]
def test_LCSI(self):
assert LCSI["unionize"] == set(["45.4.a", "45.4.b", "45.4.c"])
assert LCSI["confer"] == set(["37.6.a", "37.6.b"])
def test_MPQA(self):
assert MPQA["zealously"] == ("negative", "strongsubj", "anypos")
def test_conn2str(self):
assert conn2str(ON_THE_CONTRARY) == "on_the_contrary"
assert conn2str(NEITHER_NOT) == "neither_nor"
assert conn2str(EMPTY) == ""
def test_w2v(self):
with patch.object(gensim.models.word2vec.Word2Vec,
"load_word2vec_format") as mock_method:
W2V["zzz"]
<|code_end|>
. Use current file imports:
(from conftest import TEST_BROWN_PATH
from dsenser.resources import LoadOnDemand, load_BROWN, CONNS, DFLT_W2V_PATH, \
INQUIRER, LCSI, MPQA, STEMMED_INQUIRER, W2V, conn2str
from unittest import TestCase
from mock import patch
import gensim)
and context including class names, function names, or small code snippets from other files:
# Path: dsenser/resources.py
# BAR_RE = re.compile(r'\|')
# CHM = ConnHeadMapper()
# ELLIPSIS_RE = re.compile(r"[.][.]+")
# EQ_RE = re.compile("=+")
# HASH_RE = re.compile("\s*#\s*")
# SPACE_RE = re.compile("\s+")
# TAB_RE = re.compile("\t+")
# PSTEMMER = PorterStemmer()
# WORD1 = "word1"
# POL = "priorpolarity"
# POL_IDX = 0
# INTENS = "type"
# INTENS_IDX = 1
# POS = "pos1"
# POS_IDX = 2
# NEGATIONS = set(["cannot", "not", "none", "nothing",
# "nowhere", "neither", "nor", "nobody",
# "hardly", "scarcely", "barely", "never",
# "n't", "noone", "havent", "hasnt",
# "hadnt", "cant", "couldnt", "shouldnt",
# "wont", "wouldnt", "dont", "doesnt",
# "didnt", "isnt", "arent", "aint", "no"
# ])
# LCSI = load_LCSI(DFLT_LCSI_PATH)
# BROWN_CLUSTERS = LoadOnDemand(load_BROWN, DFLT_BROWN_PATH)
# CONNS = load_conns(DFLT_ECONN_PATH)
# CONNTOK2CONN = defaultdict(list)
# CONNTOKS = set(CONNTOK2CONN.keys())
# INQUIRER, STEMMED_INQUIRER = load_INQUIRER(DFLT_INQUIRER_PATH)
# MPQA = load_MPQA(DFLT_MPQA_PATH)
# W2V = LoadOnDemand(load_W2V, DFLT_W2V_PATH)
# def load_conns(a_fname):
# def conn2str(a_conn):
# def load_LCSI(a_fname):
# def load_BROWN(a_fname):
# def load_INQUIRER(a_fname):
# def load_MPQA(a_fname):
# def load_W2V(a_fname):
# def __init__(self, a_cmd, *a_args, **a_kwargs):
# def __contains__(self, a_name):
# def __getitem__(self, a_name):
# def load(self):
# def unload(self):
# class LoadOnDemand(object):
. Output only the next line. | mock_method.assert_any_call(DFLT_W2V_PATH, binary=True) |
Here is a snippet: <|code_start|>##################################################################
# Imports
from __future__ import absolute_import
##################################################################
# Constants
ON_THE_CONTRARY = (("on", "the", "contrary"),)
NEITHER_NOT = (("neither", ), ("nor",))
EMPTY = ((), )
BROWN_CLUSTERS = LoadOnDemand(load_BROWN, TEST_BROWN_PATH)
##################################################################
# Test Classes
class TestResources(TestCase):
def test_BROWN_CLUSTERS(self):
assert BROWN_CLUSTERS["jasper"] == "1100011110"
assert BROWN_CLUSTERS["un"] == "1100011110|1110110010|1011010110"
assert "" not in BROWN_CLUSTERS
def test_CONNS(self):
assert ON_THE_CONTRARY in CONNS
assert NEITHER_NOT in CONNS
assert EMPTY not in CONNS
def test_INQUIRER(self):
<|code_end|>
. Write the next line using the current file imports:
from conftest import TEST_BROWN_PATH
from dsenser.resources import LoadOnDemand, load_BROWN, CONNS, DFLT_W2V_PATH, \
INQUIRER, LCSI, MPQA, STEMMED_INQUIRER, W2V, conn2str
from unittest import TestCase
from mock import patch
import gensim
and context from other files:
# Path: dsenser/resources.py
# BAR_RE = re.compile(r'\|')
# CHM = ConnHeadMapper()
# ELLIPSIS_RE = re.compile(r"[.][.]+")
# EQ_RE = re.compile("=+")
# HASH_RE = re.compile("\s*#\s*")
# SPACE_RE = re.compile("\s+")
# TAB_RE = re.compile("\t+")
# PSTEMMER = PorterStemmer()
# WORD1 = "word1"
# POL = "priorpolarity"
# POL_IDX = 0
# INTENS = "type"
# INTENS_IDX = 1
# POS = "pos1"
# POS_IDX = 2
# NEGATIONS = set(["cannot", "not", "none", "nothing",
# "nowhere", "neither", "nor", "nobody",
# "hardly", "scarcely", "barely", "never",
# "n't", "noone", "havent", "hasnt",
# "hadnt", "cant", "couldnt", "shouldnt",
# "wont", "wouldnt", "dont", "doesnt",
# "didnt", "isnt", "arent", "aint", "no"
# ])
# LCSI = load_LCSI(DFLT_LCSI_PATH)
# BROWN_CLUSTERS = LoadOnDemand(load_BROWN, DFLT_BROWN_PATH)
# CONNS = load_conns(DFLT_ECONN_PATH)
# CONNTOK2CONN = defaultdict(list)
# CONNTOKS = set(CONNTOK2CONN.keys())
# INQUIRER, STEMMED_INQUIRER = load_INQUIRER(DFLT_INQUIRER_PATH)
# MPQA = load_MPQA(DFLT_MPQA_PATH)
# W2V = LoadOnDemand(load_W2V, DFLT_W2V_PATH)
# def load_conns(a_fname):
# def conn2str(a_conn):
# def load_LCSI(a_fname):
# def load_BROWN(a_fname):
# def load_INQUIRER(a_fname):
# def load_MPQA(a_fname):
# def load_W2V(a_fname):
# def __init__(self, a_cmd, *a_args, **a_kwargs):
# def __contains__(self, a_name):
# def __getitem__(self, a_name):
# def load(self):
# def unload(self):
# class LoadOnDemand(object):
, which may include functions, classes, or code. Output only the next line. | assert "" not in INQUIRER |
Continue the code snippet: <|code_start|>BROWN_CLUSTERS = LoadOnDemand(load_BROWN, TEST_BROWN_PATH)
##################################################################
# Test Classes
class TestResources(TestCase):
def test_BROWN_CLUSTERS(self):
assert BROWN_CLUSTERS["jasper"] == "1100011110"
assert BROWN_CLUSTERS["un"] == "1100011110|1110110010|1011010110"
assert "" not in BROWN_CLUSTERS
def test_CONNS(self):
assert ON_THE_CONTRARY in CONNS
assert NEITHER_NOT in CONNS
assert EMPTY not in CONNS
def test_INQUIRER(self):
assert "" not in INQUIRER
assert INQUIRER["won"] == [False, False, False, False, True,
False, True, False, False, False,
False, False, False, False, True,
False, False, False, False, False,
False, False, False, False, True,
False, False, False, False, False,
False, False, False, False, False,
False, False, False, False, False,
False, False, False, False, False]
assert INQUIRER["won"] == STEMMED_INQUIRER["won"]
def test_LCSI(self):
<|code_end|>
. Use current file imports:
from conftest import TEST_BROWN_PATH
from dsenser.resources import LoadOnDemand, load_BROWN, CONNS, DFLT_W2V_PATH, \
INQUIRER, LCSI, MPQA, STEMMED_INQUIRER, W2V, conn2str
from unittest import TestCase
from mock import patch
import gensim
and context (classes, functions, or code) from other files:
# Path: dsenser/resources.py
# BAR_RE = re.compile(r'\|')
# CHM = ConnHeadMapper()
# ELLIPSIS_RE = re.compile(r"[.][.]+")
# EQ_RE = re.compile("=+")
# HASH_RE = re.compile("\s*#\s*")
# SPACE_RE = re.compile("\s+")
# TAB_RE = re.compile("\t+")
# PSTEMMER = PorterStemmer()
# WORD1 = "word1"
# POL = "priorpolarity"
# POL_IDX = 0
# INTENS = "type"
# INTENS_IDX = 1
# POS = "pos1"
# POS_IDX = 2
# NEGATIONS = set(["cannot", "not", "none", "nothing",
# "nowhere", "neither", "nor", "nobody",
# "hardly", "scarcely", "barely", "never",
# "n't", "noone", "havent", "hasnt",
# "hadnt", "cant", "couldnt", "shouldnt",
# "wont", "wouldnt", "dont", "doesnt",
# "didnt", "isnt", "arent", "aint", "no"
# ])
# LCSI = load_LCSI(DFLT_LCSI_PATH)
# BROWN_CLUSTERS = LoadOnDemand(load_BROWN, DFLT_BROWN_PATH)
# CONNS = load_conns(DFLT_ECONN_PATH)
# CONNTOK2CONN = defaultdict(list)
# CONNTOKS = set(CONNTOK2CONN.keys())
# INQUIRER, STEMMED_INQUIRER = load_INQUIRER(DFLT_INQUIRER_PATH)
# MPQA = load_MPQA(DFLT_MPQA_PATH)
# W2V = LoadOnDemand(load_W2V, DFLT_W2V_PATH)
# def load_conns(a_fname):
# def conn2str(a_conn):
# def load_LCSI(a_fname):
# def load_BROWN(a_fname):
# def load_INQUIRER(a_fname):
# def load_MPQA(a_fname):
# def load_W2V(a_fname):
# def __init__(self, a_cmd, *a_args, **a_kwargs):
# def __contains__(self, a_name):
# def __getitem__(self, a_name):
# def load(self):
# def unload(self):
# class LoadOnDemand(object):
. Output only the next line. | assert LCSI["unionize"] == set(["45.4.a", "45.4.b", "45.4.c"]) |
Next line prediction: <|code_start|># Test Classes
class TestResources(TestCase):
def test_BROWN_CLUSTERS(self):
assert BROWN_CLUSTERS["jasper"] == "1100011110"
assert BROWN_CLUSTERS["un"] == "1100011110|1110110010|1011010110"
assert "" not in BROWN_CLUSTERS
def test_CONNS(self):
assert ON_THE_CONTRARY in CONNS
assert NEITHER_NOT in CONNS
assert EMPTY not in CONNS
def test_INQUIRER(self):
assert "" not in INQUIRER
assert INQUIRER["won"] == [False, False, False, False, True,
False, True, False, False, False,
False, False, False, False, True,
False, False, False, False, False,
False, False, False, False, True,
False, False, False, False, False,
False, False, False, False, False,
False, False, False, False, False,
False, False, False, False, False]
assert INQUIRER["won"] == STEMMED_INQUIRER["won"]
def test_LCSI(self):
assert LCSI["unionize"] == set(["45.4.a", "45.4.b", "45.4.c"])
assert LCSI["confer"] == set(["37.6.a", "37.6.b"])
def test_MPQA(self):
<|code_end|>
. Use current file imports:
(from conftest import TEST_BROWN_PATH
from dsenser.resources import LoadOnDemand, load_BROWN, CONNS, DFLT_W2V_PATH, \
INQUIRER, LCSI, MPQA, STEMMED_INQUIRER, W2V, conn2str
from unittest import TestCase
from mock import patch
import gensim)
and context including class names, function names, or small code snippets from other files:
# Path: dsenser/resources.py
# BAR_RE = re.compile(r'\|')
# CHM = ConnHeadMapper()
# ELLIPSIS_RE = re.compile(r"[.][.]+")
# EQ_RE = re.compile("=+")
# HASH_RE = re.compile("\s*#\s*")
# SPACE_RE = re.compile("\s+")
# TAB_RE = re.compile("\t+")
# PSTEMMER = PorterStemmer()
# WORD1 = "word1"
# POL = "priorpolarity"
# POL_IDX = 0
# INTENS = "type"
# INTENS_IDX = 1
# POS = "pos1"
# POS_IDX = 2
# NEGATIONS = set(["cannot", "not", "none", "nothing",
# "nowhere", "neither", "nor", "nobody",
# "hardly", "scarcely", "barely", "never",
# "n't", "noone", "havent", "hasnt",
# "hadnt", "cant", "couldnt", "shouldnt",
# "wont", "wouldnt", "dont", "doesnt",
# "didnt", "isnt", "arent", "aint", "no"
# ])
# LCSI = load_LCSI(DFLT_LCSI_PATH)
# BROWN_CLUSTERS = LoadOnDemand(load_BROWN, DFLT_BROWN_PATH)
# CONNS = load_conns(DFLT_ECONN_PATH)
# CONNTOK2CONN = defaultdict(list)
# CONNTOKS = set(CONNTOK2CONN.keys())
# INQUIRER, STEMMED_INQUIRER = load_INQUIRER(DFLT_INQUIRER_PATH)
# MPQA = load_MPQA(DFLT_MPQA_PATH)
# W2V = LoadOnDemand(load_W2V, DFLT_W2V_PATH)
# def load_conns(a_fname):
# def conn2str(a_conn):
# def load_LCSI(a_fname):
# def load_BROWN(a_fname):
# def load_INQUIRER(a_fname):
# def load_MPQA(a_fname):
# def load_W2V(a_fname):
# def __init__(self, a_cmd, *a_args, **a_kwargs):
# def __contains__(self, a_name):
# def __getitem__(self, a_name):
# def load(self):
# def unload(self):
# class LoadOnDemand(object):
. Output only the next line. | assert MPQA["zealously"] == ("negative", "strongsubj", "anypos") |
Given the code snippet: <|code_start|>ON_THE_CONTRARY = (("on", "the", "contrary"),)
NEITHER_NOT = (("neither", ), ("nor",))
EMPTY = ((), )
BROWN_CLUSTERS = LoadOnDemand(load_BROWN, TEST_BROWN_PATH)
##################################################################
# Test Classes
class TestResources(TestCase):
def test_BROWN_CLUSTERS(self):
assert BROWN_CLUSTERS["jasper"] == "1100011110"
assert BROWN_CLUSTERS["un"] == "1100011110|1110110010|1011010110"
assert "" not in BROWN_CLUSTERS
def test_CONNS(self):
assert ON_THE_CONTRARY in CONNS
assert NEITHER_NOT in CONNS
assert EMPTY not in CONNS
def test_INQUIRER(self):
assert "" not in INQUIRER
assert INQUIRER["won"] == [False, False, False, False, True,
False, True, False, False, False,
False, False, False, False, True,
False, False, False, False, False,
False, False, False, False, True,
False, False, False, False, False,
False, False, False, False, False,
False, False, False, False, False,
False, False, False, False, False]
<|code_end|>
, generate the next line using the imports in this file:
from conftest import TEST_BROWN_PATH
from dsenser.resources import LoadOnDemand, load_BROWN, CONNS, DFLT_W2V_PATH, \
INQUIRER, LCSI, MPQA, STEMMED_INQUIRER, W2V, conn2str
from unittest import TestCase
from mock import patch
import gensim
and context (functions, classes, or occasionally code) from other files:
# Path: dsenser/resources.py
# BAR_RE = re.compile(r'\|')
# CHM = ConnHeadMapper()
# ELLIPSIS_RE = re.compile(r"[.][.]+")
# EQ_RE = re.compile("=+")
# HASH_RE = re.compile("\s*#\s*")
# SPACE_RE = re.compile("\s+")
# TAB_RE = re.compile("\t+")
# PSTEMMER = PorterStemmer()
# WORD1 = "word1"
# POL = "priorpolarity"
# POL_IDX = 0
# INTENS = "type"
# INTENS_IDX = 1
# POS = "pos1"
# POS_IDX = 2
# NEGATIONS = set(["cannot", "not", "none", "nothing",
# "nowhere", "neither", "nor", "nobody",
# "hardly", "scarcely", "barely", "never",
# "n't", "noone", "havent", "hasnt",
# "hadnt", "cant", "couldnt", "shouldnt",
# "wont", "wouldnt", "dont", "doesnt",
# "didnt", "isnt", "arent", "aint", "no"
# ])
# LCSI = load_LCSI(DFLT_LCSI_PATH)
# BROWN_CLUSTERS = LoadOnDemand(load_BROWN, DFLT_BROWN_PATH)
# CONNS = load_conns(DFLT_ECONN_PATH)
# CONNTOK2CONN = defaultdict(list)
# CONNTOKS = set(CONNTOK2CONN.keys())
# INQUIRER, STEMMED_INQUIRER = load_INQUIRER(DFLT_INQUIRER_PATH)
# MPQA = load_MPQA(DFLT_MPQA_PATH)
# W2V = LoadOnDemand(load_W2V, DFLT_W2V_PATH)
# def load_conns(a_fname):
# def conn2str(a_conn):
# def load_LCSI(a_fname):
# def load_BROWN(a_fname):
# def load_INQUIRER(a_fname):
# def load_MPQA(a_fname):
# def load_W2V(a_fname):
# def __init__(self, a_cmd, *a_args, **a_kwargs):
# def __contains__(self, a_name):
# def __getitem__(self, a_name):
# def load(self):
# def unload(self):
# class LoadOnDemand(object):
. Output only the next line. | assert INQUIRER["won"] == STEMMED_INQUIRER["won"] |
Here is a snippet: <|code_start|> assert EMPTY not in CONNS
def test_INQUIRER(self):
assert "" not in INQUIRER
assert INQUIRER["won"] == [False, False, False, False, True,
False, True, False, False, False,
False, False, False, False, True,
False, False, False, False, False,
False, False, False, False, True,
False, False, False, False, False,
False, False, False, False, False,
False, False, False, False, False,
False, False, False, False, False]
assert INQUIRER["won"] == STEMMED_INQUIRER["won"]
def test_LCSI(self):
assert LCSI["unionize"] == set(["45.4.a", "45.4.b", "45.4.c"])
assert LCSI["confer"] == set(["37.6.a", "37.6.b"])
def test_MPQA(self):
assert MPQA["zealously"] == ("negative", "strongsubj", "anypos")
def test_conn2str(self):
assert conn2str(ON_THE_CONTRARY) == "on_the_contrary"
assert conn2str(NEITHER_NOT) == "neither_nor"
assert conn2str(EMPTY) == ""
def test_w2v(self):
with patch.object(gensim.models.word2vec.Word2Vec,
"load_word2vec_format") as mock_method:
<|code_end|>
. Write the next line using the current file imports:
from conftest import TEST_BROWN_PATH
from dsenser.resources import LoadOnDemand, load_BROWN, CONNS, DFLT_W2V_PATH, \
INQUIRER, LCSI, MPQA, STEMMED_INQUIRER, W2V, conn2str
from unittest import TestCase
from mock import patch
import gensim
and context from other files:
# Path: dsenser/resources.py
# BAR_RE = re.compile(r'\|')
# CHM = ConnHeadMapper()
# ELLIPSIS_RE = re.compile(r"[.][.]+")
# EQ_RE = re.compile("=+")
# HASH_RE = re.compile("\s*#\s*")
# SPACE_RE = re.compile("\s+")
# TAB_RE = re.compile("\t+")
# PSTEMMER = PorterStemmer()
# WORD1 = "word1"
# POL = "priorpolarity"
# POL_IDX = 0
# INTENS = "type"
# INTENS_IDX = 1
# POS = "pos1"
# POS_IDX = 2
# NEGATIONS = set(["cannot", "not", "none", "nothing",
# "nowhere", "neither", "nor", "nobody",
# "hardly", "scarcely", "barely", "never",
# "n't", "noone", "havent", "hasnt",
# "hadnt", "cant", "couldnt", "shouldnt",
# "wont", "wouldnt", "dont", "doesnt",
# "didnt", "isnt", "arent", "aint", "no"
# ])
# LCSI = load_LCSI(DFLT_LCSI_PATH)
# BROWN_CLUSTERS = LoadOnDemand(load_BROWN, DFLT_BROWN_PATH)
# CONNS = load_conns(DFLT_ECONN_PATH)
# CONNTOK2CONN = defaultdict(list)
# CONNTOKS = set(CONNTOK2CONN.keys())
# INQUIRER, STEMMED_INQUIRER = load_INQUIRER(DFLT_INQUIRER_PATH)
# MPQA = load_MPQA(DFLT_MPQA_PATH)
# W2V = LoadOnDemand(load_W2V, DFLT_W2V_PATH)
# def load_conns(a_fname):
# def conn2str(a_conn):
# def load_LCSI(a_fname):
# def load_BROWN(a_fname):
# def load_INQUIRER(a_fname):
# def load_MPQA(a_fname):
# def load_W2V(a_fname):
# def __init__(self, a_cmd, *a_args, **a_kwargs):
# def __contains__(self, a_name):
# def __getitem__(self, a_name):
# def load(self):
# def unload(self):
# class LoadOnDemand(object):
, which may include functions, classes, or code. Output only the next line. | W2V["zzz"] |
Given the code snippet: <|code_start|> assert BROWN_CLUSTERS["jasper"] == "1100011110"
assert BROWN_CLUSTERS["un"] == "1100011110|1110110010|1011010110"
assert "" not in BROWN_CLUSTERS
def test_CONNS(self):
assert ON_THE_CONTRARY in CONNS
assert NEITHER_NOT in CONNS
assert EMPTY not in CONNS
def test_INQUIRER(self):
assert "" not in INQUIRER
assert INQUIRER["won"] == [False, False, False, False, True,
False, True, False, False, False,
False, False, False, False, True,
False, False, False, False, False,
False, False, False, False, True,
False, False, False, False, False,
False, False, False, False, False,
False, False, False, False, False,
False, False, False, False, False]
assert INQUIRER["won"] == STEMMED_INQUIRER["won"]
def test_LCSI(self):
assert LCSI["unionize"] == set(["45.4.a", "45.4.b", "45.4.c"])
assert LCSI["confer"] == set(["37.6.a", "37.6.b"])
def test_MPQA(self):
assert MPQA["zealously"] == ("negative", "strongsubj", "anypos")
def test_conn2str(self):
<|code_end|>
, generate the next line using the imports in this file:
from conftest import TEST_BROWN_PATH
from dsenser.resources import LoadOnDemand, load_BROWN, CONNS, DFLT_W2V_PATH, \
INQUIRER, LCSI, MPQA, STEMMED_INQUIRER, W2V, conn2str
from unittest import TestCase
from mock import patch
import gensim
and context (functions, classes, or occasionally code) from other files:
# Path: dsenser/resources.py
# BAR_RE = re.compile(r'\|')
# CHM = ConnHeadMapper()
# ELLIPSIS_RE = re.compile(r"[.][.]+")
# EQ_RE = re.compile("=+")
# HASH_RE = re.compile("\s*#\s*")
# SPACE_RE = re.compile("\s+")
# TAB_RE = re.compile("\t+")
# PSTEMMER = PorterStemmer()
# WORD1 = "word1"
# POL = "priorpolarity"
# POL_IDX = 0
# INTENS = "type"
# INTENS_IDX = 1
# POS = "pos1"
# POS_IDX = 2
# NEGATIONS = set(["cannot", "not", "none", "nothing",
# "nowhere", "neither", "nor", "nobody",
# "hardly", "scarcely", "barely", "never",
# "n't", "noone", "havent", "hasnt",
# "hadnt", "cant", "couldnt", "shouldnt",
# "wont", "wouldnt", "dont", "doesnt",
# "didnt", "isnt", "arent", "aint", "no"
# ])
# LCSI = load_LCSI(DFLT_LCSI_PATH)
# BROWN_CLUSTERS = LoadOnDemand(load_BROWN, DFLT_BROWN_PATH)
# CONNS = load_conns(DFLT_ECONN_PATH)
# CONNTOK2CONN = defaultdict(list)
# CONNTOKS = set(CONNTOK2CONN.keys())
# INQUIRER, STEMMED_INQUIRER = load_INQUIRER(DFLT_INQUIRER_PATH)
# MPQA = load_MPQA(DFLT_MPQA_PATH)
# W2V = LoadOnDemand(load_W2V, DFLT_W2V_PATH)
# def load_conns(a_fname):
# def conn2str(a_conn):
# def load_LCSI(a_fname):
# def load_BROWN(a_fname):
# def load_INQUIRER(a_fname):
# def load_MPQA(a_fname):
# def load_W2V(a_fname):
# def __init__(self, a_cmd, *a_args, **a_kwargs):
# def __contains__(self, a_name):
# def __getitem__(self, a_name):
# def load(self):
# def unload(self):
# class LoadOnDemand(object):
. Output only the next line. | assert conn2str(ON_THE_CONTRARY) == "on_the_contrary" |
Given the code snippet: <|code_start|>POL = "priorpolarity"
POL_IDX = 0
INTENS = "type"
INTENS_IDX = 1
POS = "pos1"
POS_IDX = 2
NEGATIONS = set(["cannot", "not", "none", "nothing",
"nowhere", "neither", "nor", "nobody",
"hardly", "scarcely", "barely", "never",
"n't", "noone", "havent", "hasnt",
"hadnt", "cant", "couldnt", "shouldnt",
"wont", "wouldnt", "dont", "doesnt",
"didnt", "isnt", "arent", "aint", "no"
])
##################################################################
# Methods
def load_conns(a_fname):
"""Load explicit connectives from file.
Args:
a_fname (str): file containing connectives
Returns:
set: set of loaded connectives
"""
ret = set()
iconn = None
<|code_end|>
, generate the next line using the imports in this file:
from dsenser.constants import ENCODING, DFLT_BROWN_PATH, DFLT_ECONN_PATH, \
DFLT_INQUIRER_PATH, DFLT_LCSI_PATH, DFLT_MPQA_PATH, DFLT_W2V_PATH
from dsenser.scorer.conn_head_mapper import ConnHeadMapper
from collections import defaultdict
from nltk.stem.porter import PorterStemmer
from gensim.models.word2vec import Word2Vec
import codecs
import gc
import re
import sys
and context (functions, classes, or occasionally code) from other files:
# Path: dsenser/constants.py
# ENCODING = "utf-8"
#
# DFLT_BROWN_PATH = os.path.join(DATA_DIR, "brown_cluster_1000.txt")
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# DFLT_INQUIRER_PATH = os.path.join(DATA_DIR, "inquirer_word")
#
# DFLT_LCSI_PATH = os.path.join(DATA_DIR, "LCSInfomerge.txt")
#
# DFLT_MPQA_PATH = os.path.join(DATA_DIR, "MPQA_Subjectivity_Lexicon.txt")
#
# DFLT_W2V_PATH = os.path.join(DATA_DIR, "GoogleNews-vectors-negative300.bin")
. Output only the next line. | with codecs.open(a_fname, 'r', ENCODING, |
Given the code snippet: <|code_start|>
def load(self):
"""Force loading the resource.
Note:
loads the resource
"""
if self.resource is None:
self.resource = self.cmd(*self.args, **self.kwargs)
return self.resource
def unload(self):
"""Unload the resource.
Note:
unloads the resource
"""
if self.resource is not None:
print("Unloading resource '{:s}'...".format(repr(self.resource)),
file=sys.stderr)
del self.resource
self.resource = None
gc.collect()
##################################################################
# Resources
LCSI = load_LCSI(DFLT_LCSI_PATH)
<|code_end|>
, generate the next line using the imports in this file:
from dsenser.constants import ENCODING, DFLT_BROWN_PATH, DFLT_ECONN_PATH, \
DFLT_INQUIRER_PATH, DFLT_LCSI_PATH, DFLT_MPQA_PATH, DFLT_W2V_PATH
from dsenser.scorer.conn_head_mapper import ConnHeadMapper
from collections import defaultdict
from nltk.stem.porter import PorterStemmer
from gensim.models.word2vec import Word2Vec
import codecs
import gc
import re
import sys
and context (functions, classes, or occasionally code) from other files:
# Path: dsenser/constants.py
# ENCODING = "utf-8"
#
# DFLT_BROWN_PATH = os.path.join(DATA_DIR, "brown_cluster_1000.txt")
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# DFLT_INQUIRER_PATH = os.path.join(DATA_DIR, "inquirer_word")
#
# DFLT_LCSI_PATH = os.path.join(DATA_DIR, "LCSInfomerge.txt")
#
# DFLT_MPQA_PATH = os.path.join(DATA_DIR, "MPQA_Subjectivity_Lexicon.txt")
#
# DFLT_W2V_PATH = os.path.join(DATA_DIR, "GoogleNews-vectors-negative300.bin")
. Output only the next line. | BROWN_CLUSTERS = LoadOnDemand(load_BROWN, DFLT_BROWN_PATH) |
Based on the snippet: <|code_start|> def load(self):
"""Force loading the resource.
Note:
loads the resource
"""
if self.resource is None:
self.resource = self.cmd(*self.args, **self.kwargs)
return self.resource
def unload(self):
"""Unload the resource.
Note:
unloads the resource
"""
if self.resource is not None:
print("Unloading resource '{:s}'...".format(repr(self.resource)),
file=sys.stderr)
del self.resource
self.resource = None
gc.collect()
##################################################################
# Resources
LCSI = load_LCSI(DFLT_LCSI_PATH)
BROWN_CLUSTERS = LoadOnDemand(load_BROWN, DFLT_BROWN_PATH)
<|code_end|>
, predict the immediate next line with the help of imports:
from dsenser.constants import ENCODING, DFLT_BROWN_PATH, DFLT_ECONN_PATH, \
DFLT_INQUIRER_PATH, DFLT_LCSI_PATH, DFLT_MPQA_PATH, DFLT_W2V_PATH
from dsenser.scorer.conn_head_mapper import ConnHeadMapper
from collections import defaultdict
from nltk.stem.porter import PorterStemmer
from gensim.models.word2vec import Word2Vec
import codecs
import gc
import re
import sys
and context (classes, functions, sometimes code) from other files:
# Path: dsenser/constants.py
# ENCODING = "utf-8"
#
# DFLT_BROWN_PATH = os.path.join(DATA_DIR, "brown_cluster_1000.txt")
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# DFLT_INQUIRER_PATH = os.path.join(DATA_DIR, "inquirer_word")
#
# DFLT_LCSI_PATH = os.path.join(DATA_DIR, "LCSInfomerge.txt")
#
# DFLT_MPQA_PATH = os.path.join(DATA_DIR, "MPQA_Subjectivity_Lexicon.txt")
#
# DFLT_W2V_PATH = os.path.join(DATA_DIR, "GoogleNews-vectors-negative300.bin")
. Output only the next line. | CONNS = load_conns(DFLT_ECONN_PATH) |
Next line prediction: <|code_start|>
Note:
unloads the resource
"""
if self.resource is not None:
print("Unloading resource '{:s}'...".format(repr(self.resource)),
file=sys.stderr)
del self.resource
self.resource = None
gc.collect()
##################################################################
# Resources
LCSI = load_LCSI(DFLT_LCSI_PATH)
BROWN_CLUSTERS = LoadOnDemand(load_BROWN, DFLT_BROWN_PATH)
CONNS = load_conns(DFLT_ECONN_PATH)
CONNTOK2CONN = defaultdict(list)
itok = None
for iconn in CONNS:
for i, ipart in enumerate(iconn):
itok = ipart[0]
CONNTOK2CONN[itok].append((i, iconn))
for iconns in CONNTOK2CONN.itervalues():
iconns.sort(key=lambda el: el[0])
CONNTOKS = set(CONNTOK2CONN.keys())
<|code_end|>
. Use current file imports:
(from dsenser.constants import ENCODING, DFLT_BROWN_PATH, DFLT_ECONN_PATH, \
DFLT_INQUIRER_PATH, DFLT_LCSI_PATH, DFLT_MPQA_PATH, DFLT_W2V_PATH
from dsenser.scorer.conn_head_mapper import ConnHeadMapper
from collections import defaultdict
from nltk.stem.porter import PorterStemmer
from gensim.models.word2vec import Word2Vec
import codecs
import gc
import re
import sys)
and context including class names, function names, or small code snippets from other files:
# Path: dsenser/constants.py
# ENCODING = "utf-8"
#
# DFLT_BROWN_PATH = os.path.join(DATA_DIR, "brown_cluster_1000.txt")
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# DFLT_INQUIRER_PATH = os.path.join(DATA_DIR, "inquirer_word")
#
# DFLT_LCSI_PATH = os.path.join(DATA_DIR, "LCSInfomerge.txt")
#
# DFLT_MPQA_PATH = os.path.join(DATA_DIR, "MPQA_Subjectivity_Lexicon.txt")
#
# DFLT_W2V_PATH = os.path.join(DATA_DIR, "GoogleNews-vectors-negative300.bin")
. Output only the next line. | INQUIRER, STEMMED_INQUIRER = load_INQUIRER(DFLT_INQUIRER_PATH) |
Predict the next line after this snippet: <|code_start|> return self.resource.__getitem__(a_name)
def load(self):
"""Force loading the resource.
Note:
loads the resource
"""
if self.resource is None:
self.resource = self.cmd(*self.args, **self.kwargs)
return self.resource
def unload(self):
"""Unload the resource.
Note:
unloads the resource
"""
if self.resource is not None:
print("Unloading resource '{:s}'...".format(repr(self.resource)),
file=sys.stderr)
del self.resource
self.resource = None
gc.collect()
##################################################################
# Resources
<|code_end|>
using the current file's imports:
from dsenser.constants import ENCODING, DFLT_BROWN_PATH, DFLT_ECONN_PATH, \
DFLT_INQUIRER_PATH, DFLT_LCSI_PATH, DFLT_MPQA_PATH, DFLT_W2V_PATH
from dsenser.scorer.conn_head_mapper import ConnHeadMapper
from collections import defaultdict
from nltk.stem.porter import PorterStemmer
from gensim.models.word2vec import Word2Vec
import codecs
import gc
import re
import sys
and any relevant context from other files:
# Path: dsenser/constants.py
# ENCODING = "utf-8"
#
# DFLT_BROWN_PATH = os.path.join(DATA_DIR, "brown_cluster_1000.txt")
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# DFLT_INQUIRER_PATH = os.path.join(DATA_DIR, "inquirer_word")
#
# DFLT_LCSI_PATH = os.path.join(DATA_DIR, "LCSInfomerge.txt")
#
# DFLT_MPQA_PATH = os.path.join(DATA_DIR, "MPQA_Subjectivity_Lexicon.txt")
#
# DFLT_W2V_PATH = os.path.join(DATA_DIR, "GoogleNews-vectors-negative300.bin")
. Output only the next line. | LCSI = load_LCSI(DFLT_LCSI_PATH) |
Using the snippet: <|code_start|> Note:
unloads the resource
"""
if self.resource is not None:
print("Unloading resource '{:s}'...".format(repr(self.resource)),
file=sys.stderr)
del self.resource
self.resource = None
gc.collect()
##################################################################
# Resources
LCSI = load_LCSI(DFLT_LCSI_PATH)
BROWN_CLUSTERS = LoadOnDemand(load_BROWN, DFLT_BROWN_PATH)
CONNS = load_conns(DFLT_ECONN_PATH)
CONNTOK2CONN = defaultdict(list)
itok = None
for iconn in CONNS:
for i, ipart in enumerate(iconn):
itok = ipart[0]
CONNTOK2CONN[itok].append((i, iconn))
for iconns in CONNTOK2CONN.itervalues():
iconns.sort(key=lambda el: el[0])
CONNTOKS = set(CONNTOK2CONN.keys())
INQUIRER, STEMMED_INQUIRER = load_INQUIRER(DFLT_INQUIRER_PATH)
<|code_end|>
, determine the next line of code. You have imports:
from dsenser.constants import ENCODING, DFLT_BROWN_PATH, DFLT_ECONN_PATH, \
DFLT_INQUIRER_PATH, DFLT_LCSI_PATH, DFLT_MPQA_PATH, DFLT_W2V_PATH
from dsenser.scorer.conn_head_mapper import ConnHeadMapper
from collections import defaultdict
from nltk.stem.porter import PorterStemmer
from gensim.models.word2vec import Word2Vec
import codecs
import gc
import re
import sys
and context (class names, function names, or code) available:
# Path: dsenser/constants.py
# ENCODING = "utf-8"
#
# DFLT_BROWN_PATH = os.path.join(DATA_DIR, "brown_cluster_1000.txt")
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# DFLT_INQUIRER_PATH = os.path.join(DATA_DIR, "inquirer_word")
#
# DFLT_LCSI_PATH = os.path.join(DATA_DIR, "LCSInfomerge.txt")
#
# DFLT_MPQA_PATH = os.path.join(DATA_DIR, "MPQA_Subjectivity_Lexicon.txt")
#
# DFLT_W2V_PATH = os.path.join(DATA_DIR, "GoogleNews-vectors-negative300.bin")
. Output only the next line. | MPQA = load_MPQA(DFLT_MPQA_PATH) |
Next line prediction: <|code_start|> unloads the resource
"""
if self.resource is not None:
print("Unloading resource '{:s}'...".format(repr(self.resource)),
file=sys.stderr)
del self.resource
self.resource = None
gc.collect()
##################################################################
# Resources
LCSI = load_LCSI(DFLT_LCSI_PATH)
BROWN_CLUSTERS = LoadOnDemand(load_BROWN, DFLT_BROWN_PATH)
CONNS = load_conns(DFLT_ECONN_PATH)
CONNTOK2CONN = defaultdict(list)
itok = None
for iconn in CONNS:
for i, ipart in enumerate(iconn):
itok = ipart[0]
CONNTOK2CONN[itok].append((i, iconn))
for iconns in CONNTOK2CONN.itervalues():
iconns.sort(key=lambda el: el[0])
CONNTOKS = set(CONNTOK2CONN.keys())
INQUIRER, STEMMED_INQUIRER = load_INQUIRER(DFLT_INQUIRER_PATH)
MPQA = load_MPQA(DFLT_MPQA_PATH)
<|code_end|>
. Use current file imports:
(from dsenser.constants import ENCODING, DFLT_BROWN_PATH, DFLT_ECONN_PATH, \
DFLT_INQUIRER_PATH, DFLT_LCSI_PATH, DFLT_MPQA_PATH, DFLT_W2V_PATH
from dsenser.scorer.conn_head_mapper import ConnHeadMapper
from collections import defaultdict
from nltk.stem.porter import PorterStemmer
from gensim.models.word2vec import Word2Vec
import codecs
import gc
import re
import sys)
and context including class names, function names, or small code snippets from other files:
# Path: dsenser/constants.py
# ENCODING = "utf-8"
#
# DFLT_BROWN_PATH = os.path.join(DATA_DIR, "brown_cluster_1000.txt")
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# DFLT_INQUIRER_PATH = os.path.join(DATA_DIR, "inquirer_word")
#
# DFLT_LCSI_PATH = os.path.join(DATA_DIR, "LCSInfomerge.txt")
#
# DFLT_MPQA_PATH = os.path.join(DATA_DIR, "MPQA_Subjectivity_Lexicon.txt")
#
# DFLT_W2V_PATH = os.path.join(DATA_DIR, "GoogleNews-vectors-negative300.bin")
. Output only the next line. | W2V = LoadOnDemand(load_W2V, DFLT_W2V_PATH) |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
"""Module providing class for SVD sense disambiguation.
Attributes:
SVDImplicitSenser (class):
class that predicts senses of implicit relations
"""
##################################################################
# Imports
from __future__ import absolute_import, print_function
##################################################################
# Variables and Constants
##################################################################
# Classes
<|code_end|>
, generate the next line using the imports in this file:
from dsenser.svd.svdbase import SVDBaseSenser
from dsenser.utils import timeit
and context (functions, classes, or occasionally code) from other files:
# Path: dsenser/svd/svdbase.py
# class SVDBaseSenser(NNBaseSenser):
# """Abstract class for disambiguating relation senses.
#
# Attributes:
# n_y (int): number of distinct classes
#
# """
#
# def _init_nn(self):
# """Initialize neural network.
#
# """
# self.intm_dim = max(MIN_DIM, self.ndim - (self.ndim - self.n_y) / 2)
# # indices of word embeddings
# self.W_INDICES_ARG1 = TT.ivector(name="W_INDICES_ARG1")
# self.W_INDICES_ARG2 = TT.ivector(name="W_INDICES_ARG2")
# # connective's index
# self.CONN_INDEX = TT.iscalar(name="CONN_INDEX")
# # initialize the matrix of word embeddings
# self.init_w_emb()
# # word embeddings of the arguments
# self.EMB_ARG1 = self.W_EMB[self.W_INDICES_ARG1]
# self.EMB_ARG2 = self.W_EMB[self.W_INDICES_ARG2]
# # connective's embedding
# self._init_conn_emb()
# self.EMB_CONN = self.CONN_EMB[self.CONN_INDEX]
# # perform matrix decomposition
# _, _, self.ARG1 = TT.nlinalg.svd(self.EMB_ARG1,
# full_matrices=True)
# _, _, self.ARG2 = TT.nlinalg.svd(self.EMB_ARG2,
# full_matrices=True)
# self.ARG_DIFF = self.ARG1 - self.ARG2
# # map decomposed matrices to the intermediate level
# self.ARG_DIFF2I = theano.shared(value=HE_UNIFORM((self.ndim, 1)),
# name="ARG_DIFF2I")
# self.arg_diff_bias = theano.shared(value=HE_UNIFORM((1, self.ndim)),
# name="arg_diff_bias")
# self._params.extend([self.ARG_DIFF2I, self.arg_diff_bias])
# self.ARGS = (TT.dot(self.ARG_DIFF, self.ARG_DIFF2I).T +
# self.arg_diff_bias).flatten()
# # define final units
# self.I = TT.concatenate((self.ARGS, self.EMB_CONN))
# self.I2Y = theano.shared(value=HE_UNIFORM((self.n_y,
# self.ndim + self.intm_dim)),
# name="I2Y")
# self.y_bias = theano.shared(value=HE_UNIFORM((1, self.n_y)),
# name="y_bias")
# self._params.extend([self.I2Y, self.y_bias])
# self.Y_pred = TT.nnet.softmax(TT.dot(self.I2Y, self.I).T + self.y_bias)
# # initialize cost and optimization functions
# self.Y_gold = TT.vector(name="Y_gold")
# self._cost = TT.sum((self.Y_pred - self.Y_gold) ** 2)
# self._dev_cost = TT.sum((self.Y_pred - self.Y_gold) ** 2)
# self._pred_class = TT.argmax(self.Y_pred)
# grads = TT.grad(self._cost, wrt=self._params)
# self._init_funcs(grads)
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | class SVDImplicitSenser(SVDBaseSenser): |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
"""Module providing class for SVD sense disambiguation.
Attributes:
SVDImplicitSenser (class):
class that predicts senses of implicit relations
"""
##################################################################
# Imports
from __future__ import absolute_import, print_function
##################################################################
# Variables and Constants
##################################################################
# Classes
class SVDImplicitSenser(SVDBaseSenser):
"""Class for disambiguating implicit discourse relations.
"""
<|code_end|>
, predict the next line using imports from the current file:
from dsenser.svd.svdbase import SVDBaseSenser
from dsenser.utils import timeit
and context including class names, function names, and sometimes code from other files:
# Path: dsenser/svd/svdbase.py
# class SVDBaseSenser(NNBaseSenser):
# """Abstract class for disambiguating relation senses.
#
# Attributes:
# n_y (int): number of distinct classes
#
# """
#
# def _init_nn(self):
# """Initialize neural network.
#
# """
# self.intm_dim = max(MIN_DIM, self.ndim - (self.ndim - self.n_y) / 2)
# # indices of word embeddings
# self.W_INDICES_ARG1 = TT.ivector(name="W_INDICES_ARG1")
# self.W_INDICES_ARG2 = TT.ivector(name="W_INDICES_ARG2")
# # connective's index
# self.CONN_INDEX = TT.iscalar(name="CONN_INDEX")
# # initialize the matrix of word embeddings
# self.init_w_emb()
# # word embeddings of the arguments
# self.EMB_ARG1 = self.W_EMB[self.W_INDICES_ARG1]
# self.EMB_ARG2 = self.W_EMB[self.W_INDICES_ARG2]
# # connective's embedding
# self._init_conn_emb()
# self.EMB_CONN = self.CONN_EMB[self.CONN_INDEX]
# # perform matrix decomposition
# _, _, self.ARG1 = TT.nlinalg.svd(self.EMB_ARG1,
# full_matrices=True)
# _, _, self.ARG2 = TT.nlinalg.svd(self.EMB_ARG2,
# full_matrices=True)
# self.ARG_DIFF = self.ARG1 - self.ARG2
# # map decomposed matrices to the intermediate level
# self.ARG_DIFF2I = theano.shared(value=HE_UNIFORM((self.ndim, 1)),
# name="ARG_DIFF2I")
# self.arg_diff_bias = theano.shared(value=HE_UNIFORM((1, self.ndim)),
# name="arg_diff_bias")
# self._params.extend([self.ARG_DIFF2I, self.arg_diff_bias])
# self.ARGS = (TT.dot(self.ARG_DIFF, self.ARG_DIFF2I).T +
# self.arg_diff_bias).flatten()
# # define final units
# self.I = TT.concatenate((self.ARGS, self.EMB_CONN))
# self.I2Y = theano.shared(value=HE_UNIFORM((self.n_y,
# self.ndim + self.intm_dim)),
# name="I2Y")
# self.y_bias = theano.shared(value=HE_UNIFORM((1, self.n_y)),
# name="y_bias")
# self._params.extend([self.I2Y, self.y_bias])
# self.Y_pred = TT.nnet.softmax(TT.dot(self.I2Y, self.I).T + self.y_bias)
# # initialize cost and optimization functions
# self.Y_gold = TT.vector(name="Y_gold")
# self._cost = TT.sum((self.Y_pred - self.Y_gold) ** 2)
# self._dev_cost = TT.sum((self.Y_pred - self.Y_gold) ** 2)
# self._pred_class = TT.argmax(self.Y_pred)
# grads = TT.grad(self._cost, wrt=self._params)
# self._init_funcs(grads)
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | @timeit("Training implicit SVD classifier...") |
Given snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import
##################################################################
# Constants
##################################################################
# Test Classes
class TestSVDSenser(TestCase):
def test_init(self):
with patch.object(dsenser.nnbase, "Word2Vec",
MagicMock(ndim=300)):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from dsenser.svd import SVDSenser
from dsenser.svd.svdbase import SVDBaseSenser
from mock import patch, MagicMock
from unittest import TestCase
import dsenser
and context:
# Path: dsenser/svd/svd.py
# class SVDSenser(BaseSenser):
# """Class using LSTM classification for disambiguating connectives.
#
# Attributes:
# explicit (:class:`dsenser.svd.explicit.SVDExplicitSenser`):
# classifier for implicit discourse relations
# implicit (:class:`dsenser.svd.implicit.SVDExplicitSenser`):
# classifier for explicit discourse relations
# n_y (int): number of distinct classes
#
# """
#
# def __init__(self, *args, **kwargs):
# """
# Class constructor.
#
# Args:
# args (list): list of arguments
# kwargs (dict): dictionary of keyword arguments
#
# """
# self.explicit = SVDExplicitSenser(*args, **kwargs)
# self.implicit = SVDImplicitSenser(*args, **kwargs)
# self.n_y = -1
#
# Path: dsenser/svd/svdbase.py
# class SVDBaseSenser(NNBaseSenser):
# """Abstract class for disambiguating relation senses.
#
# Attributes:
# n_y (int): number of distinct classes
#
# """
#
# def _init_nn(self):
# """Initialize neural network.
#
# """
# self.intm_dim = max(MIN_DIM, self.ndim - (self.ndim - self.n_y) / 2)
# # indices of word embeddings
# self.W_INDICES_ARG1 = TT.ivector(name="W_INDICES_ARG1")
# self.W_INDICES_ARG2 = TT.ivector(name="W_INDICES_ARG2")
# # connective's index
# self.CONN_INDEX = TT.iscalar(name="CONN_INDEX")
# # initialize the matrix of word embeddings
# self.init_w_emb()
# # word embeddings of the arguments
# self.EMB_ARG1 = self.W_EMB[self.W_INDICES_ARG1]
# self.EMB_ARG2 = self.W_EMB[self.W_INDICES_ARG2]
# # connective's embedding
# self._init_conn_emb()
# self.EMB_CONN = self.CONN_EMB[self.CONN_INDEX]
# # perform matrix decomposition
# _, _, self.ARG1 = TT.nlinalg.svd(self.EMB_ARG1,
# full_matrices=True)
# _, _, self.ARG2 = TT.nlinalg.svd(self.EMB_ARG2,
# full_matrices=True)
# self.ARG_DIFF = self.ARG1 - self.ARG2
# # map decomposed matrices to the intermediate level
# self.ARG_DIFF2I = theano.shared(value=HE_UNIFORM((self.ndim, 1)),
# name="ARG_DIFF2I")
# self.arg_diff_bias = theano.shared(value=HE_UNIFORM((1, self.ndim)),
# name="arg_diff_bias")
# self._params.extend([self.ARG_DIFF2I, self.arg_diff_bias])
# self.ARGS = (TT.dot(self.ARG_DIFF, self.ARG_DIFF2I).T +
# self.arg_diff_bias).flatten()
# # define final units
# self.I = TT.concatenate((self.ARGS, self.EMB_CONN))
# self.I2Y = theano.shared(value=HE_UNIFORM((self.n_y,
# self.ndim + self.intm_dim)),
# name="I2Y")
# self.y_bias = theano.shared(value=HE_UNIFORM((1, self.n_y)),
# name="y_bias")
# self._params.extend([self.I2Y, self.y_bias])
# self.Y_pred = TT.nnet.softmax(TT.dot(self.I2Y, self.I).T + self.y_bias)
# # initialize cost and optimization functions
# self.Y_gold = TT.vector(name="Y_gold")
# self._cost = TT.sum((self.Y_pred - self.Y_gold) ** 2)
# self._dev_cost = TT.sum((self.Y_pred - self.Y_gold) ** 2)
# self._pred_class = TT.argmax(self.Y_pred)
# grads = TT.grad(self._cost, wrt=self._params)
# self._init_funcs(grads)
which might include code, classes, or functions. Output only the next line. | svd = SVDSenser() |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import
##################################################################
# Constants
##################################################################
# Test Classes
class TestSVDSenser(TestCase):
def test_init(self):
with patch.object(dsenser.nnbase, "Word2Vec",
MagicMock(ndim=300)):
svd = SVDSenser()
<|code_end|>
with the help of current file imports:
from dsenser.svd import SVDSenser
from dsenser.svd.svdbase import SVDBaseSenser
from mock import patch, MagicMock
from unittest import TestCase
import dsenser
and context from other files:
# Path: dsenser/svd/svd.py
# class SVDSenser(BaseSenser):
# """Class using LSTM classification for disambiguating connectives.
#
# Attributes:
# explicit (:class:`dsenser.svd.explicit.SVDExplicitSenser`):
# classifier for implicit discourse relations
# implicit (:class:`dsenser.svd.implicit.SVDExplicitSenser`):
# classifier for explicit discourse relations
# n_y (int): number of distinct classes
#
# """
#
# def __init__(self, *args, **kwargs):
# """
# Class constructor.
#
# Args:
# args (list): list of arguments
# kwargs (dict): dictionary of keyword arguments
#
# """
# self.explicit = SVDExplicitSenser(*args, **kwargs)
# self.implicit = SVDImplicitSenser(*args, **kwargs)
# self.n_y = -1
#
# Path: dsenser/svd/svdbase.py
# class SVDBaseSenser(NNBaseSenser):
# """Abstract class for disambiguating relation senses.
#
# Attributes:
# n_y (int): number of distinct classes
#
# """
#
# def _init_nn(self):
# """Initialize neural network.
#
# """
# self.intm_dim = max(MIN_DIM, self.ndim - (self.ndim - self.n_y) / 2)
# # indices of word embeddings
# self.W_INDICES_ARG1 = TT.ivector(name="W_INDICES_ARG1")
# self.W_INDICES_ARG2 = TT.ivector(name="W_INDICES_ARG2")
# # connective's index
# self.CONN_INDEX = TT.iscalar(name="CONN_INDEX")
# # initialize the matrix of word embeddings
# self.init_w_emb()
# # word embeddings of the arguments
# self.EMB_ARG1 = self.W_EMB[self.W_INDICES_ARG1]
# self.EMB_ARG2 = self.W_EMB[self.W_INDICES_ARG2]
# # connective's embedding
# self._init_conn_emb()
# self.EMB_CONN = self.CONN_EMB[self.CONN_INDEX]
# # perform matrix decomposition
# _, _, self.ARG1 = TT.nlinalg.svd(self.EMB_ARG1,
# full_matrices=True)
# _, _, self.ARG2 = TT.nlinalg.svd(self.EMB_ARG2,
# full_matrices=True)
# self.ARG_DIFF = self.ARG1 - self.ARG2
# # map decomposed matrices to the intermediate level
# self.ARG_DIFF2I = theano.shared(value=HE_UNIFORM((self.ndim, 1)),
# name="ARG_DIFF2I")
# self.arg_diff_bias = theano.shared(value=HE_UNIFORM((1, self.ndim)),
# name="arg_diff_bias")
# self._params.extend([self.ARG_DIFF2I, self.arg_diff_bias])
# self.ARGS = (TT.dot(self.ARG_DIFF, self.ARG_DIFF2I).T +
# self.arg_diff_bias).flatten()
# # define final units
# self.I = TT.concatenate((self.ARGS, self.EMB_CONN))
# self.I2Y = theano.shared(value=HE_UNIFORM((self.n_y,
# self.ndim + self.intm_dim)),
# name="I2Y")
# self.y_bias = theano.shared(value=HE_UNIFORM((1, self.n_y)),
# name="y_bias")
# self._params.extend([self.I2Y, self.y_bias])
# self.Y_pred = TT.nnet.softmax(TT.dot(self.I2Y, self.I).T + self.y_bias)
# # initialize cost and optimization functions
# self.Y_gold = TT.vector(name="Y_gold")
# self._cost = TT.sum((self.Y_pred - self.Y_gold) ** 2)
# self._dev_cost = TT.sum((self.Y_pred - self.Y_gold) ** 2)
# self._pred_class = TT.argmax(self.Y_pred)
# grads = TT.grad(self._cost, wrt=self._params)
# self._init_funcs(grads)
, which may contain function names, class names, or code. Output only the next line. | assert isinstance(svd.explicit, SVDBaseSenser) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import
##################################################################
# Variables and Constants
W2V = MagicMock()
DFLT_VEC_SIZE = 300
##################################################################
# Test Classes
class TestWord2Vec(TestCase):
@fixture(autouse=True)
def set_w2v(self):
<|code_end|>
with the help of current file imports:
from dsenser.word2vec import Word2Vec
from mock import patch, MagicMock
from pytest import fixture
from unittest import TestCase
import pytest
and context from other files:
# Path: dsenser/word2vec.py
# class Word2Vec(object):
# """Class for cached retrieval of word embeddings.
#
# """
#
# def __init__(self, a_w2v=W2V):
# """Class cosntructor.
#
# Args:
# a_w2v (gensim.Word2Vec):
# dictionary with original word embeddings
#
# """
# self._w2v = a_w2v
# self._cache = {}
# self.ndim = -1
#
# def __contains__(self, a_word):
# """Proxy method for looking up a word in the resource.
#
# Args:
# a_word (str): word to look up in the resource
#
# Returns:
# (bool):
# true if the word is present in the underlying resource
#
# """
# if a_word in self._cache:
# return True
# elif a_word in self._w2v:
# self._cache[a_word] = self._w2v[a_word]
# return True
# return False
#
# def __getitem__(self, a_word):
# """Proxy method for looking up a word in the resource.
#
# Args:
# a_word (str): word to look up in the resource
#
# Returns:
# (bool):
# true if the word is present in the underlying resource
#
# """
# if a_word in self._cache:
# return self._cache[a_word]
# elif a_word in self._w2v:
# emb = self._cache[a_word] = self._w2v[a_word]
# return emb
# raise KeyError
#
# def load(self):
# """Load the word2vec resource.
#
# Args:
# (void):
#
# Returns:
# (void):
# load the resource in place
#
# """
# self._w2v.load()
# self.ndim = self._w2v.resource.vector_size
#
# def unload(self):
# """Unload the word2vec resource.
#
# Args:
# (void):
#
# Returns:
# (void):
# load the resource in place
#
# """
# self._cache.clear()
# self._w2v.unload()
, which may contain function names, class names, or code. Output only the next line. | self.w2v = Word2Vec |
Predict the next line for this snippet: <|code_start|> np.array: modified ``a_ret``
"""
if self.wbench is None:
self.wbench = np.zeros((len(self.models), len(self.cls2idx)))
else:
self.wbench *= 0
for i, imodel in enumerate(self.models):
imodel.predict(a_rel, a_data, self.wbench, i)
return self.wbench
def _prune_data(self, a_rels, a_parses):
"""Remove unnecessary information from data.
Args:
a_rels (list):
list of input discourse relations
a_parses (dict):
parse trees
Returns:
2-tuple(list, dict):
abridged input data
"""
arg = None
# clean-up relations
for irel in a_rels:
irel.pop("ID")
irel[CONNECTIVE].pop(CHAR_SPAN)
<|code_end|>
with the help of current file imports:
from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys
and context from other files:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
, which may contain function names, class names, or code. Output only the next line. | arg = irel[ARG1] |
Predict the next line after this snippet: <|code_start|> if self.wbench is None:
self.wbench = np.zeros((len(self.models), len(self.cls2idx)))
else:
self.wbench *= 0
for i, imodel in enumerate(self.models):
imodel.predict(a_rel, a_data, self.wbench, i)
return self.wbench
def _prune_data(self, a_rels, a_parses):
"""Remove unnecessary information from data.
Args:
a_rels (list):
list of input discourse relations
a_parses (dict):
parse trees
Returns:
2-tuple(list, dict):
abridged input data
"""
arg = None
# clean-up relations
for irel in a_rels:
irel.pop("ID")
irel[CONNECTIVE].pop(CHAR_SPAN)
arg = irel[ARG1]
arg.pop(CHAR_SPAN)
arg.pop(RAW_TEXT)
<|code_end|>
using the current file's imports:
from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys
and any relevant context from other files:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | arg = irel[ARG2] |
Continue the code snippet: <|code_start|> Returns:
np.array: modified ``a_ret``
"""
if self.wbench is None:
self.wbench = np.zeros((len(self.models), len(self.cls2idx)))
else:
self.wbench *= 0
for i, imodel in enumerate(self.models):
imodel.predict(a_rel, a_data, self.wbench, i)
return self.wbench
def _prune_data(self, a_rels, a_parses):
"""Remove unnecessary information from data.
Args:
a_rels (list):
list of input discourse relations
a_parses (dict):
parse trees
Returns:
2-tuple(list, dict):
abridged input data
"""
arg = None
# clean-up relations
for irel in a_rels:
irel.pop("ID")
<|code_end|>
. Use current file imports:
from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys
and context (classes, functions, or code) from other files:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | irel[CONNECTIVE].pop(CHAR_SPAN) |
Based on the snippet: <|code_start|> self.models.append(WangSenser(a_grid_search=a_grid_search))
if a_type & XGBOOST:
self.models.append(XGBoostSenser(a_grid_search=a_grid_search))
# NN models have to go last, since we are pruning the parses for them
# to free some memory
nn_used = False
if a_type & SVD:
# since we cannot differentiate SVD yet, we can only use word2vec
# embeddings
if not a_w2v or a_lstsq:
print("SVD senser does not support task-specific embeddings "
"and least squares yet.", file=sys.stderr)
self.models.append(SVDSenser(a_w2v=True, a_lstsq=False,
a_max_iters=256))
nn_used = True
if a_type & LSTM:
self.models.append(LSTMSenser(a_w2v, a_lstsq))
nn_used = True
# remember all possible senses
n_senses = 0
for irel in chain(a_train_data[0], a_dev_data[0]
if a_dev_data is not None else []):
for isense in irel[SENSE]:
isense = SHORT2FULL.get(isense, isense)
if isense not in self.cls2idx:
n_senses = len(self.cls2idx)
self.cls2idx[isense] = n_senses
self.idx2cls[n_senses] = isense
if irel[TYPE] == EXPLICIT:
self.econn.add(self._normalize_conn(
<|code_end|>
, predict the immediate next line with the help of imports:
from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys
and context (classes, functions, sometimes code) from other files:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | irel[CONNECTIVE][RAW_TEXT])) |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
"""Module providing class for sense disambiguation of connectives.
Attributes:
DiscourseSenser (class): class for sense disambiguation of connectives
"""
##################################################################
# Imports
from __future__ import absolute_import, print_function, unicode_literals
##################################################################
# Variables and Constants
# load default explicit discourse connectives
DFLT_CONN = set(["upon"])
<|code_end|>
, generate the next line using the imports in this file:
from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys
and context (functions, classes, or occasionally code) from other files:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | with codecs.open(DFLT_ECONN_PATH, 'r', ENCODING) as ifile: |
Continue the code snippet: <|code_start|> self.models.append(WangSenser(a_grid_search=a_grid_search))
if a_type & XGBOOST:
self.models.append(XGBoostSenser(a_grid_search=a_grid_search))
# NN models have to go last, since we are pruning the parses for them
# to free some memory
nn_used = False
if a_type & SVD:
# since we cannot differentiate SVD yet, we can only use word2vec
# embeddings
if not a_w2v or a_lstsq:
print("SVD senser does not support task-specific embeddings "
"and least squares yet.", file=sys.stderr)
self.models.append(SVDSenser(a_w2v=True, a_lstsq=False,
a_max_iters=256))
nn_used = True
if a_type & LSTM:
self.models.append(LSTMSenser(a_w2v, a_lstsq))
nn_used = True
# remember all possible senses
n_senses = 0
for irel in chain(a_train_data[0], a_dev_data[0]
if a_dev_data is not None else []):
for isense in irel[SENSE]:
isense = SHORT2FULL.get(isense, isense)
if isense not in self.cls2idx:
n_senses = len(self.cls2idx)
self.cls2idx[isense] = n_senses
self.idx2cls[n_senses] = isense
if irel[TYPE] == EXPLICIT:
self.econn.add(self._normalize_conn(
<|code_end|>
. Use current file imports:
from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys
and context (classes, functions, or code) from other files:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | irel[CONNECTIVE][RAW_TEXT])) |
Using the snippet: <|code_start|> if a_type == 0:
raise RuntimeError("No model type specified.")
if a_dev_data is None:
a_dev_data = ([], {})
# initialize models
if a_type & MJR:
self.models.append(MajorSenser())
if a_type & WANG:
self.models.append(WangSenser(a_grid_search=a_grid_search))
if a_type & XGBOOST:
self.models.append(XGBoostSenser(a_grid_search=a_grid_search))
# NN models have to go last, since we are pruning the parses for them
# to free some memory
nn_used = False
if a_type & SVD:
# since we cannot differentiate SVD yet, we can only use word2vec
# embeddings
if not a_w2v or a_lstsq:
print("SVD senser does not support task-specific embeddings "
"and least squares yet.", file=sys.stderr)
self.models.append(SVDSenser(a_w2v=True, a_lstsq=False,
a_max_iters=256))
nn_used = True
if a_type & LSTM:
self.models.append(LSTMSenser(a_w2v, a_lstsq))
nn_used = True
# remember all possible senses
n_senses = 0
for irel in chain(a_train_data[0], a_dev_data[0]
if a_dev_data is not None else []):
<|code_end|>
, determine the next line of code. You have imports:
from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys
and context (class names, function names, or code) available:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | for isense in irel[SENSE]: |
Continue the code snippet: <|code_start|> for isentences in a_parses.itervalues():
for isent in isentences[SENTENCES]:
isent.pop(PARSE_TREE)
isent.pop(DEPS)
for iword in isent[WORDS]:
iword[-1].clear()
return (a_rels, a_parses)
def _preprocess_rels(self, a_rels):
"""Preprocess input relations.
Args:
a_rels (list):
input relations to be preprocessed
Returns:
(void):
modifies ``a_rels`` in place
"""
arg1 = arg2 = None
for irel in a_rels:
arg1 = irel[ARG1]
arg1.pop(CHAR_SPAN, None)
arg1.pop(RAW_TEXT, None)
arg2 = irel[ARG2]
arg2.pop(CHAR_SPAN, None)
arg2.pop(RAW_TEXT, None)
<|code_end|>
. Use current file imports:
from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys
and context (classes, functions, or code) from other files:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | if len(irel[CONNECTIVE][TOK_LIST]) == 0: |
Using the snippet: <|code_start|> relation in question
Returns:
(void)
"""
conn = a_rel[CONNECTIVE]
conn_txt = conn.get(RAW_TEXT, None)
if conn_txt is not None:
if not conn.get(TOK_LIST, None):
rel = IMPLICIT
elif self._normalize_conn(conn_txt) in self.econn:
rel = EXPLICIT
else:
rel = ALT_LEX
else:
rel = IMPLICIT
return rel
def _normalize_tok_list(self, a_tok_list):
"""Flatten token list, only leaving doc offsets.
Args:
a_tok_list (list(list(int)):
relation in question
Returns:
(void)
"""
<|code_end|>
, determine the next line of code. You have imports:
from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys
and context (class names, function names, or code) available:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | return [el[TOK_OFFS_IDX] if isinstance(el, Iterable) else el |
Here is a snippet: <|code_start|> self.models.append(MajorSenser())
if a_type & WANG:
self.models.append(WangSenser(a_grid_search=a_grid_search))
if a_type & XGBOOST:
self.models.append(XGBoostSenser(a_grid_search=a_grid_search))
# NN models have to go last, since we are pruning the parses for them
# to free some memory
nn_used = False
if a_type & SVD:
# since we cannot differentiate SVD yet, we can only use word2vec
# embeddings
if not a_w2v or a_lstsq:
print("SVD senser does not support task-specific embeddings "
"and least squares yet.", file=sys.stderr)
self.models.append(SVDSenser(a_w2v=True, a_lstsq=False,
a_max_iters=256))
nn_used = True
if a_type & LSTM:
self.models.append(LSTMSenser(a_w2v, a_lstsq))
nn_used = True
# remember all possible senses
n_senses = 0
for irel in chain(a_train_data[0], a_dev_data[0]
if a_dev_data is not None else []):
for isense in irel[SENSE]:
isense = SHORT2FULL.get(isense, isense)
if isense not in self.cls2idx:
n_senses = len(self.cls2idx)
self.cls2idx[isense] = n_senses
self.idx2cls[n_senses] = isense
<|code_end|>
. Write the next line using the current file imports:
from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys
and context from other files:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
, which may include functions, classes, or code. Output only the next line. | if irel[TYPE] == EXPLICIT: |
Predict the next line after this snippet: <|code_start|> meta-classifier
cls2idx (dict):
mapping from class to index
idx2cls (dict):
mapping from index to class
econn (set):
connectives marking explicit relations
"""
def __init__(self, a_model=None):
"""
Class constructor.
Args:
a_model (str or None): path to serialized model or None
"""
self.models = []
self.model_paths = []
self.judge = None
self.cls2idx = {}
self.idx2cls = {}
self.wbench = None
self.econn = set([self._normalize_conn(iconn) for iconn in DFLT_CONN])
# load serialized model
if a_model is not None:
self._load(a_model)
def train(self, a_train_data, a_type=DFLT_MODEL_TYPE,
<|code_end|>
using the current file's imports:
from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys
and any relevant context from other files:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | a_path=DFLT_MODEL_PATH, a_dev_data=None, |
Given the code snippet: <|code_start|> judge (dsenser.Judge):
meta-classifier
cls2idx (dict):
mapping from class to index
idx2cls (dict):
mapping from index to class
econn (set):
connectives marking explicit relations
"""
def __init__(self, a_model=None):
"""
Class constructor.
Args:
a_model (str or None): path to serialized model or None
"""
self.models = []
self.model_paths = []
self.judge = None
self.cls2idx = {}
self.idx2cls = {}
self.wbench = None
self.econn = set([self._normalize_conn(iconn) for iconn in DFLT_CONN])
# load serialized model
if a_model is not None:
self._load(a_model)
<|code_end|>
, generate the next line using the imports in this file:
from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys
and context (functions, classes, or occasionally code) from other files:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | def train(self, a_train_data, a_type=DFLT_MODEL_TYPE, |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
"""Module providing class for sense disambiguation of connectives.
Attributes:
DiscourseSenser (class): class for sense disambiguation of connectives
"""
##################################################################
# Imports
from __future__ import absolute_import, print_function, unicode_literals
##################################################################
# Variables and Constants
# load default explicit discourse connectives
DFLT_CONN = set(["upon"])
<|code_end|>
, predict the immediate next line with the help of imports:
from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys
and context (classes, functions, sometimes code) from other files:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | with codecs.open(DFLT_ECONN_PATH, 'r', ENCODING) as ifile: |
Next line prediction: <|code_start|> """
n_senses = len(self.cls2idx)
isense = isenses = vsense = None
for irel in a_rels:
isenses = irel[SENSE]
vsense = np.zeros(n_senses)
for isense in isenses:
isense = SHORT2FULL.get(isense, isense)
vsense[self.cls2idx[isense]] = 1
irel[SENSE] = vsense / sum(vsense)
def _get_type(self, a_rel):
"""Determine type of discourse relation.
Args:
a_rel (dict):
relation in question
Returns:
(void)
"""
conn = a_rel[CONNECTIVE]
conn_txt = conn.get(RAW_TEXT, None)
if conn_txt is not None:
if not conn.get(TOK_LIST, None):
rel = IMPLICIT
elif self._normalize_conn(conn_txt) in self.econn:
rel = EXPLICIT
else:
<|code_end|>
. Use current file imports:
(from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys)
and context including class names, function names, or small code snippets from other files:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | rel = ALT_LEX |
Predict the next line after this snippet: <|code_start|> self.models.append(MajorSenser())
if a_type & WANG:
self.models.append(WangSenser(a_grid_search=a_grid_search))
if a_type & XGBOOST:
self.models.append(XGBoostSenser(a_grid_search=a_grid_search))
# NN models have to go last, since we are pruning the parses for them
# to free some memory
nn_used = False
if a_type & SVD:
# since we cannot differentiate SVD yet, we can only use word2vec
# embeddings
if not a_w2v or a_lstsq:
print("SVD senser does not support task-specific embeddings "
"and least squares yet.", file=sys.stderr)
self.models.append(SVDSenser(a_w2v=True, a_lstsq=False,
a_max_iters=256))
nn_used = True
if a_type & LSTM:
self.models.append(LSTMSenser(a_w2v, a_lstsq))
nn_used = True
# remember all possible senses
n_senses = 0
for irel in chain(a_train_data[0], a_dev_data[0]
if a_dev_data is not None else []):
for isense in irel[SENSE]:
isense = SHORT2FULL.get(isense, isense)
if isense not in self.cls2idx:
n_senses = len(self.cls2idx)
self.cls2idx[isense] = n_senses
self.idx2cls[n_senses] = isense
<|code_end|>
using the current file's imports:
from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys
and any relevant context from other files:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | if irel[TYPE] == EXPLICIT: |
Based on the snippet: <|code_start|>
Note:
updates ``a_rels`` in place
"""
n_senses = len(self.cls2idx)
isense = isenses = vsense = None
for irel in a_rels:
isenses = irel[SENSE]
vsense = np.zeros(n_senses)
for isense in isenses:
isense = SHORT2FULL.get(isense, isense)
vsense[self.cls2idx[isense]] = 1
irel[SENSE] = vsense / sum(vsense)
def _get_type(self, a_rel):
"""Determine type of discourse relation.
Args:
a_rel (dict):
relation in question
Returns:
(void)
"""
conn = a_rel[CONNECTIVE]
conn_txt = conn.get(RAW_TEXT, None)
if conn_txt is not None:
if not conn.get(TOK_LIST, None):
<|code_end|>
, predict the immediate next line with the help of imports:
from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys
and context (classes, functions, sometimes code) from other files:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | rel = IMPLICIT |
Predict the next line after this snippet: <|code_start|> a_type (str):
type of the model to be trained
a_dev_data (list or None):
development set
a_grid_search (bool):
use grid search in order to determine hyper-paramaters of
the model
a_w2v (bool):
use word2vec embeddings
a_lstsq (bool):
use least squares method
Returns:
void:
"""
if a_type == 0:
raise RuntimeError("No model type specified.")
if a_dev_data is None:
a_dev_data = ([], {})
# initialize models
if a_type & MJR:
self.models.append(MajorSenser())
if a_type & WANG:
self.models.append(WangSenser(a_grid_search=a_grid_search))
if a_type & XGBOOST:
self.models.append(XGBoostSenser(a_grid_search=a_grid_search))
# NN models have to go last, since we are pruning the parses for them
# to free some memory
nn_used = False
<|code_end|>
using the current file's imports:
from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys
and any relevant context from other files:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | if a_type & SVD: |
Given the following code snippet before the placeholder: <|code_start|> a_lstsq (bool):
use least squares method
Returns:
void:
"""
if a_type == 0:
raise RuntimeError("No model type specified.")
if a_dev_data is None:
a_dev_data = ([], {})
# initialize models
if a_type & MJR:
self.models.append(MajorSenser())
if a_type & WANG:
self.models.append(WangSenser(a_grid_search=a_grid_search))
if a_type & XGBOOST:
self.models.append(XGBoostSenser(a_grid_search=a_grid_search))
# NN models have to go last, since we are pruning the parses for them
# to free some memory
nn_used = False
if a_type & SVD:
# since we cannot differentiate SVD yet, we can only use word2vec
# embeddings
if not a_w2v or a_lstsq:
print("SVD senser does not support task-specific embeddings "
"and least squares yet.", file=sys.stderr)
self.models.append(SVDSenser(a_w2v=True, a_lstsq=False,
a_max_iters=256))
nn_used = True
<|code_end|>
, predict the next line using imports from the current file:
from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys
and context including class names, function names, and sometimes code from other files:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | if a_type & LSTM: |
Given the code snippet: <|code_start|> a_path=DFLT_MODEL_PATH, a_dev_data=None,
a_grid_search=False, a_w2v=False, a_lstsq=False):
"""Train specified model(s) on the provided data.
Args:
a_train_data (list or None):
training set
a_path (str):
path for storing the model
a_type (str):
type of the model to be trained
a_dev_data (list or None):
development set
a_grid_search (bool):
use grid search in order to determine hyper-paramaters of
the model
a_w2v (bool):
use word2vec embeddings
a_lstsq (bool):
use least squares method
Returns:
void:
"""
if a_type == 0:
raise RuntimeError("No model type specified.")
if a_dev_data is None:
a_dev_data = ([], {})
# initialize models
<|code_end|>
, generate the next line using the imports in this file:
from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys
and context (functions, classes, or occasionally code) from other files:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | if a_type & MJR: |
Based on the snippet: <|code_start|> """Train specified model(s) on the provided data.
Args:
a_train_data (list or None):
training set
a_path (str):
path for storing the model
a_type (str):
type of the model to be trained
a_dev_data (list or None):
development set
a_grid_search (bool):
use grid search in order to determine hyper-paramaters of
the model
a_w2v (bool):
use word2vec embeddings
a_lstsq (bool):
use least squares method
Returns:
void:
"""
if a_type == 0:
raise RuntimeError("No model type specified.")
if a_dev_data is None:
a_dev_data = ([], {})
# initialize models
if a_type & MJR:
self.models.append(MajorSenser())
<|code_end|>
, predict the immediate next line with the help of imports:
from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys
and context (classes, functions, sometimes code) from other files:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | if a_type & WANG: |
Here is a snippet: <|code_start|> Args:
a_train_data (list or None):
training set
a_path (str):
path for storing the model
a_type (str):
type of the model to be trained
a_dev_data (list or None):
development set
a_grid_search (bool):
use grid search in order to determine hyper-paramaters of
the model
a_w2v (bool):
use word2vec embeddings
a_lstsq (bool):
use least squares method
Returns:
void:
"""
if a_type == 0:
raise RuntimeError("No model type specified.")
if a_dev_data is None:
a_dev_data = ([], {})
# initialize models
if a_type & MJR:
self.models.append(MajorSenser())
if a_type & WANG:
self.models.append(WangSenser(a_grid_search=a_grid_search))
<|code_end|>
. Write the next line using the current file imports:
from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys
and context from other files:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
, which may include functions, classes, or code. Output only the next line. | if a_type & XGBOOST: |
Here is a snippet: <|code_start|>
def _prune_data(self, a_rels, a_parses):
"""Remove unnecessary information from data.
Args:
a_rels (list):
list of input discourse relations
a_parses (dict):
parse trees
Returns:
2-tuple(list, dict):
abridged input data
"""
arg = None
# clean-up relations
for irel in a_rels:
irel.pop("ID")
irel[CONNECTIVE].pop(CHAR_SPAN)
arg = irel[ARG1]
arg.pop(CHAR_SPAN)
arg.pop(RAW_TEXT)
arg = irel[ARG2]
arg.pop(CHAR_SPAN)
arg.pop(RAW_TEXT)
# clean-up parses
w_attrs = None
for isentences in a_parses.itervalues():
for isent in isentences[SENTENCES]:
<|code_end|>
. Write the next line using the current file imports:
from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys
and context from other files:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
, which may include functions, classes, or code. Output only the next line. | isent.pop(PARSE_TREE) |
Continue the code snippet: <|code_start|> def _prune_data(self, a_rels, a_parses):
"""Remove unnecessary information from data.
Args:
a_rels (list):
list of input discourse relations
a_parses (dict):
parse trees
Returns:
2-tuple(list, dict):
abridged input data
"""
arg = None
# clean-up relations
for irel in a_rels:
irel.pop("ID")
irel[CONNECTIVE].pop(CHAR_SPAN)
arg = irel[ARG1]
arg.pop(CHAR_SPAN)
arg.pop(RAW_TEXT)
arg = irel[ARG2]
arg.pop(CHAR_SPAN)
arg.pop(RAW_TEXT)
# clean-up parses
w_attrs = None
for isentences in a_parses.itervalues():
for isent in isentences[SENTENCES]:
isent.pop(PARSE_TREE)
<|code_end|>
. Use current file imports:
from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys
and context (classes, functions, or code) from other files:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | isent.pop(DEPS) |
Using the snippet: <|code_start|> """Remove unnecessary information from data.
Args:
a_rels (list):
list of input discourse relations
a_parses (dict):
parse trees
Returns:
2-tuple(list, dict):
abridged input data
"""
arg = None
# clean-up relations
for irel in a_rels:
irel.pop("ID")
irel[CONNECTIVE].pop(CHAR_SPAN)
arg = irel[ARG1]
arg.pop(CHAR_SPAN)
arg.pop(RAW_TEXT)
arg = irel[ARG2]
arg.pop(CHAR_SPAN)
arg.pop(RAW_TEXT)
# clean-up parses
w_attrs = None
for isentences in a_parses.itervalues():
for isent in isentences[SENTENCES]:
isent.pop(PARSE_TREE)
isent.pop(DEPS)
<|code_end|>
, determine the next line of code. You have imports:
from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys
and context (class names, function names, or code) available:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | for iword in isent[WORDS]: |
Predict the next line after this snippet: <|code_start|> return self.wbench
def _prune_data(self, a_rels, a_parses):
"""Remove unnecessary information from data.
Args:
a_rels (list):
list of input discourse relations
a_parses (dict):
parse trees
Returns:
2-tuple(list, dict):
abridged input data
"""
arg = None
# clean-up relations
for irel in a_rels:
irel.pop("ID")
irel[CONNECTIVE].pop(CHAR_SPAN)
arg = irel[ARG1]
arg.pop(CHAR_SPAN)
arg.pop(RAW_TEXT)
arg = irel[ARG2]
arg.pop(CHAR_SPAN)
arg.pop(RAW_TEXT)
# clean-up parses
w_attrs = None
for isentences in a_parses.itervalues():
<|code_end|>
using the current file's imports:
from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys
and any relevant context from other files:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | for isent in isentences[SENTENCES]: |
Given snippet: <|code_start|> raise RuntimeError("No model type specified.")
if a_dev_data is None:
a_dev_data = ([], {})
# initialize models
if a_type & MJR:
self.models.append(MajorSenser())
if a_type & WANG:
self.models.append(WangSenser(a_grid_search=a_grid_search))
if a_type & XGBOOST:
self.models.append(XGBoostSenser(a_grid_search=a_grid_search))
# NN models have to go last, since we are pruning the parses for them
# to free some memory
nn_used = False
if a_type & SVD:
# since we cannot differentiate SVD yet, we can only use word2vec
# embeddings
if not a_w2v or a_lstsq:
print("SVD senser does not support task-specific embeddings "
"and least squares yet.", file=sys.stderr)
self.models.append(SVDSenser(a_w2v=True, a_lstsq=False,
a_max_iters=256))
nn_used = True
if a_type & LSTM:
self.models.append(LSTMSenser(a_w2v, a_lstsq))
nn_used = True
# remember all possible senses
n_senses = 0
for irel in chain(a_train_data[0], a_dev_data[0]
if a_dev_data is not None else []):
for isense in irel[SENSE]:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from dsenser.constants import ARG1, ARG2, CHAR_SPAN, CONNECTIVE, ENCODING, \
RAW_TEXT, SENSE, TOK_LIST, TOK_OFFS_IDX, TYPE, DFLT_MODEL_PATH, \
DFLT_MODEL_TYPE, DFLT_ECONN_PATH, ALT_LEX, EXPLICIT, IMPLICIT, SVD, \
LSTM, MJR, WANG, XGBOOST, PARSE_TREE, DEPS, WORDS, SENTENCES, SHORT2FULL
from dsenser.utils import timeit
from collections import Iterable
from cPickle import dump, load
from itertools import chain
from dsenser.major import MajorSenser
from dsenser.wang import WangSenser
from dsenser.xgboost import XGBoostSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
from dsenser.svd import SVDSenser
from dsenser.lstm import LSTMSenser
import codecs
import gc
import numpy as np
import os
import sys
and context:
# Path: dsenser/constants.py
# ARG1 = "Arg1"
#
# ARG2 = "Arg2"
#
# CHAR_SPAN = "CharacterSpanList"
#
# CONNECTIVE = "Connective"
#
# ENCODING = "utf-8"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# TOK_LIST = "TokenList"
#
# TOK_OFFS_IDX = 2
#
# TYPE = "Type"
#
# DFLT_MODEL_PATH = os.path.join(MODEL_DIR, "pdtb.sense.model")
#
# DFLT_MODEL_TYPE = WANG
#
# DFLT_ECONN_PATH = os.path.join(ECONN_DIR, "ExpConn.txt")
#
# ALT_LEX = "AltLex"
#
# EXPLICIT = "Explicit"
#
# IMPLICIT = "Implicit"
#
# SVD = 1
#
# LSTM = 2
#
# MJR = 4
#
# WANG = 8
#
# XGBOOST = 16
#
# PARSE_TREE = "parsetree"
#
# DEPS = "dependencies"
#
# WORDS = "words"
#
# SENTENCES = "sentences"
#
# SHORT2FULL = {"Expansion": "Expansion.Conjunction",
# "Comparison": "Comparison.Contrast",
# "Comparison.COntrast": "Comparison.Contrast"}
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
which might include code, classes, or functions. Output only the next line. | isense = SHORT2FULL.get(isense, isense) |
Using the snippet: <|code_start|> str: normalized connective
"""
a_conn = a_conn.strip().lower()
if a_conn:
return CHM.map_raw_connective(a_conn)[0]
return a_conn
def _get_toks_pos(self, a_parses, a_rel, a_arg):
"""Method for getting raw tokens with their parts of speech.
Args:
a_parses (dict):
parsed sentences
a_rel (dict):
discourse relation whose tokens should be obtained
a_arg (str):
relation argument to obtain senses for
Returns:
list: list of tokens and their parts of speech
"""
ret = []
snt = wrd = None
for s_id, w_ids in \
self._get_snt2tok(a_rel[a_arg][TOK_LIST]).iteritems():
snt = a_parses[s_id][WORDS]
for w_id in w_ids:
wrd = snt[w_id]
<|code_end|>
, determine the next line of code. You have imports:
from dsenser.constants import POS, SNT_ID, TOK_IDX, TOK_ID, TOK_LIST, WORDS
from dsenser.scorer.conn_head_mapper import ConnHeadMapper
from dsenser.resources import CHM
from dsenser.utils import is_explicit
from collections import defaultdict
and context (class names, function names, or code) available:
# Path: dsenser/constants.py
# POS = "PartOfSpeech"
#
# SNT_ID = 3
#
# TOK_IDX = 0
#
# TOK_ID = 4
#
# TOK_LIST = "TokenList"
#
# WORDS = "words"
#
# Path: dsenser/resources.py
# CHM = ConnHeadMapper()
#
# Path: dsenser/utils.py
# def is_explicit(a_rel):
# """Check whether given relation is explicit.
#
# Args:
# a_rel (dict):
# discourse relation to classify
#
# Returns:
# bool:
# ``True`` if the relation is explicit, ``False`` otherwise
#
# """
# return bool(a_rel[CONNECTIVE][TOK_LIST])
. Output only the next line. | ret.append((wrd[TOK_IDX].lower(), wrd[1].get(POS))) |
Predict the next line after this snippet: <|code_start|> relation argument to obtain senses for
Returns:
list: list of tokens and their parts of speech
"""
ret = []
snt = wrd = None
for s_id, w_ids in \
self._get_snt2tok(a_rel[a_arg][TOK_LIST]).iteritems():
snt = a_parses[s_id][WORDS]
for w_id in w_ids:
wrd = snt[w_id]
ret.append((wrd[TOK_IDX].lower(), wrd[1].get(POS)))
return ret
def _get_snt2tok(self, a_tok_list):
"""Generate mapping from sentence indices to token lists.
Args:
a_tok_list (list):
list of sentence and token indices pertaining to the argument
Returns:
defaultdict:
mapping from sentence indices to token lists
"""
snt2tok_pos = defaultdict(set)
for el in a_tok_list:
<|code_end|>
using the current file's imports:
from dsenser.constants import POS, SNT_ID, TOK_IDX, TOK_ID, TOK_LIST, WORDS
from dsenser.scorer.conn_head_mapper import ConnHeadMapper
from dsenser.resources import CHM
from dsenser.utils import is_explicit
from collections import defaultdict
and any relevant context from other files:
# Path: dsenser/constants.py
# POS = "PartOfSpeech"
#
# SNT_ID = 3
#
# TOK_IDX = 0
#
# TOK_ID = 4
#
# TOK_LIST = "TokenList"
#
# WORDS = "words"
#
# Path: dsenser/resources.py
# CHM = ConnHeadMapper()
#
# Path: dsenser/utils.py
# def is_explicit(a_rel):
# """Check whether given relation is explicit.
#
# Args:
# a_rel (dict):
# discourse relation to classify
#
# Returns:
# bool:
# ``True`` if the relation is explicit, ``False`` otherwise
#
# """
# return bool(a_rel[CONNECTIVE][TOK_LIST])
. Output only the next line. | snt_id = el[SNT_ID] |
Using the snippet: <|code_start|> str: normalized connective
"""
a_conn = a_conn.strip().lower()
if a_conn:
return CHM.map_raw_connective(a_conn)[0]
return a_conn
def _get_toks_pos(self, a_parses, a_rel, a_arg):
"""Method for getting raw tokens with their parts of speech.
Args:
a_parses (dict):
parsed sentences
a_rel (dict):
discourse relation whose tokens should be obtained
a_arg (str):
relation argument to obtain senses for
Returns:
list: list of tokens and their parts of speech
"""
ret = []
snt = wrd = None
for s_id, w_ids in \
self._get_snt2tok(a_rel[a_arg][TOK_LIST]).iteritems():
snt = a_parses[s_id][WORDS]
for w_id in w_ids:
wrd = snt[w_id]
<|code_end|>
, determine the next line of code. You have imports:
from dsenser.constants import POS, SNT_ID, TOK_IDX, TOK_ID, TOK_LIST, WORDS
from dsenser.scorer.conn_head_mapper import ConnHeadMapper
from dsenser.resources import CHM
from dsenser.utils import is_explicit
from collections import defaultdict
and context (class names, function names, or code) available:
# Path: dsenser/constants.py
# POS = "PartOfSpeech"
#
# SNT_ID = 3
#
# TOK_IDX = 0
#
# TOK_ID = 4
#
# TOK_LIST = "TokenList"
#
# WORDS = "words"
#
# Path: dsenser/resources.py
# CHM = ConnHeadMapper()
#
# Path: dsenser/utils.py
# def is_explicit(a_rel):
# """Check whether given relation is explicit.
#
# Args:
# a_rel (dict):
# discourse relation to classify
#
# Returns:
# bool:
# ``True`` if the relation is explicit, ``False`` otherwise
#
# """
# return bool(a_rel[CONNECTIVE][TOK_LIST])
. Output only the next line. | ret.append((wrd[TOK_IDX].lower(), wrd[1].get(POS))) |
Predict the next line after this snippet: <|code_start|>
Returns:
list: list of tokens and their parts of speech
"""
ret = []
snt = wrd = None
for s_id, w_ids in \
self._get_snt2tok(a_rel[a_arg][TOK_LIST]).iteritems():
snt = a_parses[s_id][WORDS]
for w_id in w_ids:
wrd = snt[w_id]
ret.append((wrd[TOK_IDX].lower(), wrd[1].get(POS)))
return ret
def _get_snt2tok(self, a_tok_list):
"""Generate mapping from sentence indices to token lists.
Args:
a_tok_list (list):
list of sentence and token indices pertaining to the argument
Returns:
defaultdict:
mapping from sentence indices to token lists
"""
snt2tok_pos = defaultdict(set)
for el in a_tok_list:
snt_id = el[SNT_ID]
<|code_end|>
using the current file's imports:
from dsenser.constants import POS, SNT_ID, TOK_IDX, TOK_ID, TOK_LIST, WORDS
from dsenser.scorer.conn_head_mapper import ConnHeadMapper
from dsenser.resources import CHM
from dsenser.utils import is_explicit
from collections import defaultdict
and any relevant context from other files:
# Path: dsenser/constants.py
# POS = "PartOfSpeech"
#
# SNT_ID = 3
#
# TOK_IDX = 0
#
# TOK_ID = 4
#
# TOK_LIST = "TokenList"
#
# WORDS = "words"
#
# Path: dsenser/resources.py
# CHM = ConnHeadMapper()
#
# Path: dsenser/utils.py
# def is_explicit(a_rel):
# """Check whether given relation is explicit.
#
# Args:
# a_rel (dict):
# discourse relation to classify
#
# Returns:
# bool:
# ``True`` if the relation is explicit, ``False`` otherwise
#
# """
# return bool(a_rel[CONNECTIVE][TOK_LIST])
. Output only the next line. | snt2tok_pos[snt_id].add(el[TOK_ID]) |
Given snippet: <|code_start|> a_conn (str):
connectve to be normalized
Returns:
str: normalized connective
"""
a_conn = a_conn.strip().lower()
if a_conn:
return CHM.map_raw_connective(a_conn)[0]
return a_conn
def _get_toks_pos(self, a_parses, a_rel, a_arg):
"""Method for getting raw tokens with their parts of speech.
Args:
a_parses (dict):
parsed sentences
a_rel (dict):
discourse relation whose tokens should be obtained
a_arg (str):
relation argument to obtain senses for
Returns:
list: list of tokens and their parts of speech
"""
ret = []
snt = wrd = None
for s_id, w_ids in \
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from dsenser.constants import POS, SNT_ID, TOK_IDX, TOK_ID, TOK_LIST, WORDS
from dsenser.scorer.conn_head_mapper import ConnHeadMapper
from dsenser.resources import CHM
from dsenser.utils import is_explicit
from collections import defaultdict
and context:
# Path: dsenser/constants.py
# POS = "PartOfSpeech"
#
# SNT_ID = 3
#
# TOK_IDX = 0
#
# TOK_ID = 4
#
# TOK_LIST = "TokenList"
#
# WORDS = "words"
#
# Path: dsenser/resources.py
# CHM = ConnHeadMapper()
#
# Path: dsenser/utils.py
# def is_explicit(a_rel):
# """Check whether given relation is explicit.
#
# Args:
# a_rel (dict):
# discourse relation to classify
#
# Returns:
# bool:
# ``True`` if the relation is explicit, ``False`` otherwise
#
# """
# return bool(a_rel[CONNECTIVE][TOK_LIST])
which might include code, classes, or functions. Output only the next line. | self._get_snt2tok(a_rel[a_arg][TOK_LIST]).iteritems(): |
Predict the next line for this snippet: <|code_start|> connectve to be normalized
Returns:
str: normalized connective
"""
a_conn = a_conn.strip().lower()
if a_conn:
return CHM.map_raw_connective(a_conn)[0]
return a_conn
def _get_toks_pos(self, a_parses, a_rel, a_arg):
"""Method for getting raw tokens with their parts of speech.
Args:
a_parses (dict):
parsed sentences
a_rel (dict):
discourse relation whose tokens should be obtained
a_arg (str):
relation argument to obtain senses for
Returns:
list: list of tokens and their parts of speech
"""
ret = []
snt = wrd = None
for s_id, w_ids in \
self._get_snt2tok(a_rel[a_arg][TOK_LIST]).iteritems():
<|code_end|>
with the help of current file imports:
from dsenser.constants import POS, SNT_ID, TOK_IDX, TOK_ID, TOK_LIST, WORDS
from dsenser.scorer.conn_head_mapper import ConnHeadMapper
from dsenser.resources import CHM
from dsenser.utils import is_explicit
from collections import defaultdict
and context from other files:
# Path: dsenser/constants.py
# POS = "PartOfSpeech"
#
# SNT_ID = 3
#
# TOK_IDX = 0
#
# TOK_ID = 4
#
# TOK_LIST = "TokenList"
#
# WORDS = "words"
#
# Path: dsenser/resources.py
# CHM = ConnHeadMapper()
#
# Path: dsenser/utils.py
# def is_explicit(a_rel):
# """Check whether given relation is explicit.
#
# Args:
# a_rel (dict):
# discourse relation to classify
#
# Returns:
# bool:
# ``True`` if the relation is explicit, ``False`` otherwise
#
# """
# return bool(a_rel[CONNECTIVE][TOK_LIST])
, which may contain function names, class names, or code. Output only the next line. | snt = a_parses[s_id][WORDS] |
Here is a snippet: <|code_start|> tuple:
trainings set with explicit and implicit connectives
"""
if not a_ds:
return (([], {}), ([], {}))
explicit_instances = []
implicit_instances = []
for i, irel in enumerate(a_ds[0]):
if is_explicit(irel):
explicit_instances.append((i, irel))
else:
implicit_instances.append((i, irel))
ret = ((explicit_instances, a_ds[1]),
(implicit_instances, a_ds[1]))
return ret
def _normalize_conn(self, a_conn):
"""Normalize connective form.
Args:
a_conn (str):
connectve to be normalized
Returns:
str: normalized connective
"""
a_conn = a_conn.strip().lower()
if a_conn:
<|code_end|>
. Write the next line using the current file imports:
from dsenser.constants import POS, SNT_ID, TOK_IDX, TOK_ID, TOK_LIST, WORDS
from dsenser.scorer.conn_head_mapper import ConnHeadMapper
from dsenser.resources import CHM
from dsenser.utils import is_explicit
from collections import defaultdict
and context from other files:
# Path: dsenser/constants.py
# POS = "PartOfSpeech"
#
# SNT_ID = 3
#
# TOK_IDX = 0
#
# TOK_ID = 4
#
# TOK_LIST = "TokenList"
#
# WORDS = "words"
#
# Path: dsenser/resources.py
# CHM = ConnHeadMapper()
#
# Path: dsenser/utils.py
# def is_explicit(a_rel):
# """Check whether given relation is explicit.
#
# Args:
# a_rel (dict):
# discourse relation to classify
#
# Returns:
# bool:
# ``True`` if the relation is explicit, ``False`` otherwise
#
# """
# return bool(a_rel[CONNECTIVE][TOK_LIST])
, which may include functions, classes, or code. Output only the next line. | return CHM.map_raw_connective(a_conn)[0] |
Using the snippet: <|code_start|> Returns:
void:
Note:
modifies ``a_ret`` in place
"""
for i, irel in enumerate(a_rels):
self.predict(irel, a_data, a_ret, i)
def predict(self, a_rel, a_data, a_ret, a_i):
"""Method for predicting sense of single relation.
Args:
a_rel (dict):
discourse relation whose sense should be predicted
a_data (2-tuple(dict, dict)):
list of input JSON data
a_ret (np.array):
output prediction vector
a_i (int):
row index in the output vector
Returns:
void:
Note:
modifies ``a_ret[a_i]`` in place
"""
<|code_end|>
, determine the next line of code. You have imports:
from dsenser.constants import POS, SNT_ID, TOK_IDX, TOK_ID, TOK_LIST, WORDS
from dsenser.scorer.conn_head_mapper import ConnHeadMapper
from dsenser.resources import CHM
from dsenser.utils import is_explicit
from collections import defaultdict
and context (class names, function names, or code) available:
# Path: dsenser/constants.py
# POS = "PartOfSpeech"
#
# SNT_ID = 3
#
# TOK_IDX = 0
#
# TOK_ID = 4
#
# TOK_LIST = "TokenList"
#
# WORDS = "words"
#
# Path: dsenser/resources.py
# CHM = ConnHeadMapper()
#
# Path: dsenser/utils.py
# def is_explicit(a_rel):
# """Check whether given relation is explicit.
#
# Args:
# a_rel (dict):
# discourse relation to classify
#
# Returns:
# bool:
# ``True`` if the relation is explicit, ``False`` otherwise
#
# """
# return bool(a_rel[CONNECTIVE][TOK_LIST])
. Output only the next line. | if is_explicit(a_rel): |
Next line prediction: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
"""Module providing class for SVD sense disambiguation.
Attributes:
SVDExplicitSenser (class):
class that predicts senses of explicit relations
"""
##################################################################
# Imports
from __future__ import absolute_import, print_function
##################################################################
# Variables and Constants
##################################################################
# Methods
##################################################################
# Class
<|code_end|>
. Use current file imports:
(from dsenser.svd.svdbase import SVDBaseSenser
from dsenser.utils import timeit)
and context including class names, function names, or small code snippets from other files:
# Path: dsenser/svd/svdbase.py
# class SVDBaseSenser(NNBaseSenser):
# """Abstract class for disambiguating relation senses.
#
# Attributes:
# n_y (int): number of distinct classes
#
# """
#
# def _init_nn(self):
# """Initialize neural network.
#
# """
# self.intm_dim = max(MIN_DIM, self.ndim - (self.ndim - self.n_y) / 2)
# # indices of word embeddings
# self.W_INDICES_ARG1 = TT.ivector(name="W_INDICES_ARG1")
# self.W_INDICES_ARG2 = TT.ivector(name="W_INDICES_ARG2")
# # connective's index
# self.CONN_INDEX = TT.iscalar(name="CONN_INDEX")
# # initialize the matrix of word embeddings
# self.init_w_emb()
# # word embeddings of the arguments
# self.EMB_ARG1 = self.W_EMB[self.W_INDICES_ARG1]
# self.EMB_ARG2 = self.W_EMB[self.W_INDICES_ARG2]
# # connective's embedding
# self._init_conn_emb()
# self.EMB_CONN = self.CONN_EMB[self.CONN_INDEX]
# # perform matrix decomposition
# _, _, self.ARG1 = TT.nlinalg.svd(self.EMB_ARG1,
# full_matrices=True)
# _, _, self.ARG2 = TT.nlinalg.svd(self.EMB_ARG2,
# full_matrices=True)
# self.ARG_DIFF = self.ARG1 - self.ARG2
# # map decomposed matrices to the intermediate level
# self.ARG_DIFF2I = theano.shared(value=HE_UNIFORM((self.ndim, 1)),
# name="ARG_DIFF2I")
# self.arg_diff_bias = theano.shared(value=HE_UNIFORM((1, self.ndim)),
# name="arg_diff_bias")
# self._params.extend([self.ARG_DIFF2I, self.arg_diff_bias])
# self.ARGS = (TT.dot(self.ARG_DIFF, self.ARG_DIFF2I).T +
# self.arg_diff_bias).flatten()
# # define final units
# self.I = TT.concatenate((self.ARGS, self.EMB_CONN))
# self.I2Y = theano.shared(value=HE_UNIFORM((self.n_y,
# self.ndim + self.intm_dim)),
# name="I2Y")
# self.y_bias = theano.shared(value=HE_UNIFORM((1, self.n_y)),
# name="y_bias")
# self._params.extend([self.I2Y, self.y_bias])
# self.Y_pred = TT.nnet.softmax(TT.dot(self.I2Y, self.I).T + self.y_bias)
# # initialize cost and optimization functions
# self.Y_gold = TT.vector(name="Y_gold")
# self._cost = TT.sum((self.Y_pred - self.Y_gold) ** 2)
# self._dev_cost = TT.sum((self.Y_pred - self.Y_gold) ** 2)
# self._pred_class = TT.argmax(self.Y_pred)
# grads = TT.grad(self._cost, wrt=self._params)
# self._init_funcs(grads)
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | class SVDExplicitSenser(SVDBaseSenser): |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
"""Module providing class for SVD sense disambiguation.
Attributes:
SVDExplicitSenser (class):
class that predicts senses of explicit relations
"""
##################################################################
# Imports
from __future__ import absolute_import, print_function
##################################################################
# Variables and Constants
##################################################################
# Methods
##################################################################
# Class
class SVDExplicitSenser(SVDBaseSenser):
"""Class for SVD disambiguation of explicit discourse relations.
"""
<|code_end|>
, generate the next line using the imports in this file:
from dsenser.svd.svdbase import SVDBaseSenser
from dsenser.utils import timeit
and context (functions, classes, or occasionally code) from other files:
# Path: dsenser/svd/svdbase.py
# class SVDBaseSenser(NNBaseSenser):
# """Abstract class for disambiguating relation senses.
#
# Attributes:
# n_y (int): number of distinct classes
#
# """
#
# def _init_nn(self):
# """Initialize neural network.
#
# """
# self.intm_dim = max(MIN_DIM, self.ndim - (self.ndim - self.n_y) / 2)
# # indices of word embeddings
# self.W_INDICES_ARG1 = TT.ivector(name="W_INDICES_ARG1")
# self.W_INDICES_ARG2 = TT.ivector(name="W_INDICES_ARG2")
# # connective's index
# self.CONN_INDEX = TT.iscalar(name="CONN_INDEX")
# # initialize the matrix of word embeddings
# self.init_w_emb()
# # word embeddings of the arguments
# self.EMB_ARG1 = self.W_EMB[self.W_INDICES_ARG1]
# self.EMB_ARG2 = self.W_EMB[self.W_INDICES_ARG2]
# # connective's embedding
# self._init_conn_emb()
# self.EMB_CONN = self.CONN_EMB[self.CONN_INDEX]
# # perform matrix decomposition
# _, _, self.ARG1 = TT.nlinalg.svd(self.EMB_ARG1,
# full_matrices=True)
# _, _, self.ARG2 = TT.nlinalg.svd(self.EMB_ARG2,
# full_matrices=True)
# self.ARG_DIFF = self.ARG1 - self.ARG2
# # map decomposed matrices to the intermediate level
# self.ARG_DIFF2I = theano.shared(value=HE_UNIFORM((self.ndim, 1)),
# name="ARG_DIFF2I")
# self.arg_diff_bias = theano.shared(value=HE_UNIFORM((1, self.ndim)),
# name="arg_diff_bias")
# self._params.extend([self.ARG_DIFF2I, self.arg_diff_bias])
# self.ARGS = (TT.dot(self.ARG_DIFF, self.ARG_DIFF2I).T +
# self.arg_diff_bias).flatten()
# # define final units
# self.I = TT.concatenate((self.ARGS, self.EMB_CONN))
# self.I2Y = theano.shared(value=HE_UNIFORM((self.n_y,
# self.ndim + self.intm_dim)),
# name="I2Y")
# self.y_bias = theano.shared(value=HE_UNIFORM((1, self.n_y)),
# name="y_bias")
# self._params.extend([self.I2Y, self.y_bias])
# self.Y_pred = TT.nnet.softmax(TT.dot(self.I2Y, self.I).T + self.y_bias)
# # initialize cost and optimization functions
# self.Y_gold = TT.vector(name="Y_gold")
# self._cost = TT.sum((self.Y_pred - self.Y_gold) ** 2)
# self._dev_cost = TT.sum((self.Y_pred - self.Y_gold) ** 2)
# self._pred_class = TT.argmax(self.Y_pred)
# grads = TT.grad(self._cost, wrt=self._params)
# self._init_funcs(grads)
#
# Path: dsenser/utils.py
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | @timeit("Training explicit SVD classifier...") |
Next line prediction: <|code_start|>
Returns:
(void)
"""
return
# # divide training set into explicit and implicit relations
# exp_train, imp_train = self._divide_data(a_train)
# exp_dev, imp_dev = self._divide_data(a_dev)
# # train explicit judge
# self.explicit.train(exp_train, exp_dev)
# # train implicit judge
# self.implicit.train(imp_train, imp_dev)
def predict(self, a_rel, a_x):
"""Method for predicting sense of single relation.
Args:
a_rel (dict):
input relation to classify
a_x (np.array):
(submodels x class) array of input predictions
Returns:
str:
most probable sense of discourse relation
"""
ret = np.mean(a_x, axis=0)
return (np.argmax(ret), ret)
<|code_end|>
. Use current file imports:
(from dsenser.utils import is_explicit, timeit
import numpy as np)
and context including class names, function names, or small code snippets from other files:
# Path: dsenser/utils.py
# def is_explicit(a_rel):
# """Check whether given relation is explicit.
#
# Args:
# a_rel (dict):
# discourse relation to classify
#
# Returns:
# bool:
# ``True`` if the relation is explicit, ``False`` otherwise
#
# """
# return bool(a_rel[CONNECTIVE][TOK_LIST])
#
# class timeit(object):
# """Decorator class for measuring time performance.
#
# Attributes:
# msg (str): message to be printed on method invocation
#
# """
#
# def __init__(self, a_msg):
# """Class constructor.
#
# Args:
# a_msg (str): debug message to print
#
# """
# self.msg = a_msg
#
# def __call__(self, a_func):
# """Decorator function.
#
# Args:
# a_func (method): decorated method
#
# Returns:
# method: wrapped method
#
# """
# def _wrapper(*args, **kwargs):
# print(self.msg + " started", file=sys.stderr)
# start_time = datetime.utcnow()
# a_func(*args, **kwargs)
# end_time = datetime.utcnow()
# time_delta = (end_time - start_time).total_seconds()
# print(self.msg + " finished ({:.2f} sec)".format(time_delta),
# file=sys.stderr)
# return wraps(a_func)(_wrapper)
. Output only the next line. | if is_explicit(a_rel): |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import
##################################################################
# Constants
##################################################################
# Test Classes
class TestSVDExplict(TestCase):
def test_train(self):
with patch("dsenser.svd.svdbase.SVDBaseSenser.train",
autospec=True):
<|code_end|>
with the help of current file imports:
from dsenser.svd.explicit import SVDExplicitSenser
from mock import patch
from unittest import TestCase
import dsenser
and context from other files:
# Path: dsenser/svd/explicit.py
# class SVDExplicitSenser(SVDBaseSenser):
# """Class for SVD disambiguation of explicit discourse relations.
#
# """
#
# @timeit("Training explicit SVD classifier...")
# def train(self, *args, **kwargs):
# super(SVDExplicitSenser, self).train(*args, **kwargs)
, which may contain function names, class names, or code. Output only the next line. | svd = SVDExplicitSenser() |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import
##################################################################
# Constants
##################################################################
# Test Classes
class TestXGBoostExplict(TestCase):
def test_train(self):
with patch("dsenser.wang.wangbase.WangBaseSenser.train",
autospec=True):
<|code_end|>
. Use current file imports:
import dsenser
from dsenser.xgboost.explicit import XGBoostExplicitSenser
from mock import patch
from unittest import TestCase
and context (classes, functions, or code) from other files:
# Path: dsenser/xgboost/explicit.py
# class XGBoostExplicitSenser(XGBoostBaseSenser, WangExplicitSenser):
# """Subclass of explicit WangSenser using XGBoost.
#
# """
# PARAM_GRID = BASE_PARAM_GRID
# N_JOBS = BASE_N_JOBS
#
# @timeit("Training explicit XGBoost classifier...")
# def train(self, *args, **kwargs):
# super(WangExplicitSenser, self).train(*args, **kwargs)
. Output only the next line. | xgb = XGBoostExplicitSenser() |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import
##################################################################
# Constants
N = 10
MAX_I = 7
##################################################################
# Methods
def test_floatX_0():
<|code_end|>
, predict the next line using imports from the current file:
from dsenser.theano_utils import floatX, rmsprop
from copy import deepcopy
from theano import config, tensor as TT
import numpy as np
import theano
and context including class names, function names, and sometimes code from other files:
# Path: dsenser/theano_utils.py
# def floatX(a_data, a_dtype=config.floatX):
# """Return numpy array populated with the given data.
#
# Args:
# data (np.array):
# input tensor
# dtype (class):
# digit type
#
# Returns:
# np.array:
# array populated with the given data
#
# """
# return np.asarray(a_data, dtype=a_dtype)
#
# def rmsprop(tparams, grads, x, y, cost):
# """A variant of SGD that automatically scales the step size.
#
# Args:
# tpramas (Theano SharedVariable):
# Model parameters
# grads (Theano variable):
# Gradients of cost w.r.t to parameres
# x (list):
# Model inputs
# y (Theano variable):
# Targets
# cost (Theano variable):
# Objective fucntion to minimize
#
# Notes:
# For more information, see [Hint2014]_.
#
# .. [Hint2014] Geoff Hinton, *Neural Networks for Machine Learning*,
# lecture 6a,
# http://cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf
#
# """
# zipped_grads = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
# running_grads = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
# running_grads2 = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
#
# zgup = [(zg, g) for zg, g in zip(zipped_grads, grads)]
# rgup = [(rg, 0.95 * rg + 0.05 * g) for rg, g in zip(running_grads, grads)]
# rg2up = [(rg2, 0.95 * rg2 + 0.05 * (g ** 2))
# for rg2, g in zip(running_grads2, grads)]
#
# f_grad_shared = theano.function(x + [y], cost,
# updates=zgup + rgup + rg2up,
# name='rmsprop_f_grad_shared')
# updir = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
# updir_new = [(ud, 0.9 * ud - 1e-4 * zg / TT.sqrt(rg2 - rg ** 2 + 1e-4))
# for ud, zg, rg, rg2 in zip(updir, zipped_grads, running_grads,
# running_grads2)]
# param_up = [(p, p + udn[1])
# for p, udn in zip(tparams, updir_new)]
# f_update = theano.function([], [], updates=updir_new + param_up,
# on_unused_input='ignore',
# name='rmsprop_f_update')
# params = [zipped_grads, running_grads, running_grads2, updir]
# return (f_grad_shared, f_update, params)
. Output only the next line. | scalar = floatX(0) |
Using the snippet: <|code_start|>MAX_I = 7
##################################################################
# Methods
def test_floatX_0():
scalar = floatX(0)
assert scalar.dtype == config.floatX
assert isinstance(scalar, np.ndarray)
def test_floatX_1():
scalar = floatX(range(5))
assert scalar.dtype == config.floatX
assert isinstance(scalar, np.ndarray)
def test_rmsprop_0():
# input
x = TT.vector(name='x')
B = theano.shared(floatX(np.ones((3, 5))), name='B')
c = theano.shared(floatX(np.ones(3)), name='c')
params = [B, c]
# output
y_pred = TT.nnet.softmax(TT.dot(B, x.T).T + c)
y_gold = TT.vector(name="y_gold")
# cost and grads
cost = TT.sum((y_pred - y_gold)**2)
grads = TT.grad(cost, wrt=params)
# funcs
<|code_end|>
, determine the next line of code. You have imports:
from dsenser.theano_utils import floatX, rmsprop
from copy import deepcopy
from theano import config, tensor as TT
import numpy as np
import theano
and context (class names, function names, or code) available:
# Path: dsenser/theano_utils.py
# def floatX(a_data, a_dtype=config.floatX):
# """Return numpy array populated with the given data.
#
# Args:
# data (np.array):
# input tensor
# dtype (class):
# digit type
#
# Returns:
# np.array:
# array populated with the given data
#
# """
# return np.asarray(a_data, dtype=a_dtype)
#
# def rmsprop(tparams, grads, x, y, cost):
# """A variant of SGD that automatically scales the step size.
#
# Args:
# tpramas (Theano SharedVariable):
# Model parameters
# grads (Theano variable):
# Gradients of cost w.r.t to parameres
# x (list):
# Model inputs
# y (Theano variable):
# Targets
# cost (Theano variable):
# Objective fucntion to minimize
#
# Notes:
# For more information, see [Hint2014]_.
#
# .. [Hint2014] Geoff Hinton, *Neural Networks for Machine Learning*,
# lecture 6a,
# http://cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf
#
# """
# zipped_grads = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
# running_grads = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
# running_grads2 = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
#
# zgup = [(zg, g) for zg, g in zip(zipped_grads, grads)]
# rgup = [(rg, 0.95 * rg + 0.05 * g) for rg, g in zip(running_grads, grads)]
# rg2up = [(rg2, 0.95 * rg2 + 0.05 * (g ** 2))
# for rg2, g in zip(running_grads2, grads)]
#
# f_grad_shared = theano.function(x + [y], cost,
# updates=zgup + rgup + rg2up,
# name='rmsprop_f_grad_shared')
# updir = [theano.shared(p.get_value() * floatX(0.))
# for p in tparams]
# updir_new = [(ud, 0.9 * ud - 1e-4 * zg / TT.sqrt(rg2 - rg ** 2 + 1e-4))
# for ud, zg, rg, rg2 in zip(updir, zipped_grads, running_grads,
# running_grads2)]
# param_up = [(p, p + udn[1])
# for p, udn in zip(tparams, updir_new)]
# f_update = theano.function([], [], updates=updir_new + param_up,
# on_unused_input='ignore',
# name='rmsprop_f_update')
# params = [zipped_grads, running_grads, running_grads2, updir]
# return (f_grad_shared, f_update, params)
. Output only the next line. | cost_func, update_func, rms_params = rmsprop(params, grads, |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import
##################################################################
# Test Classes
class TestMajorSenser(TestCase):
@fixture(autouse=True)
def set_ds(self):
self.ds = MajorSenser()
def test_ms(self):
assert isinstance(self.ds, MajorSenser)
assert self.ds.dflt_sense is None
assert len(self.ds.conn2sense) == 0
assert self.ds.n_y < 0
def test_ms_train(self):
<|code_end|>
using the current file's imports:
from dsenser.constants import CONNECTIVE, RAW_TEXT, SENSE
from dsenser.major import MajorSenser
from pytest import fixture
from unittest import TestCase
import numpy as np
and any relevant context from other files:
# Path: dsenser/constants.py
# CONNECTIVE = "Connective"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# Path: dsenser/major.py
# class MajorSenser(BaseSenser):
# """Class making majority predictions for connective senses.
#
# Attributes:
# dflt_sense (np.array or None): probabilities of all senses in
# the corpus
# conn2sense (dict): mapping from connective to the conditional
# probabilities of its senses
# n_y (int): number of distinct classes
#
# """
#
# def __init__(self):
# """Class constructor.
#
# """
# self.dflt_sense = None
# self.conn2sense = {}
# self.n_y = -1
#
# @timeit("Training majority class classifier...")
# def train(self, a_train_data, a_dev_data=None, a_n_y=-1,
# a_i=-1, a_train_out=None, a_dev_out=None):
# """Method for training the model.
#
# Args:
# a_train_data (tuple(list, dict)):
# training JSON data
# a_dev_data (tuple(list, dict) or None):
# development JSON data
# a_n_y (int):
# number of distinct classes
# a_i (int):
# row index for the output predictions
# a_train_out (numpy.array or None):
# predictions for the training set
# a_dev_out (numpy.array or None):
# predictions for the development set
#
# Returns:
# void:
#
# Note:
# updates ``a_train_out`` and ``a_dev_out`` in place if not None
#
# """
# self.n_y = a_n_y
# iconn = ""
# conn2sense = defaultdict(Counter)
# for irel in a_train_data[0]:
# iconn = self._normalize_conn(irel[CONNECTIVE][RAW_TEXT])
# for i, j in enumerate(irel[SENSE]):
# if j:
# conn2sense[iconn][i] += 1
# # compute the most frequent sense and assign it to the default
# # connective
# all_senses = defaultdict(Counter)
# for istat in conn2sense.itervalues():
# all_senses.update(istat)
# # obtain the most frequent sense and use it for missing connectives
# self.dflt_sense = self._get_sense_stat(all_senses)
# # for other connectives use their the respective most frequent sense
# for iconn, istat in conn2sense.iteritems():
# self.conn2sense[iconn] = self._get_sense_stat(istat)
# # make predictions for the training and development set instances if
# # needed
# if a_i >= 0:
# if a_train_out is not None:
# for i, irel in enumerate(a_train_data[0]):
# self.predict(irel, a_train_data, a_train_out[i], a_i)
# if a_dev_data is not None:
# for i, irel in enumerate(a_dev_data[0]):
# self.predict(irel, a_dev_data, a_dev_out[i], a_i)
#
# def predict(self, a_rel, a_data, a_ret, a_i):
# """Method for predicting sense of single relation.
#
# Args:
# a_rel (dict):
# discourse relation whose sense need to be predicted
# a_data (tuple):
# relations and parses
# a_ret (numpy.array):
# prediction matrix
# a_i (int):
# row index in the output vector
#
# Returns:
# void:
#
# Note:
# updates ``a_ret[a_i]`` in place
#
# """
# iconn = self._normalize_conn(a_rel[CONNECTIVE][RAW_TEXT])
# isense = self.conn2sense.get(iconn, self.dflt_sense)
# for i in xrange(len(isense)):
# a_ret[a_i][i] += isense[i]
#
# def _get_sense_stat(self, a_stat):
# """Generate sense statistcs.
#
# Args:
# a_stat (dict): statistics on senses
#
# Returns:
# (numpy.array): prior probabilities of senses
#
# """
# ret = np.zeros(self.n_y if self.n_y > 0 else 0)
# for i, j in a_stat.iteritems():
# ret[i] = j
# total = float(sum(ret))
# if total:
# ret /= total
# return ret
#
# def _free(self):
# """Free resources used by the model.
#
# """
# del self.dflt_sense
# del self.conn2sense
# self.n_y = -1
. Output only the next line. | irels = [{CONNECTIVE: {RAW_TEXT: "SINCE"}, |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import
##################################################################
# Test Classes
class TestMajorSenser(TestCase):
@fixture(autouse=True)
def set_ds(self):
self.ds = MajorSenser()
def test_ms(self):
assert isinstance(self.ds, MajorSenser)
assert self.ds.dflt_sense is None
assert len(self.ds.conn2sense) == 0
assert self.ds.n_y < 0
def test_ms_train(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from dsenser.constants import CONNECTIVE, RAW_TEXT, SENSE
from dsenser.major import MajorSenser
from pytest import fixture
from unittest import TestCase
import numpy as np
and context (classes, functions, sometimes code) from other files:
# Path: dsenser/constants.py
# CONNECTIVE = "Connective"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# Path: dsenser/major.py
# class MajorSenser(BaseSenser):
# """Class making majority predictions for connective senses.
#
# Attributes:
# dflt_sense (np.array or None): probabilities of all senses in
# the corpus
# conn2sense (dict): mapping from connective to the conditional
# probabilities of its senses
# n_y (int): number of distinct classes
#
# """
#
# def __init__(self):
# """Class constructor.
#
# """
# self.dflt_sense = None
# self.conn2sense = {}
# self.n_y = -1
#
# @timeit("Training majority class classifier...")
# def train(self, a_train_data, a_dev_data=None, a_n_y=-1,
# a_i=-1, a_train_out=None, a_dev_out=None):
# """Method for training the model.
#
# Args:
# a_train_data (tuple(list, dict)):
# training JSON data
# a_dev_data (tuple(list, dict) or None):
# development JSON data
# a_n_y (int):
# number of distinct classes
# a_i (int):
# row index for the output predictions
# a_train_out (numpy.array or None):
# predictions for the training set
# a_dev_out (numpy.array or None):
# predictions for the development set
#
# Returns:
# void:
#
# Note:
# updates ``a_train_out`` and ``a_dev_out`` in place if not None
#
# """
# self.n_y = a_n_y
# iconn = ""
# conn2sense = defaultdict(Counter)
# for irel in a_train_data[0]:
# iconn = self._normalize_conn(irel[CONNECTIVE][RAW_TEXT])
# for i, j in enumerate(irel[SENSE]):
# if j:
# conn2sense[iconn][i] += 1
# # compute the most frequent sense and assign it to the default
# # connective
# all_senses = defaultdict(Counter)
# for istat in conn2sense.itervalues():
# all_senses.update(istat)
# # obtain the most frequent sense and use it for missing connectives
# self.dflt_sense = self._get_sense_stat(all_senses)
# # for other connectives use their the respective most frequent sense
# for iconn, istat in conn2sense.iteritems():
# self.conn2sense[iconn] = self._get_sense_stat(istat)
# # make predictions for the training and development set instances if
# # needed
# if a_i >= 0:
# if a_train_out is not None:
# for i, irel in enumerate(a_train_data[0]):
# self.predict(irel, a_train_data, a_train_out[i], a_i)
# if a_dev_data is not None:
# for i, irel in enumerate(a_dev_data[0]):
# self.predict(irel, a_dev_data, a_dev_out[i], a_i)
#
# def predict(self, a_rel, a_data, a_ret, a_i):
# """Method for predicting sense of single relation.
#
# Args:
# a_rel (dict):
# discourse relation whose sense need to be predicted
# a_data (tuple):
# relations and parses
# a_ret (numpy.array):
# prediction matrix
# a_i (int):
# row index in the output vector
#
# Returns:
# void:
#
# Note:
# updates ``a_ret[a_i]`` in place
#
# """
# iconn = self._normalize_conn(a_rel[CONNECTIVE][RAW_TEXT])
# isense = self.conn2sense.get(iconn, self.dflt_sense)
# for i in xrange(len(isense)):
# a_ret[a_i][i] += isense[i]
#
# def _get_sense_stat(self, a_stat):
# """Generate sense statistcs.
#
# Args:
# a_stat (dict): statistics on senses
#
# Returns:
# (numpy.array): prior probabilities of senses
#
# """
# ret = np.zeros(self.n_y if self.n_y > 0 else 0)
# for i, j in a_stat.iteritems():
# ret[i] = j
# total = float(sum(ret))
# if total:
# ret /= total
# return ret
#
# def _free(self):
# """Free resources used by the model.
#
# """
# del self.dflt_sense
# del self.conn2sense
# self.n_y = -1
. Output only the next line. | irels = [{CONNECTIVE: {RAW_TEXT: "SINCE"}, |
Next line prediction: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import
##################################################################
# Test Classes
class TestMajorSenser(TestCase):
@fixture(autouse=True)
def set_ds(self):
self.ds = MajorSenser()
def test_ms(self):
assert isinstance(self.ds, MajorSenser)
assert self.ds.dflt_sense is None
assert len(self.ds.conn2sense) == 0
assert self.ds.n_y < 0
def test_ms_train(self):
irels = [{CONNECTIVE: {RAW_TEXT: "SINCE"},
<|code_end|>
. Use current file imports:
(from dsenser.constants import CONNECTIVE, RAW_TEXT, SENSE
from dsenser.major import MajorSenser
from pytest import fixture
from unittest import TestCase
import numpy as np)
and context including class names, function names, or small code snippets from other files:
# Path: dsenser/constants.py
# CONNECTIVE = "Connective"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# Path: dsenser/major.py
# class MajorSenser(BaseSenser):
# """Class making majority predictions for connective senses.
#
# Attributes:
# dflt_sense (np.array or None): probabilities of all senses in
# the corpus
# conn2sense (dict): mapping from connective to the conditional
# probabilities of its senses
# n_y (int): number of distinct classes
#
# """
#
# def __init__(self):
# """Class constructor.
#
# """
# self.dflt_sense = None
# self.conn2sense = {}
# self.n_y = -1
#
# @timeit("Training majority class classifier...")
# def train(self, a_train_data, a_dev_data=None, a_n_y=-1,
# a_i=-1, a_train_out=None, a_dev_out=None):
# """Method for training the model.
#
# Args:
# a_train_data (tuple(list, dict)):
# training JSON data
# a_dev_data (tuple(list, dict) or None):
# development JSON data
# a_n_y (int):
# number of distinct classes
# a_i (int):
# row index for the output predictions
# a_train_out (numpy.array or None):
# predictions for the training set
# a_dev_out (numpy.array or None):
# predictions for the development set
#
# Returns:
# void:
#
# Note:
# updates ``a_train_out`` and ``a_dev_out`` in place if not None
#
# """
# self.n_y = a_n_y
# iconn = ""
# conn2sense = defaultdict(Counter)
# for irel in a_train_data[0]:
# iconn = self._normalize_conn(irel[CONNECTIVE][RAW_TEXT])
# for i, j in enumerate(irel[SENSE]):
# if j:
# conn2sense[iconn][i] += 1
# # compute the most frequent sense and assign it to the default
# # connective
# all_senses = defaultdict(Counter)
# for istat in conn2sense.itervalues():
# all_senses.update(istat)
# # obtain the most frequent sense and use it for missing connectives
# self.dflt_sense = self._get_sense_stat(all_senses)
# # for other connectives use their the respective most frequent sense
# for iconn, istat in conn2sense.iteritems():
# self.conn2sense[iconn] = self._get_sense_stat(istat)
# # make predictions for the training and development set instances if
# # needed
# if a_i >= 0:
# if a_train_out is not None:
# for i, irel in enumerate(a_train_data[0]):
# self.predict(irel, a_train_data, a_train_out[i], a_i)
# if a_dev_data is not None:
# for i, irel in enumerate(a_dev_data[0]):
# self.predict(irel, a_dev_data, a_dev_out[i], a_i)
#
# def predict(self, a_rel, a_data, a_ret, a_i):
# """Method for predicting sense of single relation.
#
# Args:
# a_rel (dict):
# discourse relation whose sense need to be predicted
# a_data (tuple):
# relations and parses
# a_ret (numpy.array):
# prediction matrix
# a_i (int):
# row index in the output vector
#
# Returns:
# void:
#
# Note:
# updates ``a_ret[a_i]`` in place
#
# """
# iconn = self._normalize_conn(a_rel[CONNECTIVE][RAW_TEXT])
# isense = self.conn2sense.get(iconn, self.dflt_sense)
# for i in xrange(len(isense)):
# a_ret[a_i][i] += isense[i]
#
# def _get_sense_stat(self, a_stat):
# """Generate sense statistcs.
#
# Args:
# a_stat (dict): statistics on senses
#
# Returns:
# (numpy.array): prior probabilities of senses
#
# """
# ret = np.zeros(self.n_y if self.n_y > 0 else 0)
# for i, j in a_stat.iteritems():
# ret[i] = j
# total = float(sum(ret))
# if total:
# ret /= total
# return ret
#
# def _free(self):
# """Free resources used by the model.
#
# """
# del self.dflt_sense
# del self.conn2sense
# self.n_y = -1
. Output only the next line. | SENSE: ["Contingency.Cause.Reason"]}, |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import
##################################################################
# Test Classes
class TestMajorSenser(TestCase):
@fixture(autouse=True)
def set_ds(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from dsenser.constants import CONNECTIVE, RAW_TEXT, SENSE
from dsenser.major import MajorSenser
from pytest import fixture
from unittest import TestCase
import numpy as np
and context (classes, functions, sometimes code) from other files:
# Path: dsenser/constants.py
# CONNECTIVE = "Connective"
#
# RAW_TEXT = "RawText"
#
# SENSE = "Sense"
#
# Path: dsenser/major.py
# class MajorSenser(BaseSenser):
# """Class making majority predictions for connective senses.
#
# Attributes:
# dflt_sense (np.array or None): probabilities of all senses in
# the corpus
# conn2sense (dict): mapping from connective to the conditional
# probabilities of its senses
# n_y (int): number of distinct classes
#
# """
#
# def __init__(self):
# """Class constructor.
#
# """
# self.dflt_sense = None
# self.conn2sense = {}
# self.n_y = -1
#
# @timeit("Training majority class classifier...")
# def train(self, a_train_data, a_dev_data=None, a_n_y=-1,
# a_i=-1, a_train_out=None, a_dev_out=None):
# """Method for training the model.
#
# Args:
# a_train_data (tuple(list, dict)):
# training JSON data
# a_dev_data (tuple(list, dict) or None):
# development JSON data
# a_n_y (int):
# number of distinct classes
# a_i (int):
# row index for the output predictions
# a_train_out (numpy.array or None):
# predictions for the training set
# a_dev_out (numpy.array or None):
# predictions for the development set
#
# Returns:
# void:
#
# Note:
# updates ``a_train_out`` and ``a_dev_out`` in place if not None
#
# """
# self.n_y = a_n_y
# iconn = ""
# conn2sense = defaultdict(Counter)
# for irel in a_train_data[0]:
# iconn = self._normalize_conn(irel[CONNECTIVE][RAW_TEXT])
# for i, j in enumerate(irel[SENSE]):
# if j:
# conn2sense[iconn][i] += 1
# # compute the most frequent sense and assign it to the default
# # connective
# all_senses = defaultdict(Counter)
# for istat in conn2sense.itervalues():
# all_senses.update(istat)
# # obtain the most frequent sense and use it for missing connectives
# self.dflt_sense = self._get_sense_stat(all_senses)
# # for other connectives use their the respective most frequent sense
# for iconn, istat in conn2sense.iteritems():
# self.conn2sense[iconn] = self._get_sense_stat(istat)
# # make predictions for the training and development set instances if
# # needed
# if a_i >= 0:
# if a_train_out is not None:
# for i, irel in enumerate(a_train_data[0]):
# self.predict(irel, a_train_data, a_train_out[i], a_i)
# if a_dev_data is not None:
# for i, irel in enumerate(a_dev_data[0]):
# self.predict(irel, a_dev_data, a_dev_out[i], a_i)
#
# def predict(self, a_rel, a_data, a_ret, a_i):
# """Method for predicting sense of single relation.
#
# Args:
# a_rel (dict):
# discourse relation whose sense need to be predicted
# a_data (tuple):
# relations and parses
# a_ret (numpy.array):
# prediction matrix
# a_i (int):
# row index in the output vector
#
# Returns:
# void:
#
# Note:
# updates ``a_ret[a_i]`` in place
#
# """
# iconn = self._normalize_conn(a_rel[CONNECTIVE][RAW_TEXT])
# isense = self.conn2sense.get(iconn, self.dflt_sense)
# for i in xrange(len(isense)):
# a_ret[a_i][i] += isense[i]
#
# def _get_sense_stat(self, a_stat):
# """Generate sense statistcs.
#
# Args:
# a_stat (dict): statistics on senses
#
# Returns:
# (numpy.array): prior probabilities of senses
#
# """
# ret = np.zeros(self.n_y if self.n_y > 0 else 0)
# for i, j in a_stat.iteritems():
# ret[i] = j
# total = float(sum(ret))
# if total:
# ret /= total
# return ret
#
# def _free(self):
# """Free resources used by the model.
#
# """
# del self.dflt_sense
# del self.conn2sense
# self.n_y = -1
. Output only the next line. | self.ds = MajorSenser() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.