我正在使用 Metal Performance Shader 设置神经网络,在编写权重初始化类时遇到了问题:Type 'MyWeights' does not conform to protocol 'NSCopying'。是什么导致了错误,以及如何解决这个问题?
附言。我试图通过添加 copy() 函数来修复它,但是我不知道要返回什么或它意味着什么。
import Foundation
import MetalPerformanceShaders
class MyWeights: NSObject, MPSCNNConvolutionDataSource {
//Error: Type 'MyWeights' does not conform to protocol 'NSCopying'
/*
func copy(with zone: NSZone? = nil) -> Any {
return self
}
*/
let name: String
let kernelWidth: Int
let kernelHeight: Int
let inputFeatureChannels: Int
let outputFeatureChannels: Int
var data: Data?
init(name: String, kernelWidth: Int, kernelHeight: Int,
inputFeatureChannels: Int, outputFeatureChannels: Int,
useLeaky: Bool = true) {
self.name = name
self.kernelWidth = kernelWidth
self.kernelHeight = kernelHeight
self.inputFeatureChannels = inputFeatureChannels
self.outputFeatureChannels = outputFeatureChannels
}
func dataType() -> MPSDataType {
return .float32
}
func descriptor() -> MPSCNNConvolutionDescriptor {
let desc = MPSCNNConvolutionDescriptor(kernelWidth: kernelWidth,
kernelHeight: kernelHeight,
inputFeatureChannels: inputFeatureChannels,
outputFeatureChannels: outputFeatureChannels)
return desc
}
func weights() -> UnsafeMutableRawPointer {
return UnsafeMutableRawPointer(mutating: (data! as NSData).bytes)
}
func biasTerms() -> UnsafeMutablePointer<Float>? {
return nil
}
func load() -> Bool {
if let url = Bundle.main.url(forResource: name, withExtension: "dat") {
do {
data = try Data(contentsOf: url)
return true
} catch {
print("Error: could not load \(url): \(error)")
}
}
return false
}
func purge() {
data = nil
}
func label() -> String? {
return name
}
}
最佳答案
它告诉您确切该做什么。
你需要声明你的类符合NSCopying
协议(protocol),然后你需要实现那个协议(protocol)中唯一的函数,copy(with:)
class MyWeights: NSObject, MPSCNNConvolutionDataSource, NSCopying {
func copy(with zone: NSZone? = nil) -> Any {
return MyWeights(
name: self.name,
kernelWidth: self.kernelWidth,
kernelHeight: self.kernelHeight,
inputFeatureChannels: self.inputFeatureChannels,
outputFeatureChannels: self.outputFeatureChannels,
useLeaky: self.useLeaky)
}
//The rest of your class
}
关于ios - 类型 'MyWeights' 不符合协议(protocol) 'NSCopying',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52324167/