2016-11-12 5 views
0

与えられたデータXのすべての行について、いくつかのサンプリングされたクラスに対してのみsoftmax関数を適用する関数を作成したいとします。クラス。シンプルなPythonでコードがそのように思える:テンソルフローの行列変数の値を更新し、高度なインデックス作成

def softy(X,W, num_samples): 
    N = X.shape[0] 
    K = W.shape[0] 
    S = np.zeros((N,K)) 
    ar_to_sof = np.zeros(num_samples) 
    sampled_ind = np.zeros(num_samples, dtype = int) 
    for line in range(N):   
     for samp in range(num_samples): 
      sampled_ind[samp] = randint(0,K-1) 
      ar_to_sof[samp] = np.dot(X[line],np.transpose(W[sampled_ind[samp]])) 
     ar_to_sof = softmax(ar_to_sof) 
     S[line][sampled_ind] = ar_to_sof 

    return S 

Sは最終的に、アレイ「samped_ind」によってライン毎に定義されたインデックスではゼロ、そしてNON_ZERO値が含まれます。 Tensorflowを使用してこれを実装したいと思います。問題は、 "高度な"インデックス作成が含まれており、私はこのライブラリを使って作成する方法を見つけることができないということです。

私はこのコードを使用していることをしようとしています:

S = tf.Variable(tf.zeros((N,K))) 
tfx = tf.placeholder(tf.float32,shape=(None,D)) 
wsampled = tf.placeholder(tf.float32, shape = (None,D)) 
ar_to_sof = tf.matmul(tfx,wsampled,transpose_b=True) 
softy = tf.nn.softmax(ar_to_sof) 
r = tf.random_uniform(shape=(), minval=0,maxval=K, dtype=tf.int32) 
... 
for line in range(N): 
    sampled_ind = tf.constant(value=[sess.run(r),sess.run(r)],dtype= tf.int32) 
    Wsampled = sess.run(tf.gather(W,sampled_ind)) 
    sess.run(softy,feed_dict={tfx:X[line:line+1], wsampled:Wsampled}) 

すべてはここまで動作しますが、私はPythonコード「S [ライン]に、私は行列Sにしたいアップデートを行うための方法を見つけることができません[sampled_ind] = ar_to_sof "となります。

どうすればこの仕事をすることができますか?

+0

多分['tf.random_shuffle'](https://www.tensorflow.org/versions/r0.11/api_docs/python/constant_op.html#random_shuffle)はそれを行うでしょうか? – drpng

+0

おそらく私の質問が十分ではなかったかもしれません。そのために残念。私はS変数行列をシャッフルしたくありません。私はそれを作成したい! Sは最終的に配列 "samped_ind"によってすべての行に定義されたインデックスにゼロとゼロ以外の値を含みます。 –

+0

ああ、たぶん 'tf.one_hot'のようなもの? – drpng

答えて

0

this problemの解説で私の問題に対する答えが見つかりました。私は期待していた結果を返すこと

S = tf.Variable(tf.zeros(shape=(N*K))) 
W = tf.Variable(tf.random_uniform((K,D))) 
tfx = tf.placeholder(tf.float32,shape=(None,D)) 
sampled_ind = tf.random_uniform(dtype=tf.int32, minval=0, maxval=K-1, shape=[num_samps]) 
ar_to_sof = tf.matmul(tfx,tf.gather(W,sampled_ind),transpose_b=True) 
updates = tf.reshape(tf.nn.softmax(ar_to_sof),shape=(num_samps,)) 
init = tf.initialize_all_variables() 
sess = tf.Session() 
sess.run(init) 
for line in range(N): 
    inds_new = sampled_ind + line*K 
    sess.run(tf.scatter_update(S,inds_new,updates), feed_dict={tfx: X[line:line+1]}) 

S = tf.reshape(S,shape=(N,K)) 

:コードが動作していると、それがどのように見える、そのように私の行列S 1Dベクトルに再形成することを示唆しています。問題は、この実装が遅すぎるということです。 numpyバージョンよりもはるかに低速です。たぶんforループです。助言がありますか?

関連する問題