一、Functional API 搭建神经网络模型
1.对宽深神经网络模型进行手写数字识别:
运行代码:
inputs = keras.layers.Input(shape=X_train.shape[1:])
hidden1 = keras.layers.Dense(300,activation="relu")(inputs)
hidden2 = keras.layers.Dense(100,activation="relu")(hidden1)
concat = keras.layers.concatenate([inputs,hidden2])
output = keras.layers.Dense(10, activation="softmax")(concat)model_fun_WideDeep=keras.models.Model(inputs=[inputs], outputs=[output])
输出结果:
2.观察神经网络的情况:
运行代码
model_fun_WideDeep.summary()
输出结果:
3.对数据集进行训练:
运行代码:
model_fun_WideDeep.compile(loss="sparse_categorical_crossentropy",optimizer="sgd", metrics=["accuracy"])
h=model_fun_WideDeep.fit(X_train,y_train,batch_size=32,epochs=30,validation_data=(X_valid, y_valid))
输出结果:
4.数据拆分成A与B两部分,进行输入:
运行代码:
X_train_A,X_train_B=X_train[:,:200],X_train[:,100:]
X_valid_A,X_valid_B=X_valid[:,:200],X_valid[:,100:]
input_A=keras.layers.Input(shape=X_train_A.shape[1])
input_B=keras.layers.Input(shape=X_train_B.shape[1])
hidden1=keras.layers.Dense(300,activation="relu")(input_B)
hidden2=keras.layers.Dense(100,activation="relu")(hidden1)
concat=keras.layers.concatenate([input_A,hidden2])
output=keras.layers.Dense(10,activation="softmax")(concat)
model_fun_MulIn=keras.models.Model(inputs=[input_A,input_B],outputs=[output])_
model_fun_MulIn.compile(loss="sparse_categorical_crossentropy",optimizer="sgd",metrics=["accuracy"])
输出结果:
进行训练:
二、SubClassing API 搭建神经网络模型
- 定义模型结构,隐藏层1、2,输出层,隐藏层的激活函数,调用函数,开始初始化
运行代码:
class Model_sub_fnn(keras.models.Model):def __init__(self,units_1=300,units_2=100,units_out=10,activation="relu"):super().__init__()self.hidden1=keras.layers.Dense(units_1,activation=activation)self.hidden2=keras.layers.Dense(units_2,activation=activation)self.main_output=keras.layers.Dense(units_out,activation="softmax")
- 将输入数据传给隐藏层1
运行代码:
def call(self,data):hidden1=self.hidden1(data)hidden2=self.hidden2(hidden1)main_output=self.main_output(hidden2)return main_output
model_sub_fnn=Model_sub_fnn()
model_sub_fnn2=Model_sub_fnn(300,100,10,activation="relu")
输出结果:
1.进行训练:
运行代码:
h=model_sub_fnn.fit(X_train,y_train,batch_size=32,epochs=30,validation_data=(X_valid,y_valid))
输出结果:
2.观察神经网络的情况:
运行代码:
model_sub_fnn.summary()
输出结果: