为什么不想再用turicreate?
在之前的学习中,主要使用的是python的turicreate框架来生成iOS上的机器学习模型.mlmodel文件。苹果从WWDC2017年开始就致力于不断降低iOS开发者使用机器学习技术的难度,降低开发者们学习机器学习知识的学习成本,因此推出了python上的turicreate框架,可以几行代码之内就可以完成训练、测试、生成模型,还有用在xcode上的createML,直接用可视化UI训练模型。这样做的好处确实极大减轻了开发者们的学习负担,但坏处也显而易见,除了让人们对机器学习内在知识一无所知,更因为其封装的很多参数和算法既定,不能给我们提供很大的选择空间,故而在很多场景下不能最大化发挥机器学习的算法优势,导致性能达不到我们预想的标准。因此,turicreate作为一个很方便的工具,但终究要再学习的过程中被抛弃。
为什么使用Scikit-learn
sklearn中包含了大量的优质的数据集和大量的算法选择,在你学习机器学习的过程中,你可以通过使用这些数据集和算法实现出不同的模型,从而提高你的动手实践能力,同时这个过程也可以加深你对理论知识的理解和把握。(另一点是因为再实验室时学长学姐在发cv论文的时候都是用到了这个,也是不明觉厉。。。。)
一张图说明了sklearn里面有多少种算法可供选择,其中箭头表示的是根据不同需求寻找不同算法的路线
使用sklearn训练一个线性回归模型
import pandas as pd
from sklearn import model_selection
from sklearn import linear_model
pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。
adver = pd.read_csv("Advertising.csv", usecols=[1,2,3,4])
adver.head()
Out[5]:
TV | radio | newspaper | sales | |
---|---|---|---|---|
0 | 230.1 | 37.8 | 69.2 | 22.1 |
1 | 44.5 | 39.3 | 45.1 | 10.4 |
2 | 17.2 | 45.9 | 69.3 | 9.3 |
3 | 151.5 | 41.3 | 58.5 | 18.5 |
4 | 180.8 | 10.8 | 58.4 | 12.9 |
x表示前三列的input数据,y表示最后一列的output数据。并对数据集进行分割
x,y = adver.iloc[:, :-1], adver.iloc[:, -1]
x_train, x_test, y_train, y_test = model_selection.train_test_split(x, y, test_size=0.25,random_state=42)
创建一个线性回归(linear regression)模型;fit方法表示训练模型;score对模型进行评价
regr = linear_model.LinearRegression() # 1
regr.fit(x_train, y_train) # 2
regr.score(x_test, y_test) # 3
Out[8]: 0.8935163320163657
可以看到这个线性回归模型的得分为0.89分。
输出测试结果
X_new = [[ 50.0, 150.0, 150.0],
[250.0, 50.0, 50.0],
[100.0, 125.0, 125.0]]
regr.predict(X_new)
Out[9]: array([34.15367536, 23.83792444, 31.57473763])
使用sklearn训练一个svm模型
from sklearn import svm
svr = svm.LinearSVR(random_state=42)
svr.fit(x_train, y_train)
svr.score(x_test, y_test)
Out[11]: 0.8665383823569167
可以看出这个svm模型的得分是0.87分,两个模型性能相似,线性回归略微占优,这是由于svm算法仅仅考虑距离分解线最近的向量(support vector)的特性而导致的。
svr.predict(X_new)
Out[12]: array([25.86174666, 21.5094961 , 24.77368402])
导出coreML的mlmodel文件
import coremltools
input_features = ["tv", "radio", "newspaper"]
output_feature = "sales"
model = coremltools.converters.sklearn.convert(regr, input_features, output_feature)
# Set model metadata
model.author = 'Xiao Liang'
model.license = 'BSD'
model.short_description = 'Predicts the price of a house in the Beijing area.'
# Set feature descriptions manually
model.input_description['tv'] = 'Ads price spent on tv'
model.input_description['radio'] = 'Ads price spent on radio'
model.input_description['newspaper'] = 'Ads price spent on newspaper'
# Set the output descriptions
model.output_description['sales'] = 'Price of the house'
model.save("MyAdversising.mlmodel")
python部分的代码到此为止,接下来是在xcode上的使用,核心代码就三句:一句传入输入,一句定义输出,一句取出输出。完成啦。
let input = MyAdvertisingInput(tv: tv, radio: radio, newspaper: newspaper)
guard let output = try? advertising.prediction(input: input) else {
return
}
let sales = output.sales
参考文档:https://www.raywenderlich.com/174-beginning-machine-learning-with-scikit-learn