一、scikit—learn简介
scikit-learn是一个建立在Scipy基础上的用于机器学习的Python模块。在不同的应用领域中,已经扩展出为数众多的基于Scipy的工具包,他们统称为Scikits。而在所有的分支版本中,scikit-learn是最有名的,是开源的,任何人都可以免费地使用这个库或者进行二次开发。sklearn里面有许多已经搞好的模型,可以直接去官网看模型还有直接下载下来。
scikit-learn包含众多顶级机器学习算法,主要有六大基本功能,分别是分类、回归、聚类、数据降维、模型选择和数据预处理。scikit-learn拥有非常活跃的用户社区,基本上其所有的功能都有非常详尽的文档供用户查阅。可以研读scikit-learn的用户指南及文档,对其算法的使用有更充分的了解。
二、导入scikit—Learn库
%matplotlib inline
import numpy as np
import scipy
import sklearn #导入scikit—learn库
scikit—learn有许多的数据集可以下载,下面精选一个代码来使用
%matplotlib inline
import numpy as np
import scipy
import sklearn
from sklearn.datasets import load_iris #花的分类
iris=load_iris()
n_samples,n_datas=iris.data.shape
print(n_samples,n_datas)
print(iris.target_names)
##输出 150 4
['setosa' 'versicolor' 'virginica']
import matplotlib.pyplot as plt
x_index=1 #第二列
y_index=2
plt.scatter(iris.data[:,x_index],iris.data[:,y_index],c=iris.target)
plt.xlabel(iris.feature_names[x_index])
plt.ylabel(iris.feature_names[y_index])
输出图像为:
from sklearn.datasets import load_digits
digits=load_digits()
#这个是手写数字的训练集,标签为1~9
三、模型实例、模型选择
模型一般导入库:
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
一般步骤就是先创建一个对象,再fit()下,再预测predict(),最后在画散点图scatter()如下面程序
import numpy as np
import matplotlib.pyplot as plt
import sklearn
from sklearn.linear_model import LinearRegression
clf=LinearRegression()
from sklearn.datasets import load_boston
data=load_boston()
n_samples,n_features=data.data.shape
print(n_samples,n_features)
print(data.target.shape)
column_i=5
plt.scatter(data.data[:,column_i],data.target)
print(data.feature_names[5])
from sklearn.metrics import mean_absolute_error
clf.fit(data.data,data.target)
predicted=clf.predict(data.data)
mean_absolute_error(data.target,predicted)
plt.scatter(data.target,predicted)
plt.xlabel("ture prices")
plt.ylabel('predicted prices')
plt.plot(data.target,predicted,color='red')
输出: