翻出了2018年参加了Udacity机器学习进阶班的课上笔记,在此分享
训练与模型
1.逻辑回归
from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression()
classifier.fit(X,y)
2.神经网络
from sklearn.neural_network import MLPClassifier
classifier = MLPClassifier()
3.决策树
from sklearn.tree import DecisionTreeClassifier
classifier = DecisionTreeClassifier()
- 支持向量机
from sklearn.svm import SVC
classifier = SVC(kernel = 'poly', degree = 2)
#kernel:linear (线性), poly(多项式), rbf(高斯核)
#degree:多项式内核的次数(如果选择了多项式内核)
#gamma :γ 参数
#C:C参数
评估指标
- 召回率/查全率(R):分类模型识别所有相关实例的能力,查全率反映了被判定的正例占总的正例的比重
- 精度/查准率(P):分类模型仅仅返回相关实例的能力,查准率反映了被判定为正例中真正的正例样本的比重
- F1 score:使用调和平均结合召回率和精度的指标,F1数值接近于R和P中的较小值。
- mean absolute error
The mean absolute function has a problem, which is that the absolute value function is not differentiable, and this may not be good if we want to use methods such as grading dissent. To solve this problem, we use the more common mean squared error.
Bad model just guessing the average of the values of the points. If the model is good, then the mean squared error for the linear regression model should be a lot smaller than the mean squared error for the simple model.
模型选择
由于测试数据只能在最后一步使用,那么为了辨别模型是否欠拟合或过拟合,可以再分一部分数据用于交叉验证。
在 sklearn 中的网格搜索
在 sklearn 中的网格搜索非常简单。 我们将用一个例子来说明一下。 假设我们想要训练支持向量机,并且我们想在以下参数之间做出决定:
kernel:poly或rbf。
C:0.1,1 或 10。
1.导入 GridSearchCV
from sklearn.model_selection import GridSearchCV
2.选择参数:
现在我们来选择我们想要选择的参数,并形成一个字典。 在这本字典中,键 (keys) 将是参数的名称,值 (values) 将是每个参数可能值的列表。
parameters = {'kernel':['poly', 'rbf'],'C':[0.1, 1, 10]}
3.创建一个评分机制 (scorer)
我们需要确认将使用什么指标来为每个候选模型评分。 这里,我们将使用 F1 分数。
from sklearn.metrics import make_scorer
from sklearn.metrics import f1_score
scorer = make_scorer(f1_score)
4.使用参数 (parameter) 和评分机制 (scorer) 创建一个 GridSearch 对象。 使用此对象与数据保持一致 (fit the data) 。
//Create the object.
grid_obj = GridSearchCV(clf, parameters, scoring=scorer)
//Fit the data
grid_fit = grid_obj.fit(X, y)
5.获得最佳估算器 (estimator)
best_clf = grid_fit.best_estimator_
现在你可以使用这一估算器best_clf来做出预测。