Could not convert string to float: 'tensor(0.3494,'

Hi,

I’ve saved my model train and validation accuracy using with open( )... as f , f.close() in .txt format. The output is like this:

tensor(0.3494, device='cuda:0', dtype=torch.float64)
tensor(0.4721, device='cuda:0', dtype=torch.float64)
tensor(0.5966, device='cuda:0', dtype=torch.float64)
tensor(0.7131, device='cuda:0', dtype=torch.float64)
tensor(0.8192, device='cuda:0', dtype=torch.float64)
tensor(0.9051, device='cuda:0', dtype=torch.float64)
tensor(0.9604, device='cuda:0', dtype=torch.float64)
.
.
.

Now I want to plot the results:

accs_trn = np.loadtxt('Test/accs_trn.txt', dtype=float)
accs_val = np.loadtxt('Test/accs_val.txt', dtype=float)
plt.figure(figsize=(12, 4))
plt.plot(accs_trn[0][0])
plt.plot(accs_val[0][0])
plt.xlabel('Iteration')
plt.ylabel('Accuracy')
plt.title('model')
plt.show()

But I get this error:
ValueError: could not convert string to float: 'tensor(0.3494,'

I know what this error means but I don’t know how to handle it.
Can you please help me with how to use these .txt files to plot?

Since you’ve stored the data as strings you could use regex to match the actual floating point value and transform it into a float literal.

1 Like

Dear @ptrblck,
Thanks for your reply.

Can you help me with how I should save the accuracy of the model so I can be able to reload it and plot it easily?

You could save the binary data directly in numpy or PyTorch.
Here is a simple example:

accuracy = torch.tensor([0.876])
print(accuracy)
# tensor([0.8760])

torch.save(accuracy, "acc.pt")

loaded = torch.load("acc.pt")
print(loaded)
# tensor([0.8760])

# same for numpy
acc_np = accuracy.numpy()
with open("acc_np.npy", "wb") as f:
    np.save(f, acc_np)

np_loaded = np.load("acc_np.npy")
print(np_loaded)
# [0.876]
1 Like