Mechine learning for OpenCV 学习笔记 day3
2017-07-28 18:01
387 查看
用逻辑斯特回归(Logistic Regression)分类
主要内容有:用逻辑斯特回归Logistic Regression分类
Logisitic Regression in OpenCV
第四部分数据表示和特征工程
特征工程Feature engineering
预处理数据
1特征标准化
2特征正规化
3将特征数据缩放到一个范围
4二值化特征
5解决数据丢失问题
数据降维
1 PCA
Logisitic Regression in OpenCV
使用sklearn下载数据库:import numpy as np import cv2 from sklearn import datasets from sklearn import model_selection from sklearn import metrics import matplotlib.pyplot as plt plt.style.use('ggplot') iris = datasets.load_iris()
这一步会返回一个字典,其中包含了150个数据点,每个数据点包含4种特征,以及各自对应的标签[3类,标签为0,1,2]。为了方便起见,我们想使用2分类去着手。
idx = iris.target != 2 data = iris.data[idx].astype(np.float32) target = iris.target[idx].astype(np.float32)
在训练模型之前,我们可以先对图像点进行可视化
plt.figure(figsize=(10,6)) plt.scatter(data[:,0],data[:,1],c=target,cmap=plt.cm.Paired,s=100) plt.xlabel(iris.feature_names[0]) plt.ylabel(iris.feature_names[1]) plt.show()
输出结果为:
将数据分成训练集和测试集
X_train, X_test , y_train , y_test = model_selection.train_test_split(data,target,test_size=0.1,random_state=42)
训练集:测试集=9:1,所以将test_size设置为 0.1
训练模型
就像K-NN方法一样去训练模型
lr=cv2.ml.LogisticRegression_create() #选择训练方法,mini-batch or batch lr.setTrainMethod(cv2.ml.LOGISTIC_REGRESSION_MINI_BATCH) #设置mini-batch 每次的数量 lr.setMiniBatchSize(3) #设置迭代次数 lr.setIterations(100) #进行训练 lr.train(X_train, cv2.ml.ROW_SAMPLE, y_train) lr.get_learnt_thetas() #分别输出在训练集和测试集上的准确率 ret, y_pred = lr.predict(X_train) print(metrics.accuracy_score(y_train,y_pred)) _ , y_pred = lr.predict(X_test) print(metrics.accuracy_score(y_test,y_pred))
最终输出结果为:
我们可以通过修改mini-batch的值还有迭代次数来观察,其中当mini-batch = 1 时,正确率可为100%.
第四部分:数据表示和特征工程
提纲:1、预处理数据
2、数据降维
3、表示类型变量
4、表示文本特征
5、表示图片
特征工程(Feature engineering)
特征选择:这是找到数据重要属性(特征)的一步,opencv提供了例如SIFT,SURF等方法特征抽取:将原始数据转变成我们训练模型想要的特征
1.预处理数据
主要内容有:- 转换数据格式
- 数据清理
- 数据采样
1.1特征标准化
标准化是指将原始数据转换成均值为0,方差为1的数据集合,方便后续的机器学习算法的使用。scikit-learn就提供了相关的模块。from sklearn import preprocessing import numpy as np X = np.array([[ 1., -2., 2.], [ 3., 0., 0.], [ 0., 1., -1.]]) X_scaled = preprocessing.scale(X) print(X_scaled)
输出结果为:
1.2特征正规化
# L1正规化 X_normalized_11 = preprocessing.normalize(X, norm='l1') print(X_normalized_11)
输出结果为:
# L2正规化 X_normalized_12 = preprocessing.normalize(X, norm='l2') print(X_normalized_12)
输出结果为:
1.3将特征数据缩放到一个范围
主要是使用MinMaxScaler来实现min_max_sclaer = preprocessing.MinMaxScaler() X_min_max = min_max_sclaer.fit_transform(X) print(X_min_max)
输出结果为:
这里默认的范围是0-1,我们可以通过在MinMaxScaler()中加入feature_range
min_max_sclaer = preprocessing.MinMaxScaler(feature_range=(-10,10)) X_min_max = min_max_sclaer.fit_transform(X) print(X_min_max)
输出结果为:
1.4二值化特征
使用preprocessing模块中的Binarizer()函数,来设定一个阈值,若大于则为1,小于则为0。binarizer = preprocessing.Binarizer(threshold = 0.5) X_binarized = binarizer.transform(X) print(X_binarized)
输出结果为:
1.5解决数据丢失问题
在特征工程中,我们有时需要解决如下问题:from numpy import nan X = np.array([[ nan, 0, 3 ], [ 2, 9, -8 ], [ 1, nan, 1 ], [ 5, 2, 4 ], [ 7, 6, -3 ]])
这里的nan表示not a number, 在scikit-learn工具包中我们有3中方法来解决这个问题。
均值法(mean):用特定行(列)的均值来取代所有的nan
中间值法(median):用一行(列)的中间值来取代所有的nan
最大频率数(most_frequent):用一行(列)中的出现频率最多的值取代所有的nan
以均值法为例:
from sklearn.preprocessing import Imputer imp = Imputer(strategy='mean') X2 = imp.fit_transform(X) X2
输出结果为:
2.数据降维
2.1 PCA
import numpy as np import matplotlib.pyplot as plt plt.style.use('ggplot') mean = [20,20] cov = [[5,0],[25,25]] np.random.seed(42) x,y = np.random.multivariate_normal(mean , cov , 1000).T plt.figure(figsize=(10, 6)) plt.plot(x, y, 'o', zorder=1) plt.axis([0, 40, 0, 40]) plt.xlabel('feature 1') plt.ylabel('feature 2');
输出结果为:
这里我们需要叠加x和y坐标:
X=np.vstack((x,y)).T
然后在特征矩阵X上使用主成分分析(PCA):
import cv2 mu,eig = cv2.PCACompute(X,np.array([])) print(eig) # 输出特征向量 plt.figure(figsize=(10,6)) plt.plot(x,y,'o',zorder=1) plt.quiver(mean[0],mean[1],eig[:,0],eig[:,1],zorder=3,scale=0.2,units = 'xy') plt.text(mean[0]+5*eig[0,0],mean[1]+5*eig[0,1],'u1',zorder=5, fontsize = 16 ,bbox = dict(facecolor='white',alpha=0.6)) plt.text(mean[0]+7*eig[1,0],mean[1]+4*eig[1,1],'u2',zorder=5, fontsize = 16 ,bbox = dict(facecolor='white',alpha=0.6)) plt.axis([0,40,0,40]) plt.xlabel('feature 1') plt.ylabel('feature 2') plt.show()
输出结果为:
我们可以理解为PCA用了2个数据的主成分旋转了x和y轴,以致于便于分类和分析。
X2=cv2.PCAProject(X,mu,eig) plt.figure(figsize=(10,6)) plt.plot(X2[:,0],X2[:,1],'o') plt.xlabel('first principal component') plt.ylabel('second principal component') plt.axis([-20,20,-10,10]) plt.show()
旋转后的输出结果为:
相关文章推荐
- Machine learning for OpenCV 学习笔记 day4
- Machine learning for OpenCV 学习笔记 day6
- Machine learning for openCV 学习笔记 day1
- Machine learning for OpenCV 学习笔记 day5
- OpenCV学习笔记(七)—— OpenCV for Android实时图像处理
- Incremental Learning for Robust Visual Tracking学习笔记二之warpimg
- Fast.ai: Practical Deep Learning for coders 课程学习笔记:Part1 Lesson1 (Lesson0)
- [深度学习论文笔记][Semantic Segmentation] Learning Hierarchical Features for Scene Labeling
- Emgu CV(OpenCV for C#)学习笔记(3)
- OpenCV学习笔记(六)—— OpenCV for Android打开相机
- Fast.ai: Practical Deep Learning for coders 课程学习笔记:Part1 Lesson1 (Lesson0)
- OpenCV学习笔记(七)—— OpenCV for Android实时图像处理
- OpenCV for Ios 学习笔记(9)-用OPENGL渲染AR场景2
- 深度学习讲座笔记:Deep Learning for Computer Vision - Andrej Karpathy at Bay Area Deep Learning School
- Fast.ai: Practical Deep Learning for coders 课程学习笔记:Part1 Lesson1 (Lesson0)
- OpenCV中parallel_for 和 parallel_for_学习笔记
- [机器学习入门] 李宏毅机器学习笔记-10 (Tips for Deep Learning;深度学习小贴士)
- OpenCV for Ios 学习笔记(1)-配置
- Fast.ai: Practical Deep Learning for coders 课程学习笔记:Part1 Lesson1 (Lesson0)
- OpenCV for Ios 学习笔记(10)-标记检测总结