2016-12-13 1 views
2

Код для использования в учебном процессе изолированного леса для создания файла .pkl (здесь вы можете увидеть ссылку scikit-learn .org/стабильный/модули/генерироваться/...). После генерации файла .pkl я должен загрузить его с ubuntu в ОС raspbian. Однако я столкнулся с этой ошибкой «ValueError: не распознал макет загруженного массива». Кто-нибудь может мне с этим помочь? Полная ошибка:Ошибка Python после загрузки файла .pkl «ValueError: не распознал макет загруженного массива»

Traceback (most recent call last):
File "oneclass_test.py", line 24, in
 clf_one,stdSlr,voc,k = joblib.load('oneclass.pkl')
File "/usr/local/lib/python2.7/dist-packages/sklearn/externals/joblib/numpy_pickle.py", line 575, in
 load obj = _unpickle(fobj, filename, mmap_mode)
File "/usr/local/lib/python2.7/dist-packages/sklearn/externals/joblib/numpy_pickle.py", line 507, in
 _unpickle obj = unpickler.load()
File "/usr/lib/python2.7/pickle.py", line 858, in
 load dispatchkey
File "/usr/local/lib/python2.7/dist-packages/sklearn/externals/joblib/numpy_pickle.py", line 327, in
 load_build Unpickler.load_build(self)
File "/usr/lib/python2.7/pickle.py", line 1217, in
 load_build setstate(state)
File "sklearn/tree/_tree.pyx", line 650, in
 sklearn.tree._tree.Tree.setstate (sklearn/tree/_tree.c:8406)
ValueError: Did not recognise loaded array layout

oneclass_train.py:

#!/usr/local/bin/python2.7 

import argparse as ap 
# Importing library that supports user friendly commandline interfaces 
import cv2 
# Importing the opencv library 
import imutils 
# Importing the library that supports basic image processing functions 
import numpy as np 
# Importing the array operations library for python 
import os 
# Importing the library which supports standard systems commands 
from scipy.cluster.vq import * 
# Importing the library which classifies set of observations into clusters 
from sklearn.externals import joblib 
from sklearn.svm import OneClassSVM 
from sklearn.neighbors import KNeighborsClassifier 

clf_one,stdSlr, voc,k = joblib.load("oneclass.pkl") 

# Get the path of the testing set 
parser = ap.ArgumentParser() 
group = parser.add_mutually_exclusive_group(required=True) 
group.add_argument("-t", "--testingSet", help="Path to testing Set") 
group.add_argument("-i", "--image", help="Path to image") 
parser.add_argument('-v',"--visualize", action='store_true') 
args = vars(parser.parse_args()) 

# Get the path of the testing image(s) and store them in a list 
image_paths = [] 
if args["testingSet"]: 
    test_path = args["testingSet"] 
    try: 
     testing_names = os.listdir(test_path) 
    except OSError: 
     print "No such directory {}\nCheck if the file  exists".format(test_path) 
     exit() 
    for testing_name in testing_names: 
     dir = os.path.join(test_path, testing_name) 
     class_path = imutils.imlist(dir) 
     image_paths+=class_path 
else: 
    image_paths = [args["image"]] 

# Create feature extraction and keypoint detector objects 
fea_det = cv2.xfeatures2d.SIFT_create() 
des_ext = cv2.xfeatures2d.SIFT_create() 

# List where all the descriptors are stored 
des_list = [] 
for image_path in image_paths: 
    im = cv2.imread(image_path) 
    r = 960.0/im.shape[1] 
    dim = (960, int(im.shape[0]*r)) 
    im = cv2.resize(im, dim, interpolation = cv2.INTER_AREA) 
    if im == None: 
     print "No such file {}\nCheck if the file exists".format(image_path) 
     exit() 
    img=im 
    img2=im 
    s = 75 
    mask = np.zeros(img.shape[:2],np.uint8) 
    bgdModel = np.zeros((1,65),np.float64) 
    fgdModel = np.zeros((1,65),np.float64) 
    rect = (s,s,im.shape[1]-(2*s),im.shape[0]-(2*s)) cv2.grabCut(img,mask,rect,bgdModel,fgdModel,1,cv2.GC_INIT_WITH_RECT) 
    mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8') 
    im = img*mask2[:,:,np.newaxis] 
    cv2.imwrite(image_path + "_Segment.jpg" ,im) 
    print im.shape 
    cv2.namedWindow("segmentation", cv2.WINDOW_NORMAL) 
    pt = (0, 3 * im.shape[0] // 4) 
    cv2.putText(im, "segmentation", pt ,cv2.FONT_HERSHEY_SCRIPT_COMPLEX, 3, [0, 255, 0], 5) 
    cv2.imshow("segmentation", im) 
    cv2.waitKey(2000) 
    kpts = fea_det.detect(im) # Computing the key points of test image 
    kpts, des = des_ext.compute(im, kpts) # Computing the descriptors of the test image 
    des_list.append((image_path, des)) # Appending the descriptors to a single list 

# Stack all the descriptors vertically in a numpy array 
descriptors = des_list[0][1] 
for image_path, descriptor in des_list[0:]: 
    descriptors = np.vstack((descriptors, descriptor)) # Stacking the descriptors in to a numpy array 

# Computing the histogram of features 
test_features = np.zeros((len(image_paths), k), "float32") 
for i in xrange(len(image_paths)): 
    words, distance = vq(des_list[i][1],voc) 
    for w in words: 
     test_features[i][w] += 1 # Calculating the histogram of features 

# Perform Tf-Idf vectorization 
nbr_occurences = np.sum((test_features > 0) * 1, axis = 0) # Getting the number of occurrences of each word 
idf = np.array(np.log((1.0*len(image_paths)+1)/(1.0*nbr_occurences + 1)), 'float32') 
# Assigning weight to one that is occurring more frequently 

test_features = stdSlr.transform(test_features) 

predictions = [] 
confidences = [] 

predictions = [] 
pred = clf_one.predict(test_features) 
print clf_one.predict(test_features) 
for i in pred: 
    if i == 1: 
      predictions += ["PPB"] 
     if i == -1: 
      predictions += ["NOT PPB"] 

a=0 
# Visualize the results, if "visualize" flag set to true by the user 
if args["visualize"]: 
    for image_path, prediction in zip(image_paths, predictions): 
     image = cv2.imread(image_path) 
     cv2.namedWindow(str(image_path), cv2.WINDOW_NORMAL) 
     pt = (0, 3 * image.shape[0] // 4) 
     cv2.putText(image, prediction , pt ,cv2.FONT_HERSHEY_SCRIPT_COMPLEX, 5, [0, 255, 0], 5) 
     cv2.imshow(str(image_path), image) 
     cv2.imwrite(image_path + "_oneclass_Result.jpg" ,image) 
     cv2.waitKey(3000) 
     cv2.destroyAllWindows() 
     a= a + 1 
+0

К сожалению, это мой первый раз, чтобы оставлять сообщения. Приведенный выше код используется для процесса обучения изолированного леса для создания файла .pkl (вы можете увидеть ссылку здесь http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.IsolationForest.html). Я загружаю файл .pkl с ubuntu в ОС raspbian. После запуска кода я столкнулся с приведенной выше ошибкой. –

+0

Не комментируйте комментарии с дополнительной информацией или пояснениями: отредактируйте вопрос. Вы знаете версию протокола, используемую в файле .pkl из ubuntu? Ваш вопрос помечен 'python-2.7', который не будет распаковывать версию 3 (не знаю о сообщении об ошибке). – greybeard

+0

@greybeard i уже отредактировал вопрос –

ответ

1

попробовать соответствующие версии библиотек, используемых в обоих raspbian и убунту

+0

Я сопоставил версию sklearn на моем малине pi (работает Raspbian Jessie) и настольную систему (работает Ubuntu 16.04). Версия sklearn на обеих машинах - «0.18.1». Даже я соответствовал версии numpy, scipy, pandas. Но все-таки я получаю такую ​​же ошибку: «Не распознал загруженный массив макета», когда я пытаюсь загрузить файл model.pkl, обученный на настольной системе Ubuntu на Raspberry Pi (Raspbian Jessie). Пожалуйста, дайте мне знать о том, что еще я могу попробовать ... Спасибо ... – sansingh

Смежные вопросы