예제 #1
0
 def multiply_by_locgrad(path_value):
     result = np.zeros(flatshape)
     result[np.arange(result.shape[0]), idx] = 1
     swapped_shape = list(a.shape)
     swapped_shape[axis], swapped_shape[-1] = swapped_shape[
         -1], swapped_shape[axis]
     result = result.reshape(swapped_shape)
     result = np.swapaxes(result, axis, -1)
     return path_value * result
예제 #2
0
def cross_entropy(y_pred: Variable, y_true: np.array, axis=-1) -> Variable:
    """Cross entropy.
    Args:
        y_pred: A sp.Variable instance of shape [batch_size, n_classes]
        y_true: A NumPy array, of shape [batch_size], containing the true class labels.
    Returns:
        A scalar, reduced by summation.
    """
    indices = (np.arange(len(y_true)), y_true)
    return neg(sum(log(getitem(y_pred, indices))))
예제 #3
0
def patches_index(imheight, imwidth, kernheight, kernwidth, stride_y,
                  stride_x):
    "Index to get image patches, e.g. for 2d convolution."
    max_y_idx = imheight - kernheight + 1
    max_x_idx = imwidth - kernwidth + 1
    row_major_index = np.arange(imheight * imwidth).reshape(
        [imheight, imwidth])
    patch_corners = row_major_index[0:max_y_idx:stride_y, 0:max_x_idx:stride_x]
    elements_relative = row_major_index[0:kernheight, 0:kernwidth]
    index_of_patches = patch_corners.reshape(
        [-1, 1]) + elements_relative.reshape([1, -1])
    index_of_patches = np.unravel_index(index_of_patches,
                                        shape=[imheight, imwidth])
    outheight, outwidth = patch_corners.shape
    n_patches = outheight * outwidth
    return index_of_patches, outheight, outwidth, n_patches
예제 #4
0
def onehot(y: np.ndarray, n_classes: int) -> np.array:
    "Onehot encode vector y with classes 0 to n_classes-1."
    result = np.zeros([len(y), n_classes])
    result[np.arange(len(y)), y] = 1
    return result