def compile_train(model, data_train, data_label,data_val,label_val, deep=True): if (deep == True): import matplotlib.pyplot as plt model.compile(loss='binary_crossentropy', optimizer = 'Adam', metrics=['accuracy']) history = model.fit(data_train, data_label,validation_data=(data_val,label_val) ,epochs=10, batch_size=256,verbose=1) plt.plot(history.history['accuracy']) plt.plot(history.history['loss']) plt.title('Train Accuracy and Loss') plt.ylabel('Accuracy/Loss') plt.xlabel('Epoch') plt.legend(['accuracy', 'loss'], loc='upper left') plt.show() plt.plot(history.history['val_accuracy']) plt.plot(history.history['val_loss']) plt.title('Verification Accuracy and Loss') plt.ylabel('Accuracy/Loss') plt.xlabel('Epoch') plt.legend(['accuracy', 'loss'], loc='upper left') plt.show() print('Model Compiled and Trained') return model改成应用于模型本身
时间: 2023-08-10 09:02:48 浏览: 172
SPD-Conv-main.zip
好的,以下是将`compile_train`函数应用于Keras模型本身的代码:
```
import matplotlib.pyplot as plt
def compile_train(model, X_train, y_train, X_val, y_val, deep=True):
if deep:
model.compile(loss='binary_crossentropy', optimizer='Adam', metrics=['accuracy'])
history = model.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=10, batch_size=256, verbose=1)
plt.plot(history.history['accuracy'])
plt.plot(history.history['loss'])
plt.title('Train Accuracy and Loss')
plt.ylabel('Accuracy/Loss')
plt.xlabel('Epoch')
plt.legend(['accuracy', 'loss'], loc='upper left')
plt.show()
plt.plot(history.history['val_accuracy'])
plt.plot(history.history['val_loss'])
plt.title('Validation Accuracy and Loss')
plt.ylabel('Accuracy/Loss')
plt.xlabel('Epoch')
plt.legend(['accuracy', 'loss'], loc='upper left')
plt.show()
print('Model Compiled and Trained')
else:
model.fit(X_train, y_train)
print('Model Trained')
return model
```
在这个函数中,我们将`compile`和`fit`方法应用于传递给函数的模型对象,而不是管道对象。如果`deep`参数为`True`,则使用`compile`方法进行模型编译,并使用`fit`方法训练模型。如果`deep`参数为`False`,则仅使用`fit`方法训练模型。在训练完模型后,函数会返回训练好的模型对象。
阅读全文