先决条件: 机器学习入门 scikit学习 是一个开源Python库,使用统一的界面实现一系列机器学习、预处理、交叉验证和可视化算法。
scikit learn的重要功能:
- 简单高效的数据挖掘和数据分析工具。它具有各种分类、回归和聚类算法,包括支持向量机、随机森林、梯度增强、k均值等。
- 每个人都可以访问,并且可以在各种环境中重复使用。
- 建立在NumPy、SciPy和matplotlib之上。
- 开源,商业化使用——BSD许可证。
在本文中,我们将看到如何使用scikit learn轻松构建机器学习模型。
安装:
Scikit学习需要:
- 努比
- SciPy作为其依赖项。
在安装scikit learn之前,请确保已安装NumPy和SciPy。一旦安装了NumPy和SciPy,安装scikit learn最简单的方法就是使用pip:
pip install -U scikit-learn
现在让我们开始建模过程。
步骤1:加载数据集
数据集只是数据的集合。数据集通常有两个主要组件:
- 特征 :(也称为预测、输入或属性)它们只是我们数据的变量。它们可以不止一个,因此由一个 特征矩阵 (’X’是表示特征矩阵的常用符号)。所有要素名称的列表称为 功能名称 .
- 回答 :(也称为目标、标签或输出)这是取决于特征变量的输出变量。我们通常只有一个响应列,它由 响应向量 (’y’是表示响应向量的常用符号)。响应向量取的所有可能值称为 目标名称 .
正在加载示例数据集: scikit learn附带了一些示例数据集,如 艾里斯 和 数字 分类数据集和 波士顿房价 回归数据集。
下面是一个如何加载示例数据集的示例:
python
# load the iris dataset as an example from sklearn.datasets import load_iris iris = load_iris() # store the feature matrix (X) and response vector (y) X = iris.data y = iris.target # store the feature and target names feature_names = iris.feature_names target_names = iris.target_names # printing features and target names of our dataset print ( "Feature names:" , feature_names) print ( "Target names:" , target_names) # X and y are numpy arrays print ( "Type of X is:" , type (X)) # printing first 5 input rows print ( "First 5 rows of X:" , X[: 5 ]) |
输出:
Feature names: ['sepal length (cm)','sepal width (cm)', 'petal length (cm)','petal width (cm)']Target names: ['setosa' 'versicolor' 'virginica']Type of X is: First 5 rows of X: [[ 5.1 3.5 1.4 0.2] [ 4.9 3. 1.4 0.2] [ 4.7 3.2 1.3 0.2] [ 4.6 3.1 1.5 0.2] [ 5. 3.6 1.4 0.2]]
正在加载外部数据集: 现在,考虑当我们要加载外部数据集时的情况。为此,我们可以使用 熊猫图书馆 便于加载和操作数据集。
要安装pandas,请使用以下pip命令:
pip install pandas
在熊猫中,重要的数据类型包括: 系列 :Series是一个一维标记数组,能够保存任何数据类型。
数据帧 :它是一个二维标记数据结构,具有可能不同类型的列。你可以把它想象成一个电子表格或SQL表,或者一系列对象的dict。它通常是最常用的对象。 注意:以下示例中使用的CSV文件可从此处下载: 天气csv
python
import pandas as pd # reading csv file data = pd.read_csv( 'weather.csv' ) # shape of dataset print ( "Shape:" , data.shape) # column names print ( "Features:" , data.columns) # storing the feature matrix (X) and response vector (y) X = data[data.columns[: - 1 ]] y = data[data.columns[ - 1 ]] # printing first 5 rows of feature matrix print ( "Feature matrix:" , X.head()) # printing first 5 values of response vector print ( "Response vector:" , y.head()) |
输出:
Shape: (14, 5)Features: Index([u'Outlook', u'Temperature', u'Humidity', u'Windy', u'Play'], dtype='object')Feature matrix: Outlook Temperature Humidity Windy0 overcast hot high False1 overcast cool normal True2 overcast mild high True3 overcast hot normal False4 rainy mild high FalseResponse vector:0 yes1 yes2 yes3 yes4 yesName: Play, dtype: object
步骤2:拆分数据集 所有机器学习模型的一个重要方面是确定它们的准确性。现在,为了确定其准确性,可以使用给定的数据集训练模型,然后使用该模型预测同一数据集的响应值,从而找到模型的准确性。 但这种方法有几个缺陷,比如:
- 我们的目标是估计一个模型在 样品外 数据
- 最大限度地提高训练精度会奖励过于复杂的模型,这些模型不一定会推广我们的模型。
- 不必要的复杂模型可能会过度拟合训练数据。
更好的选择是将数据分成两部分:第一部分用于训练机器学习模型,第二部分用于测试模型。
总结一下:
- 将数据集分成两部分:训练集和测试集。
- 在训练集中训练模型。
- 在测试集上测试模型,并评估我们的模型的性能。
列车/测试分离的优点:
- 该模型可以在不同于用于训练的数据上进行训练和测试。
- 测试数据集的响应值是已知的,因此可以评估预测
- 与样本外性能的训练精度相比,测试精度是一个更好的估计。
考虑下面的例子:
python
# load the iris dataset as an example from sklearn.datasets import load_iris iris = load_iris() # store the feature matrix (X) and response vector (y) X = iris.data y = iris.target # splitting X and y into training and testing sets from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.4 , random_state = 1 ) # printing the shapes of the new X objects print (X_train.shape) print (X_test.shape) # printing the shapes of the new y objects print (y_train.shape) print (y_test.shape) |
输出:
(90L, 4L)(60L, 4L)(90L,)(60L,)
这个 列车试验分离 函数接受以下几个参数:
- 十、 y :这些是需要拆分的特征矩阵和响应向量。
- 测试尺寸 :它是测试数据与给定数据的比率。例如,为150行X设置test_size=0.4将生成150 X 0.4=60行的测试数据。
- 随机状态 :如果使用random_state=some_number,则可以保证分割始终相同。如果您希望得到可重复的结果,例如在测试文档的一致性时(这样每个人都可以看到相同的数字),这是很有用的。
第3步:培训模型
现在,是时候使用我们的数据集训练一些预测模型了。Scikit learn提供了一系列机器学习算法,这些算法在拟合、预测精度等方面具有统一/一致的界面。 下面给出的示例使用 KNN(K近邻)分类器 .
笔记 :我们不会详细介绍算法的工作原理,因为我们只想了解它的实现。
现在,考虑下面的例子:
python
# load the iris dataset as an example from sklearn.datasets import load_iris iris = load_iris() # store the feature matrix (X) and response vector (y) X = iris.data y = iris.target # splitting X and y into training and testing sets from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.4 , random_state = 1 ) # training the model on training set from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors = 3 ) knn.fit(X_train, y_train) # making predictions on the testing set y_pred = knn.predict(X_test) # comparing actual response values (y_test) with predicted response values (y_pred) from sklearn import metrics print ("kNN model accuracy:", metrics.accuracy_score(y_test, y_pred)) # making prediction for out of sample data sample = [[ 3 , 5 , 4 , 2 ], [ 2 , 3 , 5 , 4 ]] preds = knn.predict(sample) pred_species = [iris.target_names[p] for p in preds] print ("Predictions:", pred_species) # saving the model from sklearn.externals import joblib joblib.dump(knn, 'iris_knn.pkl' ) |
输出:
kNN model accuracy: 0.983333333333Predictions: ['versicolor', 'virginica']
上述代码中需要注意的要点:
- 我们使用以下方法创建knn分类器对象:
knn = KNeighborsClassifier(n_neighbors=3)
- 分类器使用X_训练数据进行训练。这个过程被称为 适合的 .我们传递特征矩阵和相应的响应向量。
knn.fit(X_train, y_train)
- 现在,我们需要在X_测试数据上测试我们的分类器。 knn。预测 方法用于此目的。它返回预测的响应向量, y_pred .
y_pred = knn.predict(X_test)
- 现在,我们感兴趣的是通过比较发现我们模型的准确性 y_测试 和 y_pred 。这是使用度量模块的方法完成的 准确度 :
print(metrics.accuracy_score(y_test, y_pred))
- 当你希望你的模型做预测时,考虑这个情况。 样品外 数据然后,样本输入可以像传递任何特征矩阵一样简单地传递。
sample = [[3, 5, 4, 2], [2, 3, 5, 4]]preds = knn.predict(sample)
- 如果您不想反复训练分类器并使用预先训练好的分类器,可以使用 乔布里 .你需要做的就是:
joblib.dump(knn, 'iris_knn.pkl')
- 如果要加载已保存的分类器,请使用以下方法:
knn = joblib.load('iris_knn.pkl')
在本文即将结束时,使用scikit learn比使用其他一些机器学习库(如R库)有一些好处:
- 一致接口 机器学习模型
- 提供了许多 调整参数 但是 合理的违约
- 异常 文档
- 功能丰富的 伴随任务 .
- 活跃社区 促进发展和支持。
参考资料:
- http://scikit-learn.org/stable/documentation.html
- https://github.com/justmarkham/scikit-learn-videos
本文由 尼希尔·库马尔 .如果你喜欢GeekSforgeks并想贡献自己的力量,你也可以用write写一篇文章。极客。组织或邮寄你的文章进行评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。