摘要:当我拖入一个.mlModel
intoXcode
时,Xcode
会为模型生成一个类接口。
- 我使用的所有模型输入都接受通用的初始化参数,
- 返回唯一的Input 类,它们被传递给模型的
predict(input:UniqueInput)
方法和 - 那些返回一个唯一的
ModelOutput
实例 - 它有一个共同
lazy var dependent: String
的属性。
问题:每次我拖入一个新的类时生成的唯一类.mlModel
需要我每次都重写代码。
目标:利用公共参数和依赖属性,以尽可能减少我在拖入 new 时需要重写的代码量.mlModels
。
当前失败尝试
我试图让自动生成的模型输入符合ModelVersion1
协议,以便新生成的模型输入具有共同的类型。但是,带有初始化程序的协议要求初始化程序实现具有required
类的关键字,而我在自动生成的类中无法控制这些类。
func createRunningDataFrame() {
var transactions: [Transaction] = []
let model = try? MITO_1(configuration: MLModelConfiguration())
URLRequest.streamFor(ticker: "MITO") { (runningFrame: DataFrame, price, ticker) in
// ----------------------------> key line ----------------------
guard let dependent: Double = try? model?.prediction(input: runningFrame.modelInput()!).dependent.double,
// <-------------------------------------------------------------
let direction = Direction(dependent: dependent) else { return }
URLRequest.transact(direction, price, ticker) { transaction in
transactions.append(transaction)
}
}
}
使用代码
(自动生成)
class MITO_1 {
func prediction(input: MITO_1Input) throws -> MITO_1Output {
return try self.prediction(input: input, options: MLPredictionOptions())
}
}
class MITO_1Input {
init(daysOfWeek: String, tradingsHours: String, quarters: String) {
self.daysOfWeek = daysOfWeek
self.tradingsHours = tradingsHours
self.quarters = quarters
}
}
class MITO_1Output : MLFeatureProvider {
lazy var dependent: String = { [unowned self] in
return self.provider.featureValue(for: "dependent")!.stringValue
}()
}
数据框
extension DataFrame {
func modelInput<T: ModelVersion1>() -> T? {
guard let daysOfWeek = self.cell(for: "daysOfWeek"),
let tradingsHours = self.cell(for: "tradingsHours"),
let quarters = self.cell(for: "quarters") else { return nil }
return T(
daysOfWeek: daysOfWeek,
tradingsHours: tradingsHours,
quarters: quarters
)
}
}
一致性
ERROR: Initializer requirement 'init(daysOfWeek:tradingsHours:quarters:)' can only be satisfied by a 'required' initializer in non-final class 'MITO_1Input'
extension MITO_1Input: ModelVersion1 {}
protocol ModelVersion1: AnyObject {
init(daysOfWeek: String, tradingsHours: String, quarters: String)
}
细绳
extension String {
var double: Double? {
Double(self)
}
}