簡體   English   中英

如何使用 Keras 的功能 api 優化 model

[英]How to optimize a model using the functional api of Keras

我正在嘗試使用 Keras 的功能 api 構建一個 model。這是我制作的整個 model。 我不確定它是否正確,如果有人能看一下,我會很高興。

我首先將數據拆分為訓練和測試數據集。

from sklearn.model_selection import train_test_split

X1_train, X1_test, X2_train, X2_test, y_train, y_test = train_test_split(X1_scaled, X2_scaled, end_y, test_size=0.2)

[i.shape for i in (X1_train, X1_test, X2_train, X2_test, y_train, y_test)]

這是我開始構建 model 的部分

from tensorflow.keras import layers, Model, utils


# Build the model
input1 = layers.Input((10, 6))
input2 = layers.Input((10, 2, 5))
x1 = layers.Flatten()(input1)
x2 = layers.Flatten()(input2)

concat = layers.concatenate([x1, x2])

# Add hidden and dropout layers
hidden1 = layers.Dense(64, activation='relu')(concat)
hid1_out = layers.Dropout(0.5)(hidden1)
hidden2 = layers.Dense(32, activation='relu')(hid1_out)
hid2_out = layers.Dropout(0.5)(hidden2)
output = layers.Dense(1, activation='sigmoid')(hid2_out)

model = Model(inputs=[input1, input2], outputs=output)

# summarize layers
print(model.summary())

# compile the model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])


# fit the keras model on the dataset
history = model.fit([X1_train, X2_train], y_train, epochs=200, batch_size=5, verbose=0, validation_data=([X1_test, X2_test], y_test))

# evaluate the keras model
_, train_accuracy = model.evaluate([X1_train, X2_train], y_train, verbose=0)
_, test_accuracy = model.evaluate([X1_test, X2_test], y_test, verbose=0)
print('Accuracy NN: %.2f' % (train_accuracy*100))
print('Accuracy NN: %.2f' % (test_accuracy*100))

這里出現問題。 沒有顯示 plot。

# Plots
from matplotlib import pyplot

pyplot.subplot(211)
pyplot.title('Loss')
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='test')
pyplot.legend()

# plot accuracy
pyplot.subplot(212)
pyplot.title('Accuracy')
pyplot.plot(history.history['accuracy'], label='train')
pyplot.plot(history.history['val_accuracy'], label='test')
pyplot.legend()
pyplot.show(`

有人可以給我任何關於如何管理它的提示嗎?
謝謝你給我一些時間

下面是 function 的代碼,它將並排生成兩個圖。 第一個 plot 顯示了訓練損失和驗證損失與時期的關系。 第二個 plot 顯示訓練准確度和驗證准確度與時期的關系。 它還在第一個 plot 中放置一個點,表示驗證損失最低的時期,在第二個 plot 中放置一個點,表示驗證精度最高的時期。

def tr_plot(history):
    #Plot the training and validation data
    tacc=history.history['accuracy']
    tloss=history.history['loss']
    vacc=history.history['val_accuracy']
    vloss=history.history['val_loss']
    Epoch_count=len(tacc)
    Epochs=[]
    for i in range (Epoch_count):
        Epochs.append(i+1) 
    index_loss=np.argmin(vloss)#  this is the epoch with the lowest validation loss
    val_lowest=vloss[index_loss] # lowest validation loss value
    index_acc=np.argmax(vacc)  # this is the epoch with the highest training accuracy
    acc_highest=vacc[index_acc] # this is the highest accuracy value
    plt.style.use('fivethirtyeight')
    sc_label='best epoch= '+ str(index_loss+1 )
    vc_label='best epoch= '+ str(index_acc + 1)
    fig,axes=plt.subplots(nrows=1, ncols=2, figsize=(20,8))
    axes[0].plot(Epochs,tloss, 'r', label='Training loss')
    axes[0].plot(Epochs,vloss,'g',label='Validation loss' )
    axes[0].scatter(index_loss+1 ,val_lowest, s=150, c= 'blue', label=sc_label)
    axes[0].set_title('Training and Validation Loss')
    axes[0].set_xlabel('Epochs')
    axes[0].set_ylabel('Loss')
    axes[0].legend()
    axes[1].plot (Epochs,tacc,'r',label= 'Training Accuracy')
    axes[1].plot (Epochs,vacc,'g',label= 'Validation Accuracy')
    axes[1].scatter(index_acc+1 ,acc_highest, s=150, c= 'blue', label=vc_label)
    axes[1].set_title('Training and Validation Accuracy')
    axes[1].set_xlabel('Epochs')
    axes[1].set_ylabel('Accuracy')
    axes[1].legend()
    plt.tight_layout
    plt.show()

結果 plot 看起來像這樣這里。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM