Numpy / Theano中矩阵和三向张量的乘积

时间:2017-03-30 04:16:52

标签: python numpy matrix linear-algebra theano

我想计算形状为¢的矩阵private const string DefaultSaveFile = @"C:\temp\testfile.txt"; private void CopyUniqueClipboardTextToFile(string filePath = null, bool updateListbox = true) { // Use global default file if nothing was passed if (filePath == null) filePath = DefaultSaveFile; // Ensure our files exist if (!File.Exists(filePath)) File.CreateText(filePath).Close(); string fileContents = File.ReadAllText(filePath); string clipboardText = Clipboard.GetText(); // Update the file with any new clipboard text if (Clipboard.ContainsText() && !fileContents.Contains(clipboardText)) { // Save the lines to our file, with a '¢' character at the end File.AppendAllText(filePath, $"{Environment.NewLine}{clipboardText}¢"); } // Re-read the new file into a single string string entireFileAsOneLine = string.Join(" ", File.ReadAllLines(filePath).Distinct().ToList()); // Now split that string on the '¢' character string[] listItems = entireFileAsOneLine.Split('¢'); // Update listbox if necessary if (updateListbox) { listBox1.BeginUpdate(); listBox1.DataSource = listItems; listBox1.EndUpdate(); } } private void button2_Click(object sender, EventArgs e) { CopyUniqueClipboardTextToFile(); } 和形状为X的张量(a, b)的乘积,以便结果Y具有(a, b, c)的形状Z和行(a, c) i(i = 1...a)的行Z与矩阵切片i的乘积X

有没有一种方便的方法在NumPy和Theano中执行此操作,理想情况下使用内置函数,而不使用循环或计算不必要的矩阵产品?

1 个答案:

答案 0 :(得分:1)

根据您的描述,编写einsum表达式很简单:

In [428]: X=np.arange(6).reshape(2,3)
In [429]: Y=np.arange(2*3*4).reshape(2,3,4)

In [431]: np.einsum('ab,abc->ac',X,Y)
Out[431]: 
array([[ 20,  23,  26,  29],
       [200, 212, 224, 236]])
In [432]: _.shape
Out[432]: (2, 4)

np.matmul@运算符有点棘手,但速度可能很快:

In [438]: (X[:,None,:]@Y).squeeze()
Out[438]: 
array([[ 20,  23,  26,  29],
       [200, 212, 224, 236]])

中间阶段的形状为(a,1,c),即

(a,1,b)@(a,b,c)=>(a,1,c)   # with sum on b