前提・実現したいこと
自作したデータセットを用いて、
入力した画像が犬か猫かを判別するプログラムを作成したいです。
学習させて、精度を求めるところまで、作成できたのですが、
画像を読み込んで、predictするとエラーが発生しました。
発生している問題・エラーメッセージ
X has 64 features, but LogisticRegression is expecting 2500 features as input. 翻訳: Xには64の機能がありますが、LogisticRegressionは入力として2500の機能を期待しています。
該当のソースコード
画像をテストデータにして、predictするプログラム。
Python
import cv2 import matplotlib.pyplot as plt %matplotlib inline def predict_digit(filename): #画像を読み込む my_img = cv2.imread(filename) plt.imshow(my_img) plt.show() #グレースケールに変換する my_img = cv2.cvtColor(my_img, cv2.COLOR_BGR2GRAY) # 8 * 8のサイズに変換する my_img = cv2.resize(my_img,(8,8)) # plt.imshow(my_img) # plt.show() #白黒反転する my_img = 15 - my_img // 16 plt.imshow(my_img) #画像を貼り付ける plt.axis('off') #グラフのメモリを消す plt.show() #画像を表示する # print(my_img) #二次元を一次元に変換 my_img = my_img.reshape((-1,64)) res = clf.predict(my_img) return res[0] n = predict_digit("dog.jpg") print("dog.jpg = " + str(n))
学習して、精度を出すまでのプログラム
Python3
#集めた画像データを学習データにする import matplotlib.pyplot as plt import os import cv2 import random import numpy as np DATADIR = "C:/Users/19t339/Documents/work/犬と猫/PetImages" CATEGORIES = ["Dog", "Cat"] IMG_SIZE = 50 training_data = [] def create_training_data(): for class_num, category in enumerate(CATEGORIES): path = os.path.join(DATADIR, category) for image_name in os.listdir(path): try: img_array = cv2.imread(os.path.join(path, image_name), cv2.IMREAD_GRAYSCALE) # 画像読み込み img_resize_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE)) # 画像のリサイズ training_data.append([img_resize_array, class_num]) # 画像データ、ラベル情報を追加 except Exception as e: pass create_training_data() random.shuffle(training_data) # データをシャッフル X_train = [] # 画像データ y_train = [] # ラベル情報 # データセット作成 for feature, label in training_data: X_train.append(feature) y_train.append(label) # numpy配列に変換 X_train = np.array(X_train) y_train = np.array(y_train) #変数の名前を分かりやすくする X = X_train y = y_train #画像データの次元を3次元から2次元へ落としている X= X.reshape(len(X), -1).astype(np.float64) y= y.reshape(len(y), -1).astype(np.float64) #学習データとテストデータのシャッフル from sklearn.model_selection import ShuffleSplit ss = ShuffleSplit(n_splits=1, train_size=0.8, test_size=0.2, random_state=0) train_index, test_index = next(ss.split(X,y)) X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] #学習と精度評価 from sklearn import linear_model clf = linear_model.LogisticRegression(solver='liblinear') clf.fit(X_train,y_train) clf.score(X_test,y_test)
試したこと
画像ファイルの拡張子の変更。
エラーメッセージの検索
補足情報(FW/ツールのバージョンなど)
jupiter notebook
まだ回答がついていません
会員登録して回答してみよう