当前位置:   article > 正文

PCA降维(主成分分析)处理训练集后,线上正式数据应该如何处理?_pca降维,线上预测的时候单条数据怎么处理

pca降维,线上预测的时候单条数据怎么处理

训练数据集在使用PCA进行数据降维后,用基本分类器进行训练得到一个分类模型,那线上预测真实数据应该怎么办?应该不能直接放入训练的分类模型中去吧?

答:当然不能,要用你从训练数据里面得到的那个降维矩阵对测试数据降维,然后再送给分类器。

如何理解?如何操作?
参考PCA+SVM的模型的保存及使用

训练模型的代码,仔细阅读注释内容

  1. import numpy as np
  2. import os
  3. import cv2
  4. from sklearn.model_selection import train_test_split
  5. from sklearn.preprocessing import LabelEncoder
  6. import pickle
  7. import sklearn.metrics as sm
  8. from sklearn.metrics import classification_report
  9. import sklearn.svm as svm
  10. from sklearn.decomposition import PCA
  11. from sklearn.svm import SVC
  12. from time import time
  13. from sklearn.model_selection import GridSearchCV
  14. def cv_imread(file_path):
  15. cv_img = cv2.imdecode(np.fromfile(file_path,dtype=np.uint8),-1) #打开文件中含有中文路径的图片
  16. return cv_img
  17. def search_files(directory):
  18. images=[]
  19. labels=[]
  20. for curdir, subdir, files in os.walk(directory):#根据路径,得到文件夹的的地址, 下面的子目录名称, 目录下的所有文件
  21. for file in files:
  22. if file.endswith('.jpg'):
  23. label = curdir.split(os.path.sep)[-1]#用分隔符'\' 进行切割,得到所在的文件夹最后一个单词,作为标签
  24. path = os.path.join(curdir,file) #拼接路径
  25. img = cv_imread(path)
  26. img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
  27. img = cv2.resize(img_gray,(256,256))
  28. h,w = img.shape
  29. img_col = img.reshape(h*w)
  30. images.append(img_col)
  31. labels.append(label)
  32. return images,labels
  33. img , labels = search_files('./train_pic')
  34. label_encoder = LabelEncoder()
  35. y = label_encoder.fit_transform(labels)
  36. X, Y = np.array(img), np.array(labels)
  37. train_x, test_x, train_y, test_y = train_test_split(X,Y, test_size=0.25,random_state=7)
  38. t0 = time()
  39. #这里我一直没想明白怎么把他给保存了, 方便以后的使用
  40. pca = PCA(n_components=20, svd_solver='randomized', whiten=True).fit(train_x) #取20个特征,并且fit 这个train_x
  41. print("done in %0.3fs" % (time() - t0))
  42. X_train_pca = pca.transform(train_x) #得到训练集投影系数
  43. X_test_pca = pca.transform(test_x) #得到测试集投影系数
  44. #这是找到最佳的参数.
  45. param_grid = {'C': [1e3, 5e3, 1e4, 5e4, 1e5],
  46. 'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1], }
  47. clf = GridSearchCV(SVC(kernel='poly', class_weight='balanced'), param_grid)
  48. clf = clf.fit(X_train_pca, train_y)
  49. output_dir = './output'
  50. print("Best estimator found by grid search:")
  51. print(clf.best_estimator_)
  52. y_pred = clf.predict(X_test_pca)
  53. print("done in %0.3fs" % (time() - t0))
  54. print(classification_report(test_y, y_pred))
  55. def save_model(model,pca,label_encoder,output_file):
  56. try:
  57. with open(output_file,'wb') as outfile:
  58. pickle.dump({
  59. 'model':model,
  60. 'pca_fit':pca,
  61. 'label_encoder':label_encoder
  62. },outfile)
  63. return True
  64. except:
  65. return False
  66. #这里重点说一下, 这个pca是能够直接保存并使用的,自己之前忘了这回事, 纠结了好久,不知道预测的时候怎么办.
  67. save_model(clf,pca,label_encoder,os.path.join(output_dir,'model_svm_poly_test010412.pkl'))


这一步已经训练并保存好了模型,接下来就可以进行模型的预测及使用了.
 

  1. import pickle
  2. import os
  3. import cv2
  4. import numpy as np
  5. from sklearn.decomposition import PCA
  6. output_dir='./output/'
  7. '''定义一个用于分类的Predictor'''
  8. class Predictor(object):
  9. def __init__(self,model_file):
  10. with open(model_file,'rb') as infile:
  11. self.loaded = pickle.load(infile)
  12. self.model = self.loaded['model']
  13. #把刚才训练的模型中的pca 读取出来, 后面可以直接对单张图片进行transform, 并进行预测了.
  14. self.pca = self.loaded['pca_fit']
  15. self.label_encoder = self.loaded['label_encoder']
  16. def cv_imread(self,file_path):
  17. cv_img = cv2.imdecode(np.fromfile(file_path,dtype=np.uint8),-1)
  18. return cv_img
  19. '''实现分类逻辑'''
  20. def predict(self,img_file):
  21. '''读取图像文件'''
  22. img = self.cv_imread(img_file)
  23. img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
  24. img = cv2.resize(img_gray,(256,256))
  25. h,w = img.shape
  26. img_col = np.array([img.reshape(h*w)])
  27. #对图片进行transform 得到特征
  28. X_test_pca =self.pca.transform(img_col)
  29. '''预测分类'''
  30. y = self.model.predict(X_test_pca)
  31. # print(y)
  32. return y
  33. predictor = Predictor('./output/model_svm_poly_test010412.pkl')
  34. '''对新图片进行分类'''
  35. label = predictor.predict('C:/Users/ugc/Desktop/20190325分类器训练图片/AI测试图片集/train/train_big_small/test_data/big/22.jpg')


ok,主要将 pca 这个直接保存成文件, 以后使用直接调用文件即可,这样就方便多了。网上的资料很少,我觉得实际环境中降维的工作很少用到,再多的维度分布式系统也可以处理,单机或者比赛中可能会用到降维。

应用pca降维就是将fit后的数据保存成文件,正式环境调用这个文件,对数据进行降维,再将降维后的数据输入到模型中。

参考:

https://blog.csdn.net/rocketye/article/details/89246549

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/304183
推荐阅读
相关标签
  

闽ICP备14008679号