How to use tensorly - 10 common examples

To help you get started, we’ve selected a few tensorly examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github tensorly / tensorly / tensorly / datasets / synthetic.py View on Github external
large_height = (image_height // 2) - (image_height // 4)
        large_width = (image_width // 2) - (image_width // 4)
        weight[large_height:-large_height, large_width:-large_width] = weight_value

    elif region is "circle":
        radius = image_width // 3
        cy = image_width // 2
        cx = image_height // 2
        y, x = np.ogrid[-radius: radius, -radius: radius]
        index = x**2 + y**2 <= radius**2
        weight[cy-radius:cy+radius, cx-radius:cx+radius][index] = 1

    if n_channels is not None and weight.ndim == 2:
        weight = np.concatenate([weight[..., None]]*n_channels, axis=-1)

    return T.tensor(weight)
github tensorly / tensorly / tensorly / contrib / test_mps_decomposition_cross.py View on Github external
def test_matrix_product_state_cross_1():
    """ Test for matrix_product_state """
    rng = check_random_state(1234)

    ## Test 1

    # Create tensor with random elements
    d = 3
    n = 4
    tensor = (np.arange(n**d).reshape((n,)*d))
    tensor = tl.tensor(tensor)


    tensor_shape = tensor.shape

    # Find MPS decomposition of the tensor
    rank = [1, 3,3, 1]
    factors = matrix_product_state_cross(tensor, rank, tol=1e-5, n_iter_max=10)
    assert(len(factors) == d), "Number of factors should be 4, currently has " + str(len(factors))

    # Check that the ranks are correct and that the second mode of each factor
    # has the correct number of elements
    r_prev_iteration = 1
    for k in range(d):
        (r_prev_k, n_k, r_k) = factors[k].shape
        assert(tensor_shape[k] == n_k), "Mode 1 of factor " + str(k) + "needs " + str(tensor_shape[k]) + " dimensions, currently has " + str(n_k)
        assert(r_prev_k == r_prev_iteration), " Incorrect ranks of factors "
github tensorly / tensorly / tensorly / contrib / test_mps_decomposition_cross.py View on Github external
def test_matrix_product_state_cross_2():
    """ Test for matrix_product_state """
    rng = check_random_state(1234)

    ## Test 2
    # Create tensor with random elements
    tensor = tl.tensor(rng.random_sample([3, 4, 5, 6, 2, 10]))
    tensor_shape = tensor.shape

    # Find MPS decomposition of the tensor
    rank = [1, 3, 3, 4, 2, 2, 1]
    factors = matrix_product_state_cross(tensor, rank)

    for k in range(6):
        (r_prev, n_k, r_k) = factors[k].shape

        first_error_message = "MPS rank " + str(k) + " is greater than the maximum allowed "
        first_error_message += str(r_prev) + " > " + str(rank[k])
        assert(r_prev<=rank[k]), first_error_message

        first_error_message = "MPS rank " + str(k+1) + " is greater than the maximum allowed "
        first_error_message += str(r_k) + " > " + str(rank[k+1])
        assert(r_k<=rank[k+1]), first_error_message
github tensorly / tensorly / tensorly / contrib / test_mps_decomposition_cross.py View on Github external
maxvoleps = 1e-4
    tol = 1e-4
    n = 10
    d = 4
    rng = 1
    grid = getEquispaceGrid(d, rng, n)
    value = evaluateGrid(grid, func)
    value = tl.tensor(value)

    # Find MPS decomposition of the tensor
    rank = [1, 4, 4, 4, 1]
    factors = matrix_product_state_cross(value, rank, tol=tol)

    approx = mps_to_tensor(factors)
    error = tl.norm(approx-value,2)
    error /= tl.norm(value, 2)

    print(error)
    tl.assert_(error < 1e-5, 'norm 2 of reconstruction higher than tol')
github tensorly / tensorly / tensorly / contrib / test_mps_decomposition_cross.py View on Github external
def test_matrix_product_state_cross_3():
    """ Test for matrix_product_state """
    rng = check_random_state(1234)

    ## Test 3
    tol = 10e-5
    tensor = tl.tensor(rng.random_sample([3, 3, 3]))
    factors = matrix_product_state_cross(tensor, (1, 3, 3, 1))
    reconstructed_tensor = mps_to_tensor(factors)
    error = tl.norm(reconstructed_tensor - tensor, 2)
    error /= tl.norm(tensor, 2)
    tl.assert_(error < tol,
              'norm 2 of reconstruction higher than tol')
github tensorly / tensorly / tensorly / contrib / test_mps_decomposition_cross.py View on Github external
def test_matrix_product_state_cross_3():
    """ Test for matrix_product_state """
    rng = check_random_state(1234)

    ## Test 3
    tol = 10e-5
    tensor = tl.tensor(rng.random_sample([3, 3, 3]))
    factors = matrix_product_state_cross(tensor, (1, 3, 3, 1))
    reconstructed_tensor = mps_to_tensor(factors)
    error = tl.norm(reconstructed_tensor - tensor, 2)
    error /= tl.norm(tensor, 2)
    tl.assert_(error < tol,
              'norm 2 of reconstruction higher than tol')
github tensorly / tensorly / tensorly / contrib / test_mps_decomposition_cross.py View on Github external
def test_matrix_product_state_cross_1():
    """ Test for matrix_product_state """
    rng = check_random_state(1234)

    ## Test 1

    # Create tensor with random elements
    d = 3
    n = 4
    tensor = (np.arange(n**d).reshape((n,)*d))
    tensor = tl.tensor(tensor)


    tensor_shape = tensor.shape

    # Find MPS decomposition of the tensor
    rank = [1, 3,3, 1]
    factors = matrix_product_state_cross(tensor, rank, tol=1e-5, n_iter_max=10)
    assert(len(factors) == d), "Number of factors should be 4, currently has " + str(len(factors))
github tensorly / tensorly / tensorly / contrib / test_mps_decomposition_cross.py View on Github external
def test_matrix_product_state_cross_2():
    """ Test for matrix_product_state """
    rng = check_random_state(1234)

    ## Test 2
    # Create tensor with random elements
    tensor = tl.tensor(rng.random_sample([3, 4, 5, 6, 2, 10]))
    tensor_shape = tensor.shape

    # Find MPS decomposition of the tensor
    rank = [1, 3, 3, 4, 2, 2, 1]
    factors = matrix_product_state_cross(tensor, rank)

    for k in range(6):
        (r_prev, n_k, r_k) = factors[k].shape

        first_error_message = "MPS rank " + str(k) + " is greater than the maximum allowed "
        first_error_message += str(r_prev) + " > " + str(rank[k])
        assert(r_prev<=rank[k]), first_error_message
github tensorly / tensorly / examples / regression / plot_tucker_regression.py View on Github external
fig = plt.figure()

for i, pattern in enumerate(patterns):

    print('fitting pattern n.{}'.format(i))

    # Generate the original image
    weight_img = gen_image(region=pattern, image_height=image_height, image_width=image_width)
    weight_img = tl.tensor(weight_img)

    # Generate the labels
    y = tl.dot(partial_tensor_to_vec(X, skip_begin=1), tensor_to_vec(weight_img))

    # Plot the original weights
    ax = fig.add_subplot(n_rows, n_columns, i*n_columns + 1)
    ax.imshow(tl.to_numpy(weight_img), cmap=plt.cm.OrRd, interpolation='nearest')
    ax.set_axis_off()
    if i == 0:
        ax.set_title('Original\nweights')

    for j, rank in enumerate(ranks):
        print('fitting for rank = {}'.format(rank))

        # Create a tensor Regressor estimator
        estimator = TuckerRegressor(weight_ranks=[rank, rank], tol=10e-7, n_iter_max=100, reg_W=1, verbose=0)

        # Fit the estimator to the data
        estimator.fit(X, y)

        ax = fig.add_subplot(n_rows, n_columns, i*n_columns + j + 2)
        ax.imshow(tl.to_numpy(estimator.weight_tensor_), cmap=plt.cm.OrRd, interpolation='nearest')
        ax.set_axis_off()
github tensorly / tensorly / examples / regression / plot_kruskal_regression.py View on Github external
ax = fig.add_subplot(n_rows, n_columns, i*n_columns + 1)
    ax.imshow(tl.to_numpy(weight_img), cmap=plt.cm.OrRd, interpolation='nearest')
    ax.set_axis_off()
    if i == 0:
        ax.set_title('Original\nweights')

    for j, rank in enumerate(ranks):

        # Create a tensor Regressor estimator
        estimator = KruskalRegressor(weight_rank=rank, tol=10e-7, n_iter_max=100, reg_W=1, verbose=0)

        # Fit the estimator to the data
        estimator.fit(X, y)

        ax = fig.add_subplot(n_rows, n_columns, i*n_columns + j + 2)
        ax.imshow(tl.to_numpy(estimator.weight_tensor_), cmap=plt.cm.OrRd, interpolation='nearest')
        ax.set_axis_off()

        if i == 0:
            ax.set_title('Learned\nrank = {}'.format(rank))

plt.suptitle("Kruskal tensor regression")
plt.show()