如何使用Keras创建一个预先指定模型输入形状的模型?
Tensorflow是Google提供的一种机器学习框架。它是一个开放源代码框架,可与Python结合使用,以实现算法,深度学习应用程序等等。它用于研究和生产目的。
Keras被开发为ONEIROS(开放式神经电子智能机器人操作系统)项目研究的一部分。Keras是使用Python编写的深度学习API。它是一个高级API,具有可帮助解决机器学习问题的高效接口。
它在Tensorflow框架之上运行。它旨在帮助快速进行实验。它提供了在开发和封装机器学习解决方案中必不可少的基本抽象和构建块。
它具有高度的可扩展性,并具有跨平台功能。这意味着Keras可以在TPU或GPU集群上运行。Keras模型也可以导出为在Web浏览器或手机中运行。
Keras已经存在于Tensorflow软件包中。可以使用下面的代码行进行访问。
import tensorflow from tensorflow import keras
我们正在使用Google合作实验室来运行以下代码。GoogleColab或Colaboratory可以帮助通过浏览器运行Python代码,并且需要零配置和对GPU(图形处理单元)的免费访问。合作已建立在JupyterNotebook的基础上。以下是代码片段-
示例
print("Three dense layers are being created") layer = layers.Dense(3) print("The weights associated with the layers are") print(layer.weights) print("The created layers is called on test data") x = tf.ones((2, 3)) y = layer(x) print("Now, the weights are : ") print(layer.weights)
代码信用-https://www.tensorflow.org/guide/keras/sequential_model
输出结果
Three dense layers are being created The weights associated with the layers are [] The created layers is called on test data Now, the weights are : [<tf.Variable 'dense_11/kernel:0' shape=(3, 3) dtype=float32, numpy= array([[-0.9901273 , -0.70897937, -0.44804883], [ 0.6849613 , 0.5198808 , 0.48534775], [-0.07876515, -0.73648643, 0.44018626]], dtype=float32)>, <tf.Variable 'dense_11/bias:0' shape=(3,) dtype=float32, numpy=array([0., 0., 0.], dtype=float32)>]
解释
Keras模型中的所有层都需要知道输入的形状,以便创建最佳权重。
最初,创建层时,它没有任何与之关联的权重。
因此,当第一次对输入调用时,它会创建权重。
这是因为权重取决于输入的形状。
层是按顺序创建的。
这称为测试数据。
控制台上将显示与此新模型关联的权重。