我目前正在我的iOS应用程序中使用Swift版本的Tensorflow。我的模型工作得很好,但是我很难将数据复制到第一张张量中,所以我可以使用神经网络来检测数据。
我咨询了存储库中的测试套件,它们的代码如下所示:
他们正在使用一些扩展:
extension Array {
/// Creates a new array from the bytes of the given unsafe data.
///
/// - Note: Returns `nil` if `unsafeData.count` is not a multiple of
/// `MemoryLayout<Element>.stride`.
/// - Parameter unsafeData: The data containing the bytes to turn into an array.
init?(unsafeData: Data) {
guard unsafeData.count % MemoryLayout<Element>.stride == 0 else { return nil }
let elements = unsafeData.withUnsafeBytes {
UnsafeBufferPointer<Element>(
start: $0,
count: unsafeData.count / MemoryLayout<Element>.stride
)
}
self.init(elements)
}
}
extension Data {
/// Creates a new buffer by copying the buffer pointer of the given array.
///
/// - Warning: The given array's element type `T` must be trivial in that it can be copied bit
/// for bit with no indirection or reference-counting operations; otherwise, reinterpreting
/// data from the resulting buffer has undefined behavior.
/// - Parameter array: An array with elements of type `T`.
init<T>(copyingBufferOf array: [T]) {
self = array.withUnsafeBufferPointer(Data.init)
}
}若要创建包含数据和数据对象的数组,请执行以下操作:
static let inputData = Data(copyingBufferOf: [Float32(1.0), Float32(3.0)])然后,他们将inputData复制到神经网络中。
我试图修改他们的代码,将图像加载到一个1,28,28,1张张量中。这张照片看起来是这样的:
[[[[Float32(254.0)],
[Float32(255.0)],
[Float32(254.0)],
[Float32(250.0)],
[Float32(252.0)],
[Float32(255.0)],
[Float32(255.0)],
[Float32(255.0)],
[Float32(255.0)],
[Float32(254.0)],
[Float32(214.0)],
[Float32(160.0)],
[Float32(130.0)],
[Float32(124.0)],
[Float32(129.0)],
...你说对了。
但是,如果我试图用图像数据将其转换为数据/ init数据,我只得到8个字节:
private func createTestData() -> Data {
return Data(copyingBufferOf:
[[[[Float32(254.0)],
[Float32(255.0)],
[Float32(254.0)],
...

测试中的代码也是如此,但是对于它们来说,这是很好的(2*Float32 32=8字节)。对我来说,这太小了(应该是28*28*4 = 3136字节)!
发布于 2019-04-17 13:26:21
Swift Array是一个固定大小的结构,具有指向实际元素存储的(不透明)指针。withUnsafeBufferPointer()方法使用指向该元素存储的缓冲区指针调用给定的闭包。对于[Float]数组,它是指向浮点值的内存地址的指针。怪不得
array.withUnsafeBufferPointer(Data.init)用于获取表示浮点数的Data值。
如果将嵌套数组(例如,[[Float]]类型)传递给withUnsafeBufferPointer()方法,则使用指向内部数组的Array结构的指针调用闭包。因此,现在的元素类型不是Float,而是[Float],而不是警告意义上的“琐碎类型”。
/// - Warning: The given array's element type `T` must be trivial in that it can be copied bit
/// for bit with no indirection or reference-counting operations; otherwise, reinterpreting
/// data from the resulting buffer has undefined behavior.您需要做的是将嵌套的数组扁平化为一个简单的数组,然后从简单数组中创建一个Data值。
https://stackoverflow.com/questions/55693685
复制相似问题