簡體   English   中英

創建一個張量,其中每個條目是其索引的 function

[英]Creating a tensor where each entry is a function of its index

我想創建一個由D[i,j]=d(ij)定義的矩陣D ,其中d是我可以選擇的任意 function。

它可以很容易地用循環來完成,但速度很慢。 有沒有一種用torch或numpy創建這個矩陣的有效方法?

您可以將 function (如果矢量化)應用於numpy.indices

import numpy as np

i, j = np.indices((n, m))
D = d(i - j)

以下代碼向您展示了如何為您的問題配置基於張量的計算過程:

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
import time

#let's define heigth and width of D:
height=45
width=77

#Let's configure inputs for neural network having input shape similar with D but also extra dimension of size 2
syote=keras.Input(shape=(height,width,2))

#Let's make next layer for the network...
valikerros=layers.Dense(1)

#And attach input to this layer...
x=valikerros(syote)
x=layers.Dense(1)(x)
x=layers.Dense(1)(x)

#...and select so many layers you need...according to complexity of the function d, more layers can easily be added...

#Let's make the neural network...
matriisimalli=keras.Model(inputs=syote,outputs=x,name="Special neural network model presenting D including function d")

#And show its strutuce
matriisimalli.summary()

#next let's create ONCE the i,j -matrix index basis for the input, where there is in each i,j coordinate the index values of those coordinates...this need to be done once only, and can also be saved as a variable and be lodaded, if it is essential to avoid usage of for-loops
pohjasyote=np.ones((1,height,width,2))

for korkeus in range(height):
    for leveys in range(width):
        pohjasyote[0,korkeus,leveys,0]=korkeus
        pohjasyote[0,korkeus,leveys,1]=leveys

#Now let's see how long time it takes to calculate the result for D:

alkuaika=time.time()
result_including_information_of_D=matriisimalli.predict(pohjasyote)
loppuaika=time.time()
print("It took ",loppuaika-alkuaika, " seconds to calculate D")

#...and to use the created (rapid tensor-based) structure for calculation let's next train the network...
#using the standard protocol ... where you train the network first to predict d accurately... then verify it works OK ...
#after that simply use it...

#alternative for the training is you arithmetically deduce the correct values for the weight tensors of the model (accurate results..)

...當然請注意,這是一種利用 keras 中張量優勢的“技巧”,但通過遵循代碼中的想法,我認為您可以找到一種直接的方法來找到解決問題的方法。

如果您發現難以在計算中遵循這個想法(抱歉評論不佳),那么首先在計算中使用您的 D 大小來測試代碼,並比較這個速度是否比您當前基於 for-loop 的解決方案更好。 如果“matriisimalli”更好,那么go值得通過仔細的代碼並利用它的想法來達到更好的性能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM