【问题标题】:numpy.genfromtxt return NaN valuesnumpy.genfromtxt 返回 NaN 值
【发布时间】:2019-06-20 20:36:10
【问题描述】:

我正在尝试绘制 csv 文件的第二列,但第二列返回 nan 值。如果我设置 dtype= None 或 dtype= str 将返回字符串值,最终导致在 Y 轴上以错误的方式绘图。任何意见将不胜感激。

csv 中的第二列包含 80-99% 的值,之前保存的值像这样 sn-p

 numpy.savetxt('loss_acc_exp4.csv', numpy.c_[losses, ACCes], fmt=['%.4f', '%d %%'], header= "loss, acc", comments='', delimiter = ",")                    

这里是用于绘制 csv 文件的 sn-p

import numpy
import matplotlib.pyplot as plt
acc_history = numpy.genfromtxt("loss_acc_exp4.csv", delimiter=",", 
skip_header=1, usecols=(1))


num_epochs = 151
epochs = range(1, num_epochs)

plt.figure(figsize=(10,6))
plt.plot(epochs, acc_history[::2], '-b', label='Training accuracy') #plot odd rows
plt.plot(epochs, acc_history[1::2], '-r', label='Validation accuracy') # plot even rows
plt.legend()
plt.xlabel('Epoch')
plt.ylabel('accuracy')
plt.xlim(0.01,151)
plt.show()

csv中的数据是这样的

import pandas as pd


def convert_percent(val):
"""
Convert the percentage string to an actual floating point percent
- Remove %
- Divide by 100 to make decimal
"""
new_val = val.replace('%', '')
new_val = pd.Series([new_val]).astype(float)
return (new_val) / 100

acc_history = pd.read_csv("loss_acc_exp4.csv", delimiter=",", header=0, 
usecols=[1], dtype=None)
acc_history[:].apply(convert_percent)

它正在返回ValueError: ('setting an array element with a sequence.', 'occurred at index acc')

【问题讨论】:

  • 您能分享一下您的loss_acc_exp4.csv 文件是什么样的吗?这是了解格式所必需的。
  • 默认数据类型是浮点数。不适合的字符串以 nan 形式返回。
  • @newkid 抱歉。我的问题是关于 acc col。
  • @Neda 你能在你的问题中添加一个片段吗?从您的评论中不清楚文件的格式(换行符、分隔符、精度等)
  • 是 '%' 字符阻止 genfromtxt 将字符串转换为数字。试试float('91%')。您可以使用dtype=None 加载,然后自己转换这些字符串。或者编写一个转换器来删除 '%' 并返回一个浮点数,例如float(astr[:-1])。或者更改savetxt 以省略不必要的'%'。

标签: python numpy matplotlib genfromtxt


【解决方案1】:

使用转换器:

def foo(astr):
    return float(astr[:-1])
In [296]: np.genfromtxt('test.csv', delimiter=',', converters={1:foo})
Out[296]: 
array([[ 0.8469, 99.    ],
       [ 0.3569, 98.    ],
       [ 0.9622, 97.    ],
       [ 0.4774, 96.    ],
       [ 0.381 , 95.    ]])

【讨论】:

    猜你喜欢
    • 2018-04-29
    • 1970-01-01
    • 2020-05-27
    • 2014-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多