Here are the examples of the python api numpy.max taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
5053 Examples
3
Source : Decision Tree using ID3.py
with MIT License
from 0xPrateek
with MIT License
from 0xPrateek
def get_node(data):
entropy1 = single_attribute_entropy(data)
IG = []
attributes = data.columns[:-1]
for attribute in attributes:
entropy2 = double_attribute_entropy(data,attribute)
IG.append(entropy1-entropy2)
value = numpy.max(IG)
index = IG.index(value)
return attributes[index]
def build_decision_tree(data,Tree = None):
3
Source : Random Forest.py
with MIT License
from 0xPrateek
with MIT License
from 0xPrateek
def get_node(data):
entropy1 = single_attribute_entropy(data)
IG = []
attributes = data.columns[:-1]
for attribute in attributes:
entropy2 = double_attribute_entropy(data,attribute)
IG.append(entropy1-entropy2)
value = numpy.max(IG)
index = IG.index(value)
return attributes[index]
# This function return the Decision tree
def build_decision_tree(data,Tree = None):
3
Source : average_precision_calculator.py
with Apache License 2.0
from 17Skye17
with Apache License 2.0
from 17Skye17
def _zero_one_normalize(predictions, epsilon=1e-7):
"""Normalize the predictions to the range between 0.0 and 1.0.
For some predictions like SVM predictions, we need to normalize them before
calculate the interpolated average precision. The normalization will not
change the rank in the original list and thus won't change the average
precision.
Args:
predictions: a numpy 1-D array storing the sparse prediction scores.
epsilon: a small constant to avoid denominator being zero.
Returns:
The normalized prediction.
"""
denominator = numpy.max(predictions) - numpy.min(predictions)
ret = (predictions - numpy.min(predictions)) / numpy.max(denominator,
epsilon)
return ret
3
Source : ref_rna.py
with MIT License
from 1ytic
with MIT License
from 1ytic
def log_softmax(acts, axis):
"""
Log softmax over the last axis of the 3D array.
"""
acts = acts - np.max(acts, axis=axis, keepdims=True)
probs = np.sum(np.exp(acts), axis=axis, keepdims=True)
log_probs = acts - np.log(probs)
return log_probs
def forward_pass(log_probs, labels, blank):
3
Source : PColorMeshItem.py
with MIT License
from 3fon3fonov
with MIT License
from 3fon3fonov
def width(self):
if self.x is None:
return None
return np.max(self.x)
def height(self):
3
Source : PColorMeshItem.py
with MIT License
from 3fon3fonov
with MIT License
from 3fon3fonov
def height(self):
if self.y is None:
return None
return np.max(self.y)
def boundingRect(self):
3
Source : PlotData.py
with MIT License
from 3fon3fonov
with MIT License
from 3fon3fonov
def max(self, field):
mx = self.maxVals.get(field, None)
if mx is None:
mx = np.max(self[field])
self.maxVals[field] = mx
return mx
def min(self, field):
3
Source : image_writer.py
with BSD 3-Clause "New" or "Revised" License
from 4DNucleome
with BSD 3-Clause "New" or "Revised" License
from 4DNucleome
def save_mask(cls, image: Image, save_path: typing.Union[str, Path], compression=""):
"""
Save mask connected to image as tiff to path or buffer
:param image: mast is obtain with :py:meth:`.Image.get_mask_for_save`
:param save_path: save location
"""
mask = image.get_mask_for_save()
if mask is None:
return
mask_max = np.max(mask)
mask = mask.astype(minimal_dtype(mask_max))
metadata = {"mode": "color", "unit": "\\u00B5m"}
spacing = image.get_um_spacing()
if len(spacing) == 3:
metadata.update({"spacing": spacing[0]})
resolution = [1 / x for x in spacing[-2:]]
cls._save(mask, save_path, resolution, metadata)
@staticmethod
3
Source : test_io.py
with BSD 3-Clause "New" or "Revised" License
from 4DNucleome
with BSD 3-Clause "New" or "Revised" License
from 4DNucleome
def test_load_old_project(self, data_test_dir):
load_data = LoadProject.load([os.path.join(data_test_dir, "stack1_component1.tgz")])
assert np.max(load_data.roi_info.roi) == 2
# TODO add more checks
def test_load_project(self, data_test_dir):
3
Source : test_io.py
with BSD 3-Clause "New" or "Revised" License
from 4DNucleome
with BSD 3-Clause "New" or "Revised" License
from 4DNucleome
def test_load_project(self, data_test_dir):
load_data = LoadProject.load([os.path.join(data_test_dir, "stack1_component1_1.tgz")])
assert np.max(load_data.roi_info.roi) == 2
# TODO add more checks
def test_save_project(self, tmpdir, analysis_project):
3
Source : test_pipeline.py
with BSD 3-Clause "New" or "Revised" License
from 4DNucleome
with BSD 3-Clause "New" or "Revised" License
from 4DNucleome
def test_simple(image, algorithm_parameters, channel):
algorithm_parameters["values"]["channel"] = channel
algorithm = analysis_algorithm_dict[algorithm_parameters["algorithm_name"]]()
algorithm.set_image(image)
algorithm.set_parameters(**algorithm_parameters["values"])
result = algorithm.calculation_run(lambda x, y: None)
assert np.max(result.roi) == 1
def test_pipeline_manual(image, algorithm_parameters, mask_property):
3
Source : test_pipeline.py
with BSD 3-Clause "New" or "Revised" License
from 4DNucleome
with BSD 3-Clause "New" or "Revised" License
from 4DNucleome
def test_pipeline_manual(image, algorithm_parameters, mask_property):
algorithm = analysis_algorithm_dict[algorithm_parameters["algorithm_name"]]()
algorithm.set_image(image)
algorithm.set_parameters(**algorithm_parameters["values"])
result = algorithm.calculation_run(lambda x, y: None)
mask = calculate_mask(mask_property, result.roi, None, image.spacing)
algorithm_parameters["values"]["channel"] = 1
algorithm.set_parameters(**algorithm_parameters["values"])
algorithm.set_mask(mask)
result2 = algorithm.calculation_run(lambda x, y: None)
assert np.max(result2.roi) == 2
@pytest.mark.parametrize("use_mask", [True, False])
3
Source : misc.py
with MIT License
from 500swapnil
with MIT License
from 500swapnil
def draw_bboxes(bboxes, ax, color='red', labels=None, IMAGE_SIZE=[300, 300]):
# image = (im - np.min(im))/np.ptp(im)
# print(image.shape)
if np.max(bboxes) < 10:
bboxes[:, [0,2]] = bboxes[:, [0,2]]*IMAGE_SIZE[1]
bboxes[:, [1,3]] = bboxes[:, [1,3]]*IMAGE_SIZE[0]
for i, bbox in enumerate(bboxes):
rect = patches.Rectangle((bbox[0], bbox[1]), bbox[2]-bbox[0], bbox[3]-bbox[1], linewidth=1, edgecolor=color, facecolor='none')
# ax.add_patch(rect)
ax.add_artist(rect)
# print(int(bbox[-1]))
if labels is not None:
ax.text(bbox[0]+0.5,bbox[1]+0.5, CLASSES[int(labels[i] - 1)], fontsize=20,
horizontalalignment='left', verticalalignment='top', bbox=dict(facecolor=color, alpha=0.4))
3
Source : transforms.py
with Apache License 2.0
from 920232796
with Apache License 2.0
from 920232796
def get_do_separate_z(spacing, anisotropy_threshold=RESAMPLING_SEPARATE_Z_ANISO_THRESHOLD):
do_separate_z = (np.max(spacing) / np.min(spacing)) > anisotropy_threshold
return do_separate_z
def get_lowres_axis(new_spacing):
3
Source : rednoise_fun.py
with MIT License
from a-n-rose
with MIT License
from a-n-rose
def matchvol(target_powerspec, speech_powerspec, speech_stft):
tmp = np.max(target_powerspec)
smp = np.max(speech_powerspec)
stft = speech_stft.copy()
if smp > tmp:
mag = tmp/smp
stft *= mag
return stft
def suspended_energy(rms_speech,row,rms_mean_noise,start):
3
Source : analyse_audio.py
with MIT License
from a-n-rose
with MIT License
from a-n-rose
def matchvol(target_powerspec, speech_powerspec, speech_stft):
tmp = np.max(target_powerspec)
smp = np.max(speech_powerspec)
stft = speech_stft.copy()
if smp > tmp:
mag = tmp/smp
stft *= mag
return stft
def suspended_energy(speech_energy,row,speech_energy_mean,start):
3
Source : utils.py
with MIT License
from aachenhang
with MIT License
from aachenhang
def save_results(input_img, gt_data,density_map,output_dir, fname='results.png'):
input_img = input_img[0][0]
gt_data = 255*gt_data/np.max(gt_data)
density_map = 255*density_map/np.max(density_map)
gt_data = gt_data[0][0]
density_map= density_map[0][0]
if density_map.shape[1] != input_img.shape[1]:
density_map = cv2.resize(density_map, (input_img.shape[1],input_img.shape[0]))
gt_data = cv2.resize(gt_data, (input_img.shape[1],input_img.shape[0]))
result_img = np.hstack((input_img,gt_data,density_map))
cv2.imwrite(os.path.join(output_dir,fname),result_img)
def save_density_map(density_map,output_dir, fname='results.png'):
3
Source : utils.py
with MIT License
from aachenhang
with MIT License
from aachenhang
def save_density_map(density_map,output_dir, fname='results.png'):
density_map = 255*density_map/np.max(density_map)
density_map= density_map[0][0]
cv2.imwrite(os.path.join(output_dir,fname),density_map)
def display_results(input_img, gt_data,density_map):
3
Source : utils.py
with MIT License
from aachenhang
with MIT License
from aachenhang
def display_results(input_img, gt_data,density_map):
input_img = input_img[0][0]
gt_data = 255*gt_data/np.max(gt_data)
density_map = 255*density_map/np.max(density_map)
gt_data = gt_data[0][0]
density_map= density_map[0][0]
if density_map.shape[1] != input_img.shape[1]:
input_img = cv2.resize(input_img, (density_map.shape[1],density_map.shape[0]))
result_img = np.hstack((input_img,gt_data,density_map))
result_img = result_img.astype(np.uint8, copy=False)
cv2.imshow('Result', result_img)
cv2.waitKey(0)
3
Source : feedback_processing.py
with MIT License
from AaltoPML
with MIT License
from AaltoPML
def create_indices_bookkeeping(self):
self.obs_indices = [i for i in range(0,self.N) if not self.is_pseudobs(i)]
self.pseudobs_indices = [i for i in range(0,self.N) if self.is_pseudobs(i)]
self.latest_obs_indices = [np.max([ind for ind in self.obs_indices if ind < i]) if self.is_pseudobs(i) else i for i in range(0,self.N)]
def scale(self,X,retain_0_values=False):
3
Source : preprocessing.py
with MIT License
from Aatr0x13
with MIT License
from Aatr0x13
def preprocess_depth(depth):
depth = np.clip(depth, 0.0, np.max(depth))
max_feature = np.max(depth)
if max_feature != 0:
depth /= max_feature
return depth
def preprocess_normal(normal):
3
Source : imtools.py
with Apache License 2.0
from Accenture
with Apache License 2.0
from Accenture
def max_aabb_area(aabbs):
x_dims = aabb_dims(aabbs, 0)
y_dims = aabb_dims(aabbs, 1)
return np.max(x_dims, 0) * np.max(y_dims, 0)
def compute_aabb_area(aabb):
3
Source : tsdf_volume.py
with Apache License 2.0
from achao2013
with Apache License 2.0
from achao2013
def get_view_frustum(depth_im, cam_intr, cam_pose):
"""Get corners of 3D camera view frustum of depth image
"""
im_h = depth_im.shape[0]
im_w = depth_im.shape[1]
max_depth = np.max(depth_im)
view_frust_pts = np.array([
(np.array([0, 0, 0, im_w, im_w]) - cam_intr[0, 2]) * np.array([0, max_depth, max_depth, max_depth, max_depth]) /
cam_intr[0, 0],
(np.array([0, 0, im_h, 0, im_h]) - cam_intr[1, 2]) * np.array([0, max_depth, max_depth, max_depth, max_depth]) /
cam_intr[1, 1],
np.array([0, max_depth, max_depth, max_depth, max_depth])
])
view_frust_pts = rigid_transform(view_frust_pts.T, cam_pose).T
return view_frust_pts
def meshwrite(filename, verts, faces, norms, colors):
3
Source : autognuplot.py
with BSD 3-Clause "New" or "Revised" License
from acorbe
with BSD 3-Clause "New" or "Revised" License
from acorbe
def __hist_normalization_function(self
, v_
, normalization ):
N_coeff = 1
if normalization is not None:
if isinstance( normalization, float):
N_coeff = normalization
elif isinstance( normalization, str):
if normalization == 'max':
N_coeff = np.max(v_)
return N_coeff
def hist_generic(self, x
3
Source : plot.py
with MIT License
from AcutronicRobotics
with MIT License
from AcutronicRobotics
def pad(xs, value=np.nan):
maxlen = np.max([len(x) for x in xs])
padded_xs = []
for x in xs:
if x.shape[0] >= maxlen:
padded_xs.append(x)
padding = np.ones((maxlen - x.shape[0],) + x.shape[1:]) * value
x_padded = np.concatenate([x, padding], axis=0)
assert x_padded.shape[1:] == x.shape[1:]
assert x_padded.shape[0] == maxlen
padded_xs.append(x_padded)
return np.array(padded_xs)
parser = argparse.ArgumentParser()
3
Source : ims.py
with GNU General Public License v3.0
from ad12
with GNU General Public License v3.0
from ad12
def im_update(self):
orientation = self.orientation
self.im.reformat(orientation, inplace=True)
im = self.im.volume
im = im / np.max(im)
if self.mask:
self.mask.reformat(orientation, inplace=True)
label_image = label(self.mask.volume)
im = self.__labeltorgb_3d__(im, label_image, 0.3)
self.im_display = im
def __labeltorgb_3d__(self, im: np.ndarray, labels: np.ndarray, alpha: float = 0.3):
3
Source : network_layers.py
with MIT License
from AdaCompNUS
with MIT License
from AdaCompNUS
def conv2_layer(filters, kernel_size, activation=None, padding='same', strides=(1,1), dilation_rate=(1,1),
data_format='channels_last', use_bias=False, name=None, layer_i=0, name2=None):
if name is None:
name = "l%d_conv%d" % (layer_i, np.max(kernel_size))
if np.max(dilation_rate) > 1:
name += "_d%d" % np.max(dilation_rate)
if name2 is not None:
name += "_"+name2
fn = lambda x: tf.layers.conv2d(
x, filters, kernel_size, activation=convert_activation_string(activation),
padding=padding, strides=strides, dilation_rate = dilation_rate, data_format=data_format,
kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=_L2_SCALE),
kernel_initializer=tf.variance_scaling_initializer(),
use_bias=use_bias, name=name)
return fn
def locallyconn2_layer(filters, kernel_size, activation=None, padding='same', strides=(1,1), dilation_rate=(1,1),
3
Source : network_layers.py
with MIT License
from AdaCompNUS
with MIT License
from AdaCompNUS
def locallyconn2_layer(filters, kernel_size, activation=None, padding='same', strides=(1,1), dilation_rate=(1,1),
data_format='channels_last', use_bias=False, name=None, layer_i=0, name2=None):
assert dilation_rate == (1, 1) # keras layer doesnt have this input. maybe different name?
if name is None:
name = "l%d_conv%d"%(layer_i, np.max(kernel_size))
if np.max(dilation_rate) > 1:
name += "_d%d"%np.max(dilation_rate)
if name2 is not None:
name += "_"+name2
fn = tf.keras.layers.LocallyConnected2D(
filters, kernel_size, activation=convert_activation_string(activation),
padding=padding, strides=strides, data_format=data_format,
kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=_L2_SCALE),
kernel_initializer=tf.variance_scaling_initializer(),
use_bias=use_bias, name=name)
return fn
def convert_activation_string(activation):
3
Source : run.py
with MIT License
from AdamStelmaszczyk
with MIT License
from AdamStelmaszczyk
def fit_batch(env, model, target_model, batch):
observations, actions, rewards, next_observations, dones = batch
# Predict the Q values of the next states. Passing ones as the action mask.
next_q_values = predict(env, target_model, next_observations)
# The Q values of terminal states is 0 by definition.
next_q_values[dones] = 0.0
# The Q values of each start state is the reward + gamma * the max next state Q value
q_values = rewards + DISCOUNT_FACTOR_GAMMA * np.max(next_q_values, axis=1)
one_hot_actions = np.array([one_hot_encode(env.action_space.n, action) for action in actions])
history = model.fit(
x=[observations, one_hot_actions],
y=one_hot_actions * q_values[:, None],
batch_size=BATCH_SIZE,
verbose=0,
)
return history.history['loss'][0]
def create_model(env):
3
Source : reporters.py
with MIT License
from ADicksonLab
with MIT License
from ADicksonLab
def report(self,current_time,current_state_vec):
tmp = current_state_vec[self.selection_idxs]
self._reports.append({'t': current_time,
'report': (np.max(tmp),np.argmax(tmp))})
class MinReporter(Reporter):
3
Source : arrayprint.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def __init__(self, data):
if data.size > 0:
max_str_len = max(len(str(np.max(data))),
len(str(np.min(data))))
else:
max_str_len = 0
self.format = '%{}d'.format(max_str_len)
def __call__(self, x):
3
Source : arrayprint.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def __init__(self, data):
non_nat = data[~isnat(data)]
if len(non_nat) > 0:
# Max str length of non-NaT elements
max_str_len = max(len(self._format_non_nat(np.max(non_nat))),
len(self._format_non_nat(np.min(non_nat))))
else:
max_str_len = 0
if len(non_nat) < data.size:
# data contains a NaT
max_str_len = max(max_str_len, 5)
self._format = '%{}s'.format(max_str_len)
self._nat = "'NaT'".rjust(max_str_len)
def _format_non_nat(self, x):
3
Source : test_nanfunctions.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def test_nanmax(self):
tgt = np.max(self.mat)
for mat in self.integer_arrays():
assert_equal(np.nanmax(mat), tgt)
def test_nanargmin(self):
3
Source : test_defmatrix.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def test_max(self):
x = matrix([[1, 2, 3], [4, 5, 6]])
assert_equal(x.max(), 6)
assert_equal(x.max(0), matrix([[4, 5, 6]]))
assert_equal(x.max(1), matrix([[3], [6]]))
assert_equal(np.max(x), 6)
assert_equal(np.max(x, axis=0), matrix([[4, 5, 6]]))
assert_equal(np.max(x, axis=1), matrix([[3], [6]]))
def test_min(self):
3
Source : test_analytics.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def test_max(self):
with warnings.catch_warnings(record=True):
self._check_stat_op('max', np.max, check_dates=True)
self._check_stat_op('max', np.max, frame=self.intframe)
def test_mad(self):
3
Source : test_nanops.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def test_nanmax(self):
with warnings.catch_warnings(record=True):
func = partial(self._minmax_wrap, func=np.max)
self.check_funs(nanops.nanmax, func,
allow_str=False, allow_obj=False)
def _argminmax_wrap(self, value, axis=None, func=None):
3
Source : test_window.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def test_rolling_max(self):
self._check_moment_func(np.max, name='max')
a = pd.Series([1, 2, 3, 4, 5], dtype=np.float64)
b = a.rolling(window=100, min_periods=1).max()
tm.assert_almost_equal(a, b)
with pytest.raises(ValueError):
pd.Series([1, 2, 3]).rolling(window=3, min_periods=5).max()
@pytest.mark.parametrize('q', [0.0, .1, .5, .9, 1.0])
3
Source : test_real_transforms.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def test_definition(self):
for i in FFTWDATA_SIZES:
x, yr, dt = fftw_dct_ref(self.type, i, self.rdt)
y = dct(x, type=self.type)
assert_equal(y.dtype, dt)
# XXX: we divide by np.max(y) because the tests fail otherwise. We
# should really use something like assert_array_approx_equal. The
# difference is due to fftw using a better algorithm w.r.t error
# propagation compared to the ones from fftpack.
assert_array_almost_equal(y / np.max(y), yr / np.max(y), decimal=self.dec,
err_msg="Size %d failed" % i)
def test_axis(self):
3
Source : test_real_transforms.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def test_definition(self):
for i in FFTWDATA_SIZES:
xr, yr, dt = fftw_dct_ref(self.type, i, self.rdt)
x = idct(yr, type=self.type)
if self.type == 1:
x /= 2 * (i-1)
else:
x /= 2 * i
assert_equal(x.dtype, dt)
# XXX: we divide by np.max(y) because the tests fail otherwise. We
# should really use something like assert_array_approx_equal. The
# difference is due to fftw using a better algorithm w.r.t error
# propagation compared to the ones from fftpack.
assert_array_almost_equal(x / np.max(x), xr / np.max(x), decimal=self.dec,
err_msg="Size %d failed" % i)
class TestIDCTIDouble(_TestIDCTBase):
3
Source : test_real_transforms.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def test_definition(self):
for i in FFTWDATA_SIZES:
xr, yr, dt = fftw_dst_ref(self.type, i, self.rdt)
y = dst(xr, type=self.type)
assert_equal(y.dtype, dt)
# XXX: we divide by np.max(y) because the tests fail otherwise. We
# should really use something like assert_array_approx_equal. The
# difference is due to fftw using a better algorithm w.r.t error
# propagation compared to the ones from fftpack.
assert_array_almost_equal(y / np.max(y), yr / np.max(y), decimal=self.dec,
err_msg="Size %d failed" % i)
class TestDSTIDouble(_TestDSTBase):
3
Source : test_real_transforms.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def test_definition(self):
for i in FFTWDATA_SIZES:
xr, yr, dt = fftw_dst_ref(self.type, i, self.rdt)
x = idst(yr, type=self.type)
if self.type == 1:
x /= 2 * (i+1)
else:
x /= 2 * i
assert_equal(x.dtype, dt)
# XXX: we divide by np.max(x) because the tests fail otherwise. We
# should really use something like assert_array_approx_equal. The
# difference is due to fftw using a better algorithm w.r.t error
# propagation compared to the ones from fftpack.
assert_array_almost_equal(x / np.max(x), xr / np.max(x), decimal=self.dec,
err_msg="Size %d failed" % i)
class TestIDSTIDouble(_TestIDSTBase):
3
Source : test_binned_statistic.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def test_1d_max(self):
x = self.x
v = self.v
stat1, edges1, bc = binned_statistic(x, v, 'max', bins=10)
stat2, edges2, bc = binned_statistic(x, v, np.max, bins=10)
assert_allclose(stat1, stat2)
assert_allclose(edges1, edges2)
def test_1d_median(self):
3
Source : test_binned_statistic.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def test_2d_max(self):
x = self.x
y = self.y
v = self.v
stat1, binx1, biny1, bc = binned_statistic_2d(x, y, v, 'max', bins=5)
stat2, binx2, biny2, bc = binned_statistic_2d(x, y, v, np.max, bins=5)
assert_allclose(stat1, stat2)
assert_allclose(binx1, binx2)
assert_allclose(biny1, biny2)
def test_2d_median(self):
3
Source : test_binned_statistic.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def test_dd_max(self):
X = self.X
v = self.v
stat1, edges1, bc = binned_statistic_dd(X, v, 'max', bins=3)
stat2, edges2, bc = binned_statistic_dd(X, v, np.max, bins=3)
assert_allclose(stat1, stat2)
assert_allclose(edges1, edges2)
def test_dd_median(self):
3
Source : iou_loss.py
with MIT License
from AdivarekarBhumit
with MIT License
from AdivarekarBhumit
def IoU(y_true, y_pred, eps=1e-6):
if np.max(y_true) == 0.0:
return IoU(1-y_true, 1-y_pred) ## empty image; calc IoU of zeros
intersection = K.sum(y_true * y_pred, axis=[1,2,3])
union = K.sum(y_true, axis=[1,2,3]) + K.sum(y_pred, axis=[1,2,3]) - intersection
return -K.mean( (intersection + eps) / (union + eps), axis=0)
3
Source : func.py
with Apache License 2.0
from advboxes
with Apache License 2.0
from advboxes
def softmax(logits):
"""Transforms predictions into probability values."""
assert logits.ndim == 1
logits = logits - np.max(logits)
e = np.exp(logits)
return e / np.sum(e)
def crossentropy(label, logits):
3
Source : image.py
with Apache License 2.0
from advboxes
with Apache License 2.0
from advboxes
def ndarray_to_bytes(image):
"""Converting image in ndarray format to bytes."""
if np.max(image) < 2.0:
image = (image * 255.)
if image.dtype != np.uint8:
image = image.astype(np.uint8)
image_pil = Image.fromarray(image)
bytes_output = BytesIO()
image_pil.save(bytes_output, format='PNG')
return bytes_output.getvalue()
def letterbox_image(
3
Source : cheap_image.py
with MIT License
from aeb
with MIT License
from aeb
def estimate_dynamic_range(self,x,y,I) :
peak_flux = np.max(I)
peak_negative_flux = np.max(np.maximum(-I,0.0))
return peak_flux/peak_negative_flux
def generate_mpl_plot(self,fig,ax,**kwargs) :
3
Source : heatmap_utils.py
with Apache License 2.0
from ahmdtaha
with Apache License 2.0
from ahmdtaha
def save_heatmap(heatmap,save=None):
heat_map_resized = transform.resize(heatmap, (const.max_frame_size, const.max_frame_size))
# normalize heat map
max_value = np.max(heat_map_resized)
min_value = np.min(heat_map_resized)
normalized_heat_map = 255* (heat_map_resized - min_value) / (max_value - min_value)
imageio.imwrite(save,normalized_heat_map)
3
Source : functions.py
with MIT License
from ahn-github
with MIT License
from ahn-github
def softmax(x):
if x.ndim == 2:
x = x.T
x = x - np.max(x, axis=0)
y = np.exp(x) / np.sum(np.exp(x), axis=0)
return y.T
x = x - np.max(x) # 오버플로 대책
return np.exp(x) / np.sum(np.exp(x))
def mean_squared_error(y, t):
See More Examples