如何使用TensorFlow构建自定义结构的ANN神经网络?

实现代码及说明
首先修正你原代码的基础语法问题:
in是Python保留关键字,不能作为变量名使用- 数组定义多了多余的逗号
- 自定义损失函数没有返回损失值
- 缺少可训练权重的定义逻辑
完整可运行的实现如下:
import tensorflow as tf import numpy as np # 修正输入定义,增加batch维度适配TensorFlow输入规范 x_input = np.array([[1, 2, 3, 4]], dtype="float32") y_true = np.array([[10, 11]], dtype="float32") # 自定义实现匹配你需求的网络层 class CustomANNLayer(tf.keras.layers.Layer): def __init__(self): super().__init__() def build(self, input_shape): # 定义可训练权重w,长度为2,trainable=True表示反向传播时会被优化器更新 self.w = self.add_weight(shape=(2,), initializer="random_normal", trainable=True) def call(self, inputs): # 完全对齐你注释中的计算逻辑 y_pred_1 = (inputs[:, 0] + inputs[:, 1]) * self.w[0] y_pred_2 = (inputs[:, 2] + inputs[:, 3]) * self.w[1] y_pred = tf.stack([y_pred_1, y_pred_2], axis=1) # sigmoid激活 y_pred1 = tf.sigmoid(y_pred) return y_pred1 # 构建当前网络模型 input_layer = tf.keras.Input(shape=(4,)) current_output = CustomANNLayer()(input_layer) model = tf.keras.Model(inputs=input_layer, outputs=current_output) # 自定义损失函数 def loss_fun(y_true, y_pred1): return tf.reduce_sum(tf.pow(y_pred1 - y_true, 2)) # 编译模型,指定优化器后会自动更新可训练权重 model.compile(loss=loss_fun, optimizer='adam', metrics=['accuracy']) # 训练模型 model.fit(x_input, y_true, epochs=10, batch_size=1) # 如需接入下游ANN,直接把current_output作为下游层的输入即可,示例: # downstream_out = DownstreamANNLayer()(current_output) # full_model = tf.keras.Model(inputs=input_layer, outputs=downstream_out)
提示:当前你使用sigmoid激活后输出范围是[0,1],但标签值为10、11,训练时损失会长期处于较高水平,建议根据实际需求调整激活函数或对标签做归一化处理。
内容的提问来源于stack exchange,提问作者ewr3243
相关产品推荐
相关产品推荐

