4

I would like to plot pytorch gpu tensor:

input= torch.randn(100).to(device)
output = torch.where(input>=0, input, -input)

input = input.('cpu').detach().numpy().copy()
output = output.('cpu').detach().numpy().copy()

plt.plot(input,out)

However I try to convert those tensors into cpu, numpy, it does not work. How can I plot the tensors ?

2 Answers 2

1

Does this work?

plt.plot(input.cpu().numpy(),output.cpu().numpy())

Alternatively you can try,

plt.plot(input.to('cpu').numpy(),output.to('cpu').numpy())
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. But they say 'can't convert non-cpu tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.'
Hi @JennyRowland , I updated my answer, does that work?
plt.plot() accepts numpy arrays. The are sequence of operations to perform. First, assuming the tensor is on device(GPU), you need to copy it to CPU first by using .cpu(). Then the you need to change the data type from tensors to numpy by using .numpy(). so, it should be (a.cpu().numpy()).
FYI, I use output.numpy(Force=True) for this. pytorch.org/docs/stable/generated/torch.Tensor.numpy.html
0

To address multiple dimensions I've just written the following function

import matplotlib.pyplot as plt
def plot_tensor(X: Tensor) -> None:
    X_copy = X.clone().to("cpu")
    print(f"The input tensor contains {X_copy.shape[0]} points in {X_copy.shape[1]} dimensions")
    print(X_copy.tolist())
    print(f"Tensor on device {X.device}, shape {X.shape}, type {X.dtype} ")
    
    if X.shape[1] == 1:
        plt.scatter(X_copy[:, 0], np.zeros_like(X_copy[:, 0]))
        plt.title("1D Tensor Values")
        plt.xlabel("X1")
        plt.ylabel("Value")  

    if X.shape[1] == 2:
        plt.scatter(X_copy[:, 0], X_copy[:, 1])
        plt.title("2D Tensor Values")
        plt.xlabel("X1")
        plt.ylabel("X2")

    if X.shape[1] == 3:
        fig = plt.figure()
        ax = fig.add_subplot(projection='3d')
        ax.scatter(X_copy[:, 0], X_copy[:, 1], X_copy[:, 2])
        ax.set_title("3D Tensor Values")
        ax.set_xlabel("X1")
        ax.set_ylabel("X2")
        ax.set_zlabel("X3")

    plt.show()

2 Comments

I feel like this answer is a bit overcomplicated and doesn’t really solve the original problem directly.
well, you need to move the tensors on the CPU anyways, don't you? Beside that I've just added the dimension handling just to ensure proper plotting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.