How to train a model using Keras?

In Keras, model training is commonly accomplished by calling the fit method of the model. The fit method takes input data and labels, and trains the model based on the specified loss function and optimizer.

Here is a simple example demonstrating how to train a basic neural network model in Keras.

import numpy as np
from keras.models import Sequential
from keras.layers import Dense

# 生成一些随机的训练数据
X_train = np.random.random((1000, 20))
y_train = np.random.randint(2, size=(1000, 1))

# 创建一个简单的神经网络模型
model = Sequential()
model.add(Dense(64, input_dim=20, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

# 编译模型,定义损失函数和优化器
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# 训练模型
model.fit(X_train, y_train, epochs=10, batch_size=32)

In the example above, we first generated some random training data, then created a simple neural network model with two fully connected layers. Next, we compiled the model using the compile method, defining the loss function as binary cross-entropy, the optimizer as Adam, and specifying accuracy as the evaluation metric. Finally, we used the fit method to train the model, specifying the training data X_train and labels y_train, as well as the number of epochs and batch size.

I hope this example will help you get started training your model in Keras.

bannerAds