【问题标题】:How to read from CSV file如何从 CSV 文件中读取
【发布时间】:2019-05-27 00:45:36
【问题描述】:

我试图了解非线性系统的Kalman Filter 是如何工作的。在搜索示例时,我发现this 很好的基本示例。

import numpy as np
import pylab as pl
import pandas as pd
from pykalman import UnscentedKalmanFilter

# initialize parameters
def transition_function(state, noise):
    a = np.sin(state[0]) + state[1] * noise[0]
    b = state[1] + noise[1]
    return np.array([a, b])

def observation_function(state, noise):
    C = np.array([[-1, 0.5], [0.2, 0.1]])
    return np.dot(C, state) + noise

transition_covariance = np.eye(2)
random_state = np.random.RandomState(0)
observation_covariance = np.eye(2) + random_state.randn(2, 2) * 0.1
initial_state_mean = [0, 0]
initial_state_covariance = [[1, 0.1], [-0.1, 1]]

# sample from model
kf = UnscentedKalmanFilter(
    transition_function, observation_function,
    transition_covariance, observation_covariance,
    initial_state_mean, initial_state_covariance,
    random_state=random_state
)
states, observations = kf.sample(50, initial_state_mean)

# estimate state with filtering and smoothing
filtered_state_estimates = kf.filter(observations)[0]
smoothed_state_estimates = kf.smooth(observations)[0]

# draw estimates
pl.figure()
lines_true = pl.plot(states, color='b')
lines_filt = pl.plot(filtered_state_estimates, color='r', ls='-')
lines_smooth = pl.plot(smoothed_state_estimates, color='g', ls='-.')
pl.legend((lines_true[0], lines_filt[0], lines_smooth[0]),
          ('true', 'filt', 'smooth'),
          loc='lower left'
)
pl.show()

此代码生成以下图表。

但是,对于我的实验 - 我创建了一个非常小的时间序列数据,其中包含如下格式的三列。完整的数据集附在here 以供重复使用。

  time        X      Y
 0.040662  1.041667  1
 0.139757  1.760417  2
 0.144357  1.190104  1
 0.145341  1.047526  1
 0.145401  1.011882  1
 0.148465  1.002970  1
 ....      .....     .

我们如何从我附加的CSV 文件中输入而不是使用代码中显示的随机值?这是我的方法,但它似乎不适合我,我将不胜感激。

df = pd.read_csv('testdata.csv')
pd.set_option('use_inf_as_null', True)

df.dropna(inplace=True)

X = df.drop('Y', axis=1)
y = df['Y']


d1= np.array(X)
d2 = np.array(y)

【问题讨论】:

  • 我想你会在这里找到答案:stackoverflow.com/questions/43749472/…
  • @rankind,先生,这对我没有多大帮助。谢谢
  • 您在尝试 csv 文件时遇到了什么错误?
  • @AI_Learning,这是我得到的错误ValueError: could not broadcast input array from shape (377,2) into shape (377)
  • 请发布错误的完整回溯,否则很难理解您在哪里得到了这个错误。

标签: python-3.x pandas csv numpy kalman-filter


【解决方案1】:

从我分享的链接中,您可以将 CSV 数据导入 Numpy 数组。

import numpy as np
import csv

with open('testdata.csv','r') as csvfile:
    r = csv.reader(csvfile, delimiter=',')
    data = [i for i in r]

headings = data.pop(0)
data = np.array([[np.float(j) for j in i] for i in data])

T = data.T[0] #Time
X = data.T[1] #X
Y = data.T[2] #Y

print(T)
print(X)
print(Y)

【讨论】:

  • 因此,如果您能尝试复制我发布的内容并使用可行的解决方案更新您的答案,以便我将您的答案标记为已接受,我将不胜感激。谢谢。
  • "我们如何从我附加的 CSV 文件中输入,而不是使用代码中显示的随机值?"
猜你喜欢
  • 2021-07-05
  • 2013-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-22
  • 2016-11-02
相关资源
最近更新 更多