我想将一个形状(..., n * (n - 1) / 2)
的数组打包到张量的下三角部分,其形状为(..., n, n)
,其中...
表示任意形状。在numpy中,我会将其实现为
import numpy as np
# Create the array to store data in
arbitrary_shape = (10, 11, 12)
n = 5
target = np.zeros(arbitrary_shape + (n, n))
# Create the source array
source = np.random.normal(0, 1, arbitrary_shape + (n * (n - 1) / 2,))
# Create indices and set values
u, v = np.tril_indices(n, -1)
target[..., u, v] = source
# Check that everything went ok
print target[0, 0, 0]
到目前为止,我已经能够使用transpose
,reshape
和scatter_update
的组合在tensorflow中实现类似的功能,但感觉很笨拙。
import tensorflow as tf
# Create the source array
source = np.random.normal(0, 1, (n * (n - 1) / 2,) + arbitrary_shape)
sess = tf.InteractiveSession()
# Create a flattened representation
target = tf.Variable(np.zeros((n * n,) + arbitrary_shape))
# Assign the values
target = tf.scatter_update(target, u * n + v, source)
# Reorder the axes and reshape into a square matrix along the last dimension
target = tf.transpose(target, (1, 2, 3, 0))
target = tf.reshape(target, arbitrary_shape + (n, n))
# Initialise variables and check results
sess.run(tf.initialize_all_variables())
print target.eval()[0, 0, 0]
sess.close()
有没有更好的方法来实现这一目标?
答案 0 :(得分:3)
我意识到这有点晚了,但我一直试图加载一个较低的三角矩阵,并且我使用sparse_to_dense工作了:
class ExerciseDatabaseController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var ExerciseSearchField: UISearchBar!
@IBOutlet weak var ExercisesTableView: UITableView!
var arrRes = [[String:AnyObject]]() // Array of dictionary
override func viewDidLoad() {
super.viewDidLoad()
let arrRes = ApiService.getExerciseData()
if let resData = ApiService.swiftyJsonVar?["exercise"].arrayObject {
self.arrRes = resData as! [[String:AnyObject]]
}
if self.arrRes.count > 0 {
self.ExercisesTableView.reloadData()
}
print(arrRes)
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrRes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
var dict = arrRes[indexPath.row]
cell.textLabel?.text = dict["name"] as? String
cell.detailTextLabel?.text = dict["description"] as? String
return cell
}
答案 1 :(得分:3)
您可以使用fill_lower_triangular
:
import numpy as np
import tensorflow as tf
from tensorflow.python.ops.distributions.util import fill_lower_triangular
n = 4
coeffs = tf.constant(np.random.normal(0, 1, int(n*(n+1)/2)), dtype=tf.float64)
lower_diag = fill_lower_triangular(coeffs)