Как я могу обучить автоэнкодер LSTM для каждой итерации обучения с каждым набором данных?Python

Программы на Python
Ответить
Anonymous
 Как я могу обучить автоэнкодер LSTM для каждой итерации обучения с каждым набором данных?

Сообщение Anonymous »

Описание
Я пытался создать и обучить автоэнкодер LSTM. Хотя ссылка, которую я использовал, обучала модель только один раз, я добавил функцию для многократного запуска обучения, если каждая итерация обучения для каждого набора данных закончилась.
Тем не менее, это не так. действительно уверен, на правильном ли я пути или нет. Такое ощущение, что есть вероятность, что мой код перезаписывает обученную модель на каждой итерации.
Вопрос
Поэтому я хотел бы спросить, приведенный ниже код Python фактически обучает модель для каждой итерации обучения с каждым набором данных (для обучения этой модели можно использовать 75 CSV-файлов).
Ниже приведен код Python, который я добавлено для построения и обучения модели внутри одной функции(trainModel())
from sklearn.preprocessing import StandardScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM, Dropout, RepeatVector, TimeDistributed
from tensorflow.keras.callbacks import EarlyStopping

# The LSTM network takes the input in the form of subsequences of equal intervals of input shape (n_sample,n_timesteps,features).
# We will use the below custom function to create these sequences
def create_sequences(X, y, time_steps=1):
Xs, ys = [], []
for i in range(len(X) - time_steps):
v = X.iloc[i:(i + time_steps)].values
Xs.append(v)
ys.append(y.iloc[i + time_steps])
return np.array(Xs), np.array(ys)

def trainModel():
for i in range(75):
fileList = pd.read_csv("/content/drive/MyDrive/fileList.csv")
filename = fileList.iloc[i, 0]
temp = pd.read_csv("/content/drive/MyDrive/dataFolder/"+filename+".csv")
train_size = int(len(temp[["time_abs(%Y-%m-%dT%H:%M:%S.%f)", "velocity(m/s)"]]))
train = df.iloc[0:train_size]

# Normalizing the data
scalar = StandardScaler()
scalar = scalar.fit(train[['velocity(m/s)']])

train['velocity(m/s)'] = scalar.transform(train[['velocity(m/s)']])

time_steps = 30

X_train, y_train = create_sequences(train[['velocity(m/s)']],train['velocity(m/s)'],time_steps)

# Build an LSTM Autoencoder

# An autoencoder is a neural network model that seeks to learn a compressed representation of an input.
# They are trained using supervised learning methods, referred to as self-supervised.

# In this architecture, an encoder LSTM model reads the input sequence step-by-step.
# After reading in the entire input sequence, the hidden state or output of this model represents
# an internal learned representation of the entire input sequence as a fixed-length vector.
# This vector is then provided as an input to the decoder model that interprets it as each step
# in the output sequence is generated.

timesteps = X_train.shape[1]
num_features = X_train.shape[2]

model = Sequential()
model.add(LSTM(128,input_shape=(timesteps,num_features)))
model.add(Dropout(0.2))
model.add(RepeatVector(timesteps)) # Repeats the input n times.
model.add(LSTM(128,return_sequences=True))
model.add(Dropout(0.2))
model.add(TimeDistributed(Dense(num_features))) # apply a layer to every temporal slice of an input.

model.compile(loss='mae',optimizer='adam')

# Train the Autoencoder
early_stop = EarlyStopping(monitor='val_loss',patience=3,mode='min') # if the monitored metric does not change wrt to the mode applied for 3 epochs, stop training
history = model.fit(X_train,y_train,epochs=100,batch_size=32,validation_split=0.1,callbacks=[early_stop],shuffle=False)

model.save('anomaly_model.h5', overwrite=False)
model.save('anomaly_model_'+ i +'.h5')


Подробнее здесь: https://stackoverflow.com/questions/790 ... h-each-dat
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»