tensorflow.keras.layers.Layer官网介绍、样例代码

@创建于:20210629
@修改于:20210629

1、Layer官网介绍

| A layer is a callable object that takes as input one or more tensors and that outputs one or more tensors. It involves computation, defined in the call() method, and a state (weight variables), defined either in the constructor __init__() or in the build() method.

层是一个可调用对象,它以一个或多个张量作为输入并输出一个或多个张量。 它涉及在call() 方法中定义的计算,以及在构造函数__init__()build() 方法中定义的state(权重变量)。

We recommend that descendants of Layer implement the following methods:
我们建议 Layer 的后代实现以下方法:

  • __init__(): Defines custom layer attributes, and creates layer state variables that do not depend on input shapes, using add_weight().

  • __init__():定义自定义层属性,并使用 add_weight() 创建不依赖于输入形状的层状态变量。

  • build(self, input_shape): This method can be used to create weights that depend on the shape(s) of the input(s), using add_weight(). __call__() will automatically build the layer (if it has not been built yet) by calling build().

  • build(self, input_shape):此方法可用于创建依赖于输入形状的权重,使用 add_weight()__call__() 将通过调用 build() 自动构建层(如果尚未构建)。

  • call(self, *args, **kwargs): Called in __call__ after making sure build() has been called. call() performs the logic of applying the layer to the input tensors (which should be passed in as argument).

  • Two reserved keyword arguments you can optionally use in call() are:

    • training (boolean, whether the call is in inference mode or training mode)
    • mask (boolean tensor encoding masked timesteps in the input, used in RNN layers)
  • call(self, *args, **kwargs):在确保调用了 build() 之后在 __call__ 中调用。 call() 执行将层应用到输入张量(应该作为参数传入)的逻辑。
    您可以选择在 call() 中使用的两个保留关键字参数是:

    • training(布尔值,无论调用是在推理模式还是训练模式)
    • mask(布尔张量编码输入中的屏蔽时间步长,用于 RNN 层)
  • get_config(self): Returns a dictionary containing the configuration used to initialize this layer. If the keys differ from the arguments in __init__, then override from_config(self) as well. This method is used when saving the layer or a model that contains this layer.

  • get_config(self):返回一个包含用于初始化该层的配置的字典。如果键与 __init__ 中的参数不同,那么也覆盖 from_config(self)。保存图层或包含该图层的模型时使用此方法。

2、使用样例代码

2.1 使用样例

import tensorflow as tf


class TestDenseLayer(tf.keras.layers.Layer):
    def __init__(self, num_outputs):
        print('In __init__')
        super(TestDenseLayer, self).__init__()
        self.num_outputs = num_outputs

    def build(self, input_shape):
        print('In build')
        self.kernel = self.add_variable("kernel",
            shape=[int(input_shape[-1]), self.num_outputs])
        print('self.kernel = ', self.kernel.shape)

    def call(self, input):
        print('In call')
        return tf.matmul(input, self.kernel)


layer = TestDenseLayer(10)
input = tf.ones((2, 3))
print('input shape = {}, value is\n{}'.format(input.shape, input))
# 此处显式调用类中的call方法,但是在调用call方法前,自动调用build的方法。
result = layer(input)
print('result =', result)

2.2 输出结果

In __init__

input shape = (2, 3), value is
[[1. 1. 1.]
 [1. 1. 1.]]
 
In build
self.kernel =  (3, 10)

In call
result = tf.Tensor(
[[-0.81507313 -0.070647    0.5845617   0.1208241  -0.07275787  1.3390236
   1.0638947  -1.4866217   0.42016876 -0.28244376]
 [-0.81507313 -0.070647    0.5845617   0.1208241  -0.07275787  1.3390236
   1.0638947  -1.4866217   0.42016876 -0.28244376]], shape=(2, 10), dtype=float32)

3、参考资料

tensorflow2.0中Layer的__init__(),build(), call()函数
官网:https://www.tensorflow.org/guide/keras/custom_layers_and_models

### 使用 TensorFlow.NET 和 Keras 进行线性回归并从 CSV 文件加载数据 以下是如何使用 TensorFlow.NET 和 Keras 实现线性回归,并从 CSV 文件中加载数据的完整示。此示涵盖了数据读取、预处理、模型构建、编译和训练的过程。 --- #### 加载依赖项 首先,确保已安装必要的库(如 Pandas 和 TensorFlow.NET),并通过 C# 导入这些库以支持数据分析和深度学习功能[^1]。 ```csharp using System; using System.Linq; using Tensorflow; using static Tensorflow.Binding; using NumSharp; // 数组操作工具 using Pandas; // 数据分析工具 ``` --- #### 读取 CSV 数据 使用 Pandas 库读取存储在本地路径中的 CSV 文件,并提取特征列和目标列作为输入变量 \(X\) 和输出变量 \(Y\)[^2]。 ```csharp // Step 1: Load the dataset from a CSV file. var data = DataFrame.ReadCsv("path/to/your/data.csv"); // 替换为实际文件路径 // Extract features (e.g., 'Feature1', 'Feature2') and target ('Target'). NDArray<float> X = data[["Feature1", "Feature2"]].ToNumpy().Cast<float>(); // 特征矩阵 NDArray<float> Y = data[["Target"]].ToNumpy().Cast<float>(); // 目标向量 Console.WriteLine("Data loaded successfully."); ``` --- #### 创建线性回归模型 通过 `tf.keras.Sequential` 定义一个简单的线性回归模型。在此模型中,仅需一层全连接层(Dense Layer)即可完成任务[^3]。 ```csharp // Step 2: Build the linear regression model. var model = tf.keras.models.Sequential(); // 添加 Dense 层,设置 units=1 表示单个输出节点。 model.Add(tf.keras.layers.Dense(units: 1, input_shape: new Shape(X.shape[1]))); Console.WriteLine("Model created."); ``` --- #### 编译模型 指定优化器(如 SGD 或 Adam)、损失函数(如 MSE)以及评估指标(如 MAE)。这一步决定了模型的学习策略和评价标准[^3]。 ```csharp // Step 3: Compile the model with an optimizer and loss function. model.compile( optimizer: tf.keras.optimizers.SGD(learning_rate: 0.01), loss: "mean_squared_error", metrics: new[] { "mean_absolute_error" } ); Console.WriteLine("Model compiled."); ``` --- #### 训练模型 将先前准备好的数据传递给模型进行训练。可以通过调整 epoch 数量或 batch size 来控制训练过程的质量与效率[^2]。 ```csharp // Step 4: Train the model on the provided dataset. model.fit( x: X, y: Y, epochs: 100, batch_size: 32, verbose: 1 ); Console.WriteLine("Training completed."); ``` --- #### 测试预测能力 验证模型是否能准确估计未见过的新本值。此处展示了一个简单的子来说明如何调用 `.predict()` 方法获取结果[^1]。 ```csharp // Step 5: Test the trained model by predicting unseen samples. var testSample = np.array(new float[][] { new float[] { 5.0f, 3.0f } }); // 假设这是新的测试 var prediction = model.predict(testSample).numpy()[0][0]; Console.WriteLine($"Predicted value for sample [5.0, 3.0]: {prediction:F2}"); ``` 以上就是完整的基于 TensorFlow.NET 和 Keras 的线性回归实现方法,同时包含了从 CSV 文件加载数据的功能[^2]. --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值