def run(self, data):
"""Compute biclustering.
Parameters
----------
data : numpy.ndarray
"""
data = check_array(data, dtype=np.bool, copy=True)
self._validate_parameters()
data = [np.packbits(row) for row in data]
biclusters = []
patterns_found = set()
for ri, rj in combinations(data, 2):
pattern = np.bitwise_and(ri, rj)
pattern_cols = sum(popcount(int(n)) for n in pattern)
if pattern_cols >= self.min_cols and self._is_new(patterns_found, pattern):
rows = [k for k, r in enumerate(data) if self._match(pattern, r)]
if len(rows) >= self.min_rows:
cols = np.where(np.unpackbits(pattern) == 1)[0]
biclusters.append(Bicluster(rows, cols))
return Biclustering(biclusters)
python类packbits()的实例源码
def test_packbits():
# Copied from the docstring.
a = [[[1, 0, 1], [0, 1, 0]],
[[1, 1, 0], [0, 0, 1]]]
for dtype in [np.bool, np.uint8, np.int]:
arr = np.array(a, dtype=dtype)
b = np.packbits(arr, axis=-1)
assert_equal(b.dtype, np.uint8)
assert_array_equal(b, np.array([[[160], [64]], [[192], [32]]]))
assert_raises(TypeError, np.packbits, np.array(a, dtype=float))
def main(_):
if (FLAGS.input_image is None or FLAGS.output_codes is None or
FLAGS.model is None):
print('\nUsage: python encoder.py --input_image=/your/image/here.png '
'--output_codes=output_codes.pkl --iteration=15 '
'--model=residual_gru.pb\n\n')
return
if FLAGS.iteration < 0 or FLAGS.iteration > 15:
print('\n--iteration must be between 0 and 15 inclusive.\n')
return
with tf.gfile.FastGFile(FLAGS.input_image) as input_image:
input_image_str = input_image.read()
with tf.Graph().as_default() as graph:
# Load the inference model for encoding.
with tf.gfile.FastGFile(FLAGS.model, 'rb') as model_file:
graph_def = tf.GraphDef()
graph_def.ParseFromString(model_file.read())
_ = tf.import_graph_def(graph_def, name='')
input_tensor = graph.get_tensor_by_name('Placeholder:0')
outputs = [graph.get_tensor_by_name(name) for name in
get_output_tensor_names()]
input_image = tf.placeholder(tf.string)
_, ext = os.path.splitext(FLAGS.input_image)
if ext == '.png':
decoded_image = tf.image.decode_png(input_image, channels=3)
elif ext == '.jpeg' or ext == '.jpg':
decoded_image = tf.image.decode_jpeg(input_image, channels=3)
else:
assert False, 'Unsupported file format {}'.format(ext)
decoded_image = tf.expand_dims(decoded_image, 0)
with tf.Session(graph=graph) as sess:
img_array = sess.run(decoded_image, feed_dict={input_image:
input_image_str})
results = sess.run(outputs, feed_dict={input_tensor: img_array})
results = results[0:FLAGS.iteration + 1]
int_codes = np.asarray([x.astype(np.int8) for x in results])
# Convert int codes to binary.
int_codes = (int_codes + 1)//2
export = np.packbits(int_codes.reshape(-1))
output = io.BytesIO()
np.savez_compressed(output, shape=int_codes.shape, codes=export)
with tf.gfile.FastGFile(FLAGS.output_codes, 'w') as code_file:
code_file.write(output.getvalue())
def finishframe(self, symbols):
# look for flag at end.
flagcorr = numpy.correlate(symbols, [-1, 1, 1, 1, 1, 1, 1, 1, -1])
cimax = numpy.argmax(flagcorr) # index of first flag
cimin = numpy.argmin(flagcorr) # index of first inverted flag
if flagcorr[cimax] == 9 and flagcorr[cimin] == -9:
# they are both proper flags
ci = min(cimax, cimin)
elif flagcorr[cimax] == 9:
ci = cimax
else:
ci = cimin
symbols = symbols[0:ci+1]
# un-nrzi symbols to get bits.
bits = numpy.where(numpy.equal(symbols[:-1], symbols[1:]), 1, 0)
# un-bit-stuff. every sequence of five ones must be followed
# by a zero, which we should delete.
nones = 0
nbits = [ ]
for i in range(0, len(bits)):
if nones == 5:
nones = 0
# assuming bits[i] == 0
# don't append the zero...
elif bits[i] == 1:
nones += 1
nbits.append(bits[i])
else:
nbits.append(bits[i])
nones = 0
bits = nbits
if len(bits) < 8:
return [ 0, None, 0 ]
# convert bits to bytes.
# bits[] is least-significant-first, but
# numpy.packbits() wants MSF.
bits = numpy.array(bits)
bits = bits[0:(len(bits)/8)*8]
assert (len(bits)%8) == 0
bits = bits[::-1]
bytes = numpy.packbits(bits)
bytes = bytes[::-1]
msg = None
ok = self.checkpacket(bytes)
if ok > 0 or len(bytes) > 16:
msg = self.printpacket(bytes)
return [ ok, msg, len(symbols) ]
# 0: syntactically unlikely to be a packet
# 1: syntactically plausible but crc failed
# 2: crc is correct