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


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))

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])
# tensor([0.8760]), "")

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

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

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