我想创建一个网络,其中输入层中的节点仅连接到下一层中的某些节点。这是一个小例子:
到目前为止,我的解决方案是将i1和之间的边的权重设置h1为零,并且在每个优化步骤之后,我将权重乘以一个矩阵(我称之为矩阵掩码矩阵),其中每个条目都是 1,除了权重的条目之间的边缘i1和h1。(见下面的代码)
这种做法对吗?或者这对 GradientDescent 有影响吗?有没有另一种方法可以在 TensorFlow 中创建这种网络?
import tensorflow as tf
import tensorflow.contrib.eager as tfe
import numpy as np
tf.enable_eager_execution()
model = tf.keras.Sequential([
tf.keras.layers.Dense(2, activation=tf.sigmoid, input_shape=(2,)), # input shape required
tf.keras.layers.Dense(2, activation=tf.sigmoid)
])
#set the weights
weights=[np.array([[0, 0.25],[0.2,0.3]]),np.array([0.35,0.35]),np.array([[0.4,0.5],[0.45, 0.55]]),np.array([0.6,0.6])]
model.set_weights(weights)
model.get_weights()
features = tf.convert_to_tensor([[0.05,0.10 ]])
labels = tf.convert_to_tensor([[0.01,0.99 ]])
mask =np.array([[0, 1],[1,1]])
#define the loss function
def loss(model, x, y):
y_ = model(x)
return tf.losses.mean_squared_error(labels=y, predictions=y_)
#define the gradient calculation
def …Run Code Online (Sandbox Code Playgroud)