質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
scikit-learn

scikit-learnは、Pythonで使用できるオープンソースプロジェクトの機械学習用ライブラリです。多くの機械学習アルゴリズムが実装されていますが、どのアルゴリズムも同じような書き方で利用できます。

NumPy

NumPyはPythonのプログラミング言語の科学的と数学的なコンピューティングに関する拡張モジュールです。

OpenCV

OpenCV(オープンソースコンピュータービジョン)は、1999年にインテルが開発・公開したオープンソースのコンピュータビジョン向けのクロスプラットフォームライブラリです。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

1566閲覧

画像データの特徴量を抽出し機械学習用のデータセットを作りたい

shishi_maru440

総合スコア38

scikit-learn

scikit-learnは、Pythonで使用できるオープンソースプロジェクトの機械学習用ライブラリです。多くの機械学習アルゴリズムが実装されていますが、どのアルゴリズムも同じような書き方で利用できます。

NumPy

NumPyはPythonのプログラミング言語の科学的と数学的なコンピューティングに関する拡張モジュールです。

OpenCV

OpenCV(オープンソースコンピュータービジョン)は、1999年にインテルが開発・公開したオープンソースのコンピュータビジョン向けのクロスプラットフォームライブラリです。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2021/04/12 15:25

編集2021/04/13 21:25

前提・実現したいこと

自前の画像データから機械学習用のデータセットを作成し学習させたいのですが、
モデルをfitさせた時に下記エラーにより実行できません。画像データを配列にする
ときの方法が不適切ではと考えているのですが、解決方法をご存知の方ご教示ください。

発生している問題・エラーメッセージ

--------------------------------------------------------------------------- TypeError Traceback (most recent call last) TypeError: only size-1 arrays can be converted to Python scalars The above exception was the direct cause of the following exception: ValueError Traceback (most recent call last) ValueError: setting an array element with a sequence.

該当のソースコード

python

1import pandas as pd 2import numpy as np 3import glob 4import cv2 5 6df2 = pd.read_csv("data2.csv") 7df2.shape 8 9 10#file pathの設定(フォルダ内の画像データを読み込み 画像データは6486枚) 11files = glob.glob("/Users/a440/Desktop/happy_images/*") 12len(files) 13 14#filesのデータフレームを作成 15df_files = pd.DataFrame({"data":files}) 16 17#dataのformatを合わせる 18df2["data"] = "/Users/a440/Desktop/happy_images/" + df2["data"] + ".jpg" 19df2 = df2.drop("Unnamed: 0", axis=1) 20df2.to_csv("data2-2.csv") 21 22#df2とdf_filesをdata列でマージする 23df_join = pd.merge(df2, df_files, how="inner",on="data",indicator=True) 24df_join.shape

OUT

16441, 3
df_join.to_csv("df_join.csv") **#targetにsmileのカテゴリを代入 smiles =df_join["smile"] target = [] for smile in smiles: data = np.asarray(smile) target.append(data) y = np.array(target)** y

OUT

1array([1, 3, 1, ..., 3, 3, 3])
#photo_array に画像データの配列を代入 titles = df_join["data"] image_size = 50 photo_array = [] for title in titles: bgr = cv2.imread(title, cv2.IMREAD_GRAYSCALE) bgr = np.asarray(bgr) photo_array.append(bgr) x = np.array(photo_array) x[0]

OUT

1array([[217, 217, 217, ..., 188, 196, 203], 2 [217, 217, 217, ..., 188, 196, 203], 3 [217, 217, 217, ..., 188, 196, 204], 4 ..., 5 [ 4, 4, 4, ..., 44, 43, 42], 6 [ 4, 4, 4, ..., 44, 43, 42], 7 [ 4, 4, 4, ..., 44, 43, 41]], dtype=uint8)
from sklearn import linear_model clf = linear_model.LogisticRegression() from sklearn.model_selection import StratifiedKFold ss = StratifiedKFold(n_splits=10, shuffle=True) for train_index, test_index in ss.split(x, y): x_train, x_test = x[train_index], x[test_index] y_train, y_test = y[train_index], y[test_index] clf.fit(x_train, y_train) print(clf.score(x_test, y_test))
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) TypeError: only size-1 arrays can be converted to Python scalars The above exception was the direct cause of the following exception: ValueError Traceback (most recent call last) <ipython-input-15-305a5bf690e8> in <module> 10 y_train, y_test = y[train_index], y[test_index] 11 ---> 12 clf.fit(x_train, y_train) 13 print(clf.score(x_test, y_test)) 14 /opt/anaconda3/lib/python3.7/site-packages/sklearn/linear_model/_logistic.py in fit(self, X, y, sample_weight) 1342 X, y = self._validate_data(X, y, accept_sparse='csr', dtype=_dtype, 1343 order="C", -> 1344 accept_large_sparse=solver != 'liblinear') 1345 check_classification_targets(y) 1346 self.classes_ = np.unique(y) /opt/anaconda3/lib/python3.7/site-packages/sklearn/base.py in _validate_data(self, X, y, reset, validate_separately, **check_params) 430 y = check_array(y, **check_y_params) 431 else: --> 432 X, y = check_X_y(X, y, **check_params) 433 out = X, y 434 /opt/anaconda3/lib/python3.7/site-packages/sklearn/utils/validation.py in inner_f(*args, **kwargs) 70 FutureWarning) 71 kwargs.update({k: arg for k, arg in zip(sig.parameters, args)}) ---> 72 return f(**kwargs) 73 return inner_f 74 /opt/anaconda3/lib/python3.7/site-packages/sklearn/utils/validation.py in check_X_y(X, y, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, multi_output, ensure_min_samples, ensure_min_features, y_numeric, estimator) 800 ensure_min_samples=ensure_min_samples, 801 ensure_min_features=ensure_min_features, --> 802 estimator=estimator) 803 if multi_output: 804 y = check_array(y, accept_sparse='csr', force_all_finite=True, /opt/anaconda3/lib/python3.7/site-packages/sklearn/utils/validation.py in inner_f(*args, **kwargs) 70 FutureWarning) 71 kwargs.update({k: arg for k, arg in zip(sig.parameters, args)}) ---> 72 return f(**kwargs) 73 return inner_f 74 /opt/anaconda3/lib/python3.7/site-packages/sklearn/utils/validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, estimator) 596 array = array.astype(dtype, casting="unsafe", copy=False) 597 else: --> 598 array = np.asarray(array, order=order, dtype=dtype) 599 except ComplexWarning: 600 raise ValueError("Complex data not supported\n" /opt/anaconda3/lib/python3.7/site-packages/numpy/core/_asarray.py in asarray(a, dtype, order) 81 82 """ ---> 83 return array(a, dtype, copy=False, order=order) 84 85 ValueError: setting an array element with a sequence.

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

自己解決

2次元配列にすることで解決できました。

投稿2021/04/15 14:51

shishi_maru440

総合スコア38

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問