在LSTM预测模型中,是否可以迭代Pandas Dataframe ?

2cmtqfgy  于 2023-03-06  发布在  其他
关注(0)|答案(1)|浏览(142)

我导入以下模块:

import numpy as np
import pandas as pd
from tensorflow import keras
from tensorflow.keras.optimizers import Adam
from keras.models import Sequential
from keras.layers import LSTM, Densr, Bidirectional, Dropout
from sklearn.preprocessing import StandardScaler
  • --代码---
    print("The predicted numbers are:",scaler.inverse_transform(y_pred).astype(int)[0])这将打印一个预测数字数组。
    我想打印数据中某个行范围的预测数字数组。例如,
    导向头(0)至导向头(20)
    我在网上搜寻解决方案,但找不到。这有可能吗?
    我尝试了以下方法:
for index, row in df.iterrows():
    print(row)

这只会在处理数据之前遍历数据中的行

for column_name in df.iteritems():
    print(column_name)

这也是在处理数据之前对列进行的迭代

for index, row in np.array([scaled_to_predict]):
    print(row)

这返回了一个ValueError:要解包的值太多(应为2)

dbf7pr2w

dbf7pr2w1#

是的,您可以按照下面的示例进行操作:

import numpy as np
import pandas as pd
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Bidirectional, Dropout
from tensorflow.keras.optimizers import Adam
from sklearn.preprocessing import StandardScaler

data = np.random.randn(100, 5)
df = pd.DataFrame(data, columns=['A', 'B', 'C', 'D', 'E'])

train_size = int(len(df) * 0.8)
train = df[:train_size]
test = df[train_size:]

scaler = StandardScaler()
train_scaled = scaler.fit_transform(train)
test_scaled = scaler.transform(test)

def create_sequences(X, y, time_steps=10):
    Xs, ys = [], []
    for i in range(len(X) - time_steps):
        Xs.append(X[i:i + time_steps])
        ys.append(y[i + time_steps])
    return np.array(Xs), np.array(ys)

X_train, y_train = create_sequences(train_scaled[:, :-1], train_scaled[:, -1])
X_test, y_test = create_sequences(test_scaled[:, :-1], test_scaled[:, -1])

X_train = X_train.reshape(-1, 10, 5)
X_test = X_test.reshape(-1, 10, 5)

# create model
model = Sequential()
model.add(Bidirectional(LSTM(64, input_shape=(10, 5))))
model.add(Dropout(0.5))
model.add(Dense(1))

model.compile(loss='mse', optimizer=Adam(learning_rate=0.001))

model.fit(X_train, y_train, epochs=50, batch_size=32, validation_split=0.1, shuffle=False)

y_pred = model.predict(X_test)

y_test_zeros = np.zeros((len(y_test), 4))
y_test_concat = np.hstack((y_test.reshape(-1,1), y_test_zeros))

y_pred_concat = np.hstack((y_pred, np.zeros((len(y_pred), 4))))
y_pred_scaled = scaler.inverse_transform(y_pred_concat)[:, 0].astype(int)

print("The predicted numbers are:")
for i in range(len(y_pred_scaled)):
    print(y_pred_scaled[i])

该函数返回:

The predicted numbers are:
0
0
0
0
1
-1
0
0

因此,您只需执行以下操作:

y_pred_concat = np.hstack((y_pred, np.zeros((len(y_pred), 4))))
y_pred_scaled = scaler.inverse_transform(y_pred_concat)[:, 0].astype(int)

print("The predicted numbers are:")
for i in range(len(y_pred_scaled)):
    print(y_pred_scaled[i])

相关问题