将矩阵列名称与数字矢量名称匹配并将值存储到R中的矩阵中

时间:2018-11-24 02:24:15

标签: r matrix

我正在尝试将矩阵列名称与数字矢量的名称匹配,并将数字矢量的值存储到矩阵中。

例如:

import tensorflow as tf

hidden_1_layer = {'weights': tf.Variable(tf.random_normal([37500, 500])),
                  'biases': tf.Variable(tf.random_normal([500]))}
hidden_2_layer = {'weights': tf.Variable(tf.random_normal([500, 250])),
                  'biases': tf.Variable(tf.random_normal([250]))}
hidden_3_layer = {'weights': tf.Variable(tf.random_normal([250, 125])),
                  'biases': tf.Variable(tf.random_normal([125]))}
output_layer = {'weights': tf.Variable(tf.random_normal([125, 1])),
                'biases': tf.Variable(tf.random_normal([1]))}

class ImageNN():
    def train(self, array, target):
        x = tf.placeholder('float', name='x')
        l1 = tf.add(tf.matmul(x, hidden_1_layer['weights']), hidden_1_layer['biases'])
        l1 = tf.nn.relu(l1)
        l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']), hidden_2_layer['biases'])
        l2 = tf.nn.relu(l2)
        l3 = tf.add(tf.matmul(l2, hidden_3_layer['weights']), hidden_3_layer['biases'])
        l3 = tf.nn.relu(l3)
        output = tf.add(tf.matmul(l3, output_layer['weights']), output_layer['biases'])
        output = tf.nn.sigmoid(output)
        cost = tf.square(output-target)
        optimizer = tf.train.AdamOptimizer().minimize(cost)
        array = array.reshape(1, 37500)
        with tf.Session() as sess:
            sess.run(tf.global_variables_initializer())
            sess.run(optimizer, feed_dict={x: array})
            sess.close()
        del x, l1, l2, output, cost, optimizer

    #Do computations with our artificial nueral network
    def predict(self, data):          #Input data is of size (37500,)
        x = tf.placeholder('float', name='x')    #get data into the right rank (dimensions), this is just a placeholder, it has no values
        l1 = tf.add(tf.matmul(x, hidden_1_layer['weights']), hidden_1_layer['biases'])
        l1 = tf.nn.relu(l1)
        l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']), hidden_2_layer['biases'])
        l2 = tf.nn.relu(l2)
        l3 = tf.add(tf.matmul(l2, hidden_3_layer['weights']), hidden_3_layer['biases'])
        l3 = tf.nn.relu(l3)
        output = tf.add(tf.matmul(l3, output_layer['weights']), output_layer['biases'])
        output = tf.nn.sigmoid(output)
        data = data.reshape(1, 37500)
        with tf.Session() as sess:
            sess.run(tf.global_variables_initializer())
            theOutput = sess.run(output, feed_dict={x: data})
            sess.close()
        del x, l1, l2, output, data
        return theOutput

在上面的代码中,我希望通过匹配相应的列名将vec(数字)复制到ex(矩阵)中。我已经尝试过了,但是由于我还是R的新手,所以我没有得到解决方案。

1 个答案:

答案 0 :(得分:1)

# loop through column name of matrix that have correspondences in your vector   
for(i in colnames(ex)[colnames(ex) %in% names(vec)]) {
  # fill these matrix columns with the designated values from your vector
  ex[ , i] <- vec[i]
}