How to add a hidden layer to a neural network in Keras.
To add a hidden layer to a neural network in Keras, you need to use the Sequential model and add the hidden layer using the add method. Here is a simple example code:
from keras.models import Sequential
from keras.layers import Dense
# 创建一个Sequential模型
model = Sequential()
# 添加输入层和第一个隐藏层
model.add(Dense(units=128, activation='relu', input_shape=(input_shape,)))
# 添加第二个隐藏层
model.add(Dense(units=64, activation='relu'))
# 添加输出层
model.add(Dense(units=num_classes, activation='softmax'))
# 编译模型
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
In the example above, we start by creating a Sequential model, then we use the add method to add two hidden layers and one output layer. Each hidden layer has a specified number of neurons (units) and activation function. Finally, we compile the model, specifying the optimizer, loss function, and evaluation metrics.
Using a similar approach, you can continue to add more hidden layers to the neural network.