Tensorflow自定义层:使用可训练的参数创建稀疏矩阵

时间:2019-09-30 15:34:13

标签: python tensorflow machine-learning

我正在研究的模型应该同时预测很多变量(> 1000)。因此,对于每个输出,我希望在网络的末端有一个小的神经网络。

为了紧凑地执行此操作,我想找到一种在Tensorflow框架内的神经网络的两层之间创建稀疏可训练连接的方法。

连接矩阵的一小部分应该是可训练的:仅参数是块对角线的一部分。


例如: see the Not dense part

连接矩阵如下:

Block diagonal matrix

可训练的参数应位于 1 的位置。

2 个答案:

答案 0 :(得分:2)

我已经写了这么一层:

https://github.com/ArnovanHilten/GenNet/blob/master/utils/LocallyDirectedConnected_tf2.py

它将稀疏矩阵作为输入,并让您决定如何在图层之间进行连接。该层使用稀疏张量和矩阵乘法。

答案 1 :(得分:1)

编辑 因此评论为Is this a trainable object though?

答案:否。您目前无法使用稀疏矩阵并使它可训练。相反,您可以使用遮罩矩阵(请参阅最后)

但是,如果需要使用稀疏矩阵,则只需使用tf.sparse.sparse_dense_matmul()tf.sparse_tensor_to_dense()即可使稀疏与密集矩阵进行交互。我从here中提取了一个简单的XOR示例,并用稀疏矩阵替换了密集的值:

#Declaring necessary modules
import tensorflow as tf
import numpy as np
"""
A simple numpy implementation of a XOR gate to understand the backpropagation
algorithm
"""

x = tf.placeholder(tf.float32,shape = [4,2],name = "x")
#declaring a place holder for input x
y = tf.placeholder(tf.float32,shape = [4,1],name = "y")
#declaring a place holder for desired output y

m = np.shape(x)[0]#number of training examples
n = np.shape(x)[1]#number of features
hidden_s = 2 #number of nodes in the hidden layer
l_r = 1#learning rate initialization

theta1 = tf.SparseTensor(indices=[[0, 0],[0, 1], [1, 1]], values=[0.1, 0.2, 0.1], dense_shape=[3, 2])
#theta1 = tf.cast(tf.Variable(tf.random_normal([3,hidden_s]),name = "theta1"),tf.float64)
theta2 = tf.cast(tf.Variable(tf.random_normal([hidden_s+1,1]),name = "theta2"),tf.float32)

#conducting forward propagation
a1 = tf.concat([np.c_[np.ones(x.shape[0])],x],1)
#the weights of the first layer are multiplied by the input of the first layer

#z1 = tf.sparse_tensor_dense_matmul(theta1, a1)

z1 = tf.matmul(a1,tf.sparse_tensor_to_dense(theta1))
#the input of the second layer is the output of the first layer, passed through the 

a2 = tf.concat([np.c_[np.ones(x.shape[0])],tf.sigmoid(z1)],1)
#the input of the second layer is multiplied by the weights

z3 = tf.matmul(a2,theta2)
#the output is passed through the activation function to obtain the final probability

h3 = tf.sigmoid(z3)
cost_func = -tf.reduce_sum(y*tf.log(h3)+(1-y)*tf.log(1-h3),axis = 1)

#built in tensorflow optimizer that conducts gradient descent using specified 

optimiser = tf.train.GradientDescentOptimizer(learning_rate = l_r).minimize(cost_func)

#setting required X and Y values to perform XOR operation
X = [[0,0],[0,1],[1,0],[1,1]]
Y = [[0],[1],[1],[0]]

#initializing all variables, creating a session and running a tensorflow session
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

#running gradient descent for each iterati
for i in range(200):
   sess.run(optimiser, feed_dict = {x:X,y:Y})#setting place holder values using feed_dict
   if i%100==0:
      print("Epoch:",i)
      print(sess.run(theta1))

,输出为:

Epoch: 0
SparseTensorValue(indices=array([[0, 0],
       [0, 1],
       [1, 1]]), values=array([0.1, 0.2, 0.1], dtype=float32), dense_shape=array([3, 2]))
Epoch: 100
SparseTensorValue(indices=array([[0, 0],
       [0, 1],
       [1, 1]]), values=array([0.1, 0.2, 0.1], dtype=float32), dense_shape=array([3, 2]))

因此,唯一的方法是使用掩码矩阵。您可以通过乘法或tf.where

使用它

1)乘法:您可以创建所需形状的蒙版矩阵,并将其与权重矩阵相乘:

mask = tf.Variable([[1,0,0],[0,1,0],[0,0,1]],name ='mask', trainable=False)
weight = tf.cast(tf.Variable(tf.random_normal([3,3])),tf.float32)
desired_tensor = tf.matmul(weight, mask)

2)tf.where

mask = tf.Variable([[1,0,0],[0,1,0],[0,0,1]],name ='mask', trainable=False)
weight = tf.cast(tf.Variable(tf.random_normal([3,3])),tf.float32)
desired_tensor = tf.where(mask > 0, tf.ones_like(weight), weight)

希望有帮助


您可以像这样使用稀疏张量来做到这一点:

SparseTensor(indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4])

,输出为:

[[1, 0, 0, 0]
 [0, 0, 2, 0]
 [0, 0, 0, 0]]

您可以在此处查找有关稀疏张量的文档的更多信息:

https://www.tensorflow.org/api_docs/python/tf/sparse/SparseTensor

希望有帮助!