- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用 Keras 构建一个模型,以根据传感器的类型和相同类型传感器的历史数据来预测传感器的时间序列。
下图显示了 3 个时间序列,由 3 个相同类型的传感器生成,绿色虚线是新传感器数据,垂直线是新传感器数据结束的地方。
我曾尝试编写一个 LSTM 网络,该网络对其他传感器的历史数据进行训练,一次提供一个历史数据,但这导致 LSTM 在预测新传感器时考虑传感器的最后一天。
所以我猜我走错了路。根据其他同类时间序列的历史,仅用几个历史样本来预测时间序列的选项有哪些?
任何帮助/引用/视频将不胜感激。
更新:
我想详细说明一下,传感器“分数”(如上图所示)是从随时间收集的一组特征生成的。 IE:
⨍(event_1_count ,event_2_count ,event_3_count ,days_since_last_event_1 ) = 分数
+----------+----+--------------+--------------+--------------+------------------------+
|sensor_id |day |event_1_count |event_2_count |event_3_count |days_since_last_event_1 |
+----------+----+--------------+--------------+--------------+------------------------+
| 1 |0 | 2 | 1 | 0 | 0 |
+----------+----+--------------+--------------+--------------+------------------------+
| 1 |1 | 0 | 10 | 2 | 1 |
+----------+----+--------------+--------------+--------------+------------------------+
| 1 |2 | 0 | 1 | 0 | 2 |
... until last day
+----------+----+--------------+--------------+--------------+------------------------+
| 2 |0 | 2 | 1 | 0 | 0 |
+----------+----+--------------+--------------+--------------+------------------------+
| 2 |1 | 0 | 10 | 2 | 1 |
+----------+----+--------------+--------------+--------------+------------------------+
| 2 |2 | 0 | 1 | 0 | 2 |
... until last day
+----------+----+--------------+--------------+--------------+------------------------+
| 3 |0 | 2 | 1 | 0 | 0 |
+----------+----+--------------+--------------+--------------+------------------------+
| 3 |1 | 0 | 10 | 2 | 1 |
+----------+----+--------------+--------------+--------------+------------------------+
| 3 |2 | 0 | 1 | 0 | 2 |
... until last day
+----------+----+--------------+--------------+--------------+------------------------+
|sensor_id |day |event_1_count |event_2_count |event_3_count |days_since_last_event_1 |
+----------+----+--------------+--------------+--------------+------------------------+
| 4 |0 | 2 | 1 | 0 | 0 |
+----------+----+--------------+--------------+--------------+------------------------+
| 4 |1 | 0 | 10 | 2 | 1 |
+----------+----+--------------+--------------+--------------+------------------------+
| 4 |2 | 0 | 1 | 0 | 2 |
---END OF DATA---
最佳答案
有不同的方法,具体取决于您的确切设置和所需的输出。
版本 A
如果您想拥有一个 LSTM 模型,该模型可以获取大量数据并预测下一步,这里有一个独立的示例。
合成数据与您的图中显示的数据仅略有相似,但我希望它仍然对说明有用。
上图中的预测显示了所有时间序列块都已知的情况,并且对于每个块都预测了下一步。
下面的面板显示了更现实的情况,其中所讨论的时间序列的开始是已知的,其余部分是迭代预测的,一次一个步骤。显然,预测误差可能会随着时间的推移而累积和增长。
# import modules
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import keras
import keras.models
import keras.layers
import sklearn
import sklearn.metrics
# please load auxiliary functions defined below!
# (omitted here for better readability)
# set seed
np.random.seed(42)
# number of time series
n_samples = 5
# number of steps used for prediction
n_steps = 50
# number of epochs for LSTM training
epochs = 100
# create synthetic data
# (see bottom left panel below, very roughly resembling your data)
tab = create_data(n_samples)
# train model without first column
x_train, y_train = prepare_data(tab.iloc[:, 1:], n_steps=n_steps)
model, history = train_model(x_train, y_train, n_steps=n_steps, epochs=epochs)
# predict first column for testing
# (all chunks are known and only on time step is predicted for each)
veo = tab[0].copy().values
y_test, y_pred = predict_all(veo, model)
# predict iteratively
# (first chunk is known and new values are predicted iteratively)
vec = veo.copy()
y_iter = predict_iterative(vec, n_steps, model)
# plot results
plot_single(y_test, [y_pred, y_iter], n_steps)
# please load auxiliary functions defined below!
# (omitted here for better readability)
# number of time series
n_samples = 10
# create synthetic data
# (see bottom left panel below, very roughly resembling your data)
tab = create_data(n_samples)
# prepare training data
x_train = tab.iloc[:n_steps, 1:].values.T
x_train = x_train.reshape(*x_train.shape, 1)
y_train = tab.iloc[n_steps:, 1:].values.T
print(x_train.shape) # (9, 50, 1) = old shape, 1D time series
# create additional dummy features to demonstrate usage of nD time series input data
# (feature_i = factor_i * score_i, with sum_i factor_i = 1)
feature_factors = [0.3, 0.2, 0.5]
x_train = np.dstack([x_train] + [factor*x_train for factor in feature_factors])
print(x_train.shape) # (9, 50, 4) = new shape, original 1 + 3 new features
# create LSTM which predicts everything beyond n_steps
n_steps_out = len(tab) - n_steps
model, history = train_model(x_train, y_train, n_steps=n_steps, epochs=epochs,
n_steps_out=n_steps_out)
# prepare test data
x_test = tab.iloc[:n_steps, :1].values.T
x_test = x_test.reshape(*x_test.shape, 1)
x_test = np.dstack([x_test] + [factor*x_test for factor in feature_factors])
y_test = tab.iloc[n_steps:, :1].values.T[0]
y_pred = model.predict(x_test)[0]
# plot results
plot_multi(history, tab, y_pred, n_steps)
n_features = x_train.shape[2]
在 LSTM 网络设置功能中。在将它们输入网络之前,请确保您的单个特征被正确缩放(例如 [0-1])。当然,预测质量在很大程度上取决于实际数据。
def create_data(n_samples):
# window width for rolling average
window = 10
# position of change in trend
thres = 200
# time period of interest
dates = pd.date_range(start='2020-02-16', end='2020-03-15', freq='H')
# create data frame
tab = pd.DataFrame(index=dates)
lend = len(tab)
lin = np.arange(lend)
# create synthetic time series
for ids in range(n_samples):
trend = 4 * lin - 3 * (lin-thres) * (lin > thres)
# scale to [0, 1] interval (approximately) for easier handling by network
trend = 0.9 * trend / max(trend)
noise = 0.1 * (0.1 + trend) * np.random.randn(lend)
vec = trend + noise
tab[ids] = vec
# compute rolling average to get smoother variation
tab = tab.rolling(window=window).mean().iloc[window:]
return tab
def split_sequence(vec, n_steps=20):
# split sequence into chunks of given size
x_trues, y_trues = [], []
steps = len(vec) - n_steps
for step in range(steps):
ilo = step
iup = step + n_steps
x_true, y_true = vec[ilo:iup], vec[iup]
x_trues.append(x_true)
y_trues.append(y_true)
x_true = np.array(x_trues)
y_true = np.array(y_trues)
return x_true, y_true
def prepare_data(tab, n_steps=20):
# convert data frame with multiple columns into chucks
x_trues, y_trues = [], []
if tab.ndim == 2:
arr = np.atleast_2d(tab).T
else:
arr = np.atleast_2d(tab)
for col in arr:
x_true, y_true = split_sequence(col, n_steps=n_steps)
x_trues.append(x_true)
y_trues.append(y_true)
x_true = np.vstack(x_trues)
x_true = x_true.reshape(*x_true.shape, 1)
y_true = np.hstack(y_trues)
return x_true, y_true
def train_model(x_train, y_train, n_units=50, n_steps=20, epochs=200,
n_steps_out=1):
# get number of features from input data
n_features = x_train.shape[2]
# setup network
# (feel free to use other combination of layers and parameters here)
model = keras.models.Sequential()
model.add(keras.layers.LSTM(n_units, activation='relu',
return_sequences=True,
input_shape=(n_steps, n_features)))
model.add(keras.layers.LSTM(n_units, activation='relu'))
model.add(keras.layers.Dense(n_steps_out))
model.compile(optimizer='adam', loss='mse', metrics=['mse'])
# train network
history = model.fit(x_train, y_train, epochs=epochs,
validation_split=0.1, verbose=1)
return model, history
def predict_all(vec, model):
# split data
x_test, y_test = prepare_data(vec, n_steps=n_steps)
# use trained model to predict all data points from preceeding chunk
y_pred = model.predict(x_test, verbose=1)
y_pred = np.hstack(y_pred)
return y_test, y_pred
def predict_iterative(vec, n_steps, model):
# use last chunk to predict next value, iterate until end is reached
y_iter = vec.copy()
lent = len(y_iter)
steps = lent - n_steps - 1
for step in range(steps):
print(step, steps)
ilo = step
iup = step + n_steps + 1
x_test, y_test = prepare_data(y_iter[ilo:iup], n_steps=n_steps)
y_pred = model.predict(x_test, verbose=0)
y_iter[iup] = y_pred
return y_iter[n_steps:]
def plot_single(y_test, y_plots, n_steps, nrows=2):
# prepare variables for plotting
metric = 'mse'
mima = [min(y_test), max(y_test)]
titles = ['all', 'iterative']
lin = np.arange(-n_steps, len(y_test))
# create figure
fig, axis = plt.subplots(figsize=(16, 9),
nrows=2, ncols=3)
# plot time series
axia = axis[1, 0]
axia.set_title('original data')
tab.plot(ax=axia)
axia.set_xlabel('time')
axia.set_ylabel('value')
# plot network training history
axia = axis[0, 0]
axia.set_title('training history')
axia.plot(history.history[metric], label='train')
axia.plot(history.history['val_'+metric], label='test')
axia.set_xlabel('epoch')
axia.set_ylabel(metric)
axia.set_yscale('log')
plt.legend()
# plot result for "all" and "iterative" prediction
for idy, y_plot in enumerate(y_plots):
# plot true/predicted time series
axia = axis[idy, 1]
axia.set_title(titles[idy])
axia.plot(lin, veo, label='full')
axia.plot(y_test, label='true')
axia.plot(y_plot, label='predicted')
plt.legend()
axia.set_xlabel('time')
axia.set_ylabel('value')
axia.set_ylim(0, 1)
# plot scatter plot of true/predicted data
axia = axis[idy, 2]
r2 = sklearn.metrics.r2_score(y_test, y_plot)
axia.set_title('R2 = %.2f' % r2)
axia.scatter(y_test, y_plot)
axia.plot(mima, mima, color='black')
axia.set_xlabel('true')
axia.set_ylabel('predicted')
plt.tight_layout()
return None
def plot_multi(history, tab, y_pred, n_steps):
# prepare variables for plotting
metric = 'mse'
# create figure
fig, axis = plt.subplots(figsize=(16, 9),
nrows=1, ncols=2, squeeze=False)
# plot network training history
axia = axis[0, 0]
axia.set_title('training history')
axia.plot(history.history[metric], label='train')
axia.plot(history.history['val_'+metric], label='test')
axia.set_xlabel('epoch')
axia.set_ylabel(metric)
axia.set_yscale('log')
plt.legend()
# plot true/predicted time series
axia = axis[0, 1]
axia.plot(tab[0].values, label='true')
axia.plot(range(n_steps, len(tab)), y_pred, label='predicted')
plt.legend()
axia.set_xlabel('time')
axia.set_ylabel('value')
axia.set_ylim(0, 1)
plt.tight_layout()
return None
关于python keras - 预测时间序列,基于相似序列的历史样本很少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61484189/
我遇到了一个让我非常难过的问题。但现在看来这一定是一个普遍的问题,我很惊讶我找不到关于它的另一个问题。 基本上,我的网站上会出现一些图标。我希望它们在每台设备上都显示出大致相同的大小——大致是可触摸的
我是一名 Java 专业人士。现在我喜欢转向其他编程语言。谁能建议我哪种编程语言更容易消化,并且该语言具有 Web 开发功能。我对 Web 开发感兴趣。 最佳答案 C# - 网络开发非常好(只需看看这
我需要为不同的 url 发送不同的响应。但是我正在使用的正则表达式不起作用。 有问题的两个正则表达式是 "/v1/users/[^/]+/permissions/domain/HTTP/" (例
让我描述一下我的问题。有一个输入字符串和一个包含数千个字符串的表。我正在寻找搜索与输入字符串最相似* 字符串的最佳方法。搜索应该返回一个包含 ~10 个建议字符串的列表,按相似度排序。字符串在数据库中
我在使用 crypt() 时遇到问题,如果用户有密码(本例中为 password1),并且他们将其更改为 password2,则散列会返回相同的结果。您可以在此处进行测试:旧链接输入 password
我问这个是因为我发现 XML 在视觉上没有吸引力。我知道 XML 非常有名,很有用,而且它被大多数(如果不是全部)程序员接受为一种非常有用的定义和结构化数据的语言;然而,我真的不觉得盯着它看、看着它或
我有工作需要在 14 天内完成。我有5名 worker 。一天正好需要3个 worker 。每个 worker 最多只能工作 9 天。每个 worker 都有自己的日期偏好,每个 worker 每天都
FileStream 或 DB 句柄类型的对象必须正确关闭,因为它在内部使用 Windows 句柄。同样,Threads 也使用 Windows 句柄吧?线程是否有一些内部机制来释放那些 Window
如果这是非常基本的,请原谅。我一直在尝试遍历行数组中的每个单元格包括标题单元格。我可以在 Nokogiri CSS 选择器中使用 OR 运算符吗? thang= Nokogiri::HTML(IO.r
默认情况下,RichTextFx(顶部控件)看起来不像 TextArea(底部控件): 我找到了一种添加圆角的方法(只需从 modena.css 复制并配置 some styles): .virtua
在 64 位 Java 中,每个对象实例往往包含一个 192-bit header , 包含 类指针, 标志和 锁(每个 64 位)。 这可能会导致小对象的大量内存开销。 尼姆的情况是否类似?用两种语
我正在开发一个具有多个功能(通过 tableview 选择)的应用程序,这些功能几乎都做同样的事情,相似的布局、相似的按钮、相似的输入字段等等。但在我相信它们自己的地方有足够的不同类(class)。每
题目地址:https://leetcode-cn.com/problems/similar-rgb-color/ 题目描述 Inthe following, every capital lette
我正在编写 R 代码,我希望它在“非调试”或“调试”模式下运行。在 Debug模式下,我希望代码打印出运行时信息。 在其他语言中,我通常会有某种打印功能,除非打开标志(用于编译或运行时),否则什么都不
我不明白这个OP接受的答案的一部分: Javascript function scoping and hoisting 作者说: " 此外,在这种情况下, function a() {} 行为与相同
我正在做一个bcmp(&v6_addr1,&v6_addr2,sizeof(v6_addr1)) (gdb) p v6_addr2 $15 = {u = {b = "0\001", '\000' ,
我有一个充满按钮的 Canvas,我将其 ID 存储在字典中。 Canvas 很长,带有垂直滚动条。有一种方法可以自动将 View 定位在给定的按钮上吗? 当使用 Text 时,txt.see(pos
我正在尝试使用 Python 2.6 和 PIL 计算两个图像的相似度(读作:Levenshtein 距离)。 我打算给我们e python-levenshtein用于快速比较的库。 主要问题: 什么
换句话说,php $object->method(); 和 $object->property = 'someValue'; 相当于,js: $object.method(); 和 $object.p
我写了一个简单的函数,它接收实现 .index() 的东西和要检查的字符列表。 我的假设是,由于字符串和元组都是不可变的,因此它们具有相似的性能(或者至少,元组的性能优于列表)。相反,元组似乎等同于列
我是一名优秀的程序员,十分优秀!