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

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

新規登録して質問してみよう
ただいま回答率
85.48%
Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

機械学習

機械学習は、データからパターンを自動的に発見し、そこから知能的な判断を下すためのコンピューターアルゴリズムを指します。人工知能における課題のひとつです。

Python

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

API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

Q&A

解決済

1回答

24034閲覧

pythonで機械学習モデルを作り実行するとTypeError: float() argument must be a string or a number, not 'dict'とエラーが出た

Homaresan

総合スコア15

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

機械学習

機械学習は、データからパターンを自動的に発見し、そこから知能的な判断を下すためのコンピューターアルゴリズムを指します。人工知能における課題のひとつです。

Python

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

API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

0グッド

0クリップ

投稿2019/10/30 11:00

編集2019/10/30 12:22

前提・実現したいこと

Ruby on Railsで作ったWEBアプリとPythonで作った機械学習モデルの連携を最終目標として今作業しています。

そこで、まずpythonでlearning.pyというファイルに簡単な学習モデルを作成しました。python learning.pyで実行するとarray([1])と出力されるはずが、下記のようなエラーが出ました。
エラー文を見るとfloatの()引数は 'dict'ではなく文字列または数値でなければなりませんと書かれているのでエラー文を調べて見たが、解決法がわからなかったので対処法をご教示願いたいです。

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

/Users/takuma/opt/anaconda3/lib/python3.7/site-packages/sklearn/linear_model/logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning. FutureWarning) /Users/takuma/opt/anaconda3/lib/python3.7/site-packages/sklearn/linear_model/logistic.py:469: FutureWarning: Default multi_class will be changed to 'auto' in 0.22. Specify the multi_class option to silence this warning. "this warning.", FutureWarning) /Users/takuma/opt/anaconda3/lib/python3.7/site-packages/sklearn/externals/joblib/__init__.py:15: DeprecationWarning: sklearn.externals.joblib is deprecated in 0.21 and will be removed in 0.23. Please import this functionality directly from joblib, which can be installed with: pip install joblib. If this warning is raised when loading pickled models, you may need to re-serialize those models with scikit-learn 0.21+. warnings.warn(msg, category=DeprecationWarning) Traceback (most recent call last): File "learning.py", line 24, in <module> print(clf.predict([send_data])) File "/Users/takuma/opt/anaconda3/lib/python3.7/site-packages/sklearn/linear_model/base.py", line 289, in predict scores = self.decision_function(X) File "/Users/takuma/opt/anaconda3/lib/python3.7/site-packages/sklearn/linear_model/base.py", line 265, in decision_function X = check_array(X, accept_sparse='csr') File "/Users/takuma/opt/anaconda3/lib/python3.7/site-packages/sklearn/utils/validation.py", line 536, in check_array array = array.astype(np.float64) TypeError: float() argument must be a string or a number, not 'dict'

learning.py

from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression import pandas as pd iris = datasets.load_iris() X = pd.DataFrame(iris.data, columns=["sepal_length", "sepal_width", "petal_length", "petal_width"]) y = iris.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=0) clf = LogisticRegression() clf.fit(X_train, y_train) from sklearn.externals import joblib joblib.dump(clf, 'iris_logreg.pkl') joblib.dump(["sepal_length", "sepal_width", "petal_length", "petal_width"], 'iris_logreg_cols.pkl') send_data = [{'petal_length': 4.5, 'petal_width': 1.5, 'sepal_length': 6.0, 'sepal_width': 2.8999999999999999}] print(clf.predict([send_data]))

補足情報(FW/ツールのバージョンなど)

Ruby on Railsで作ったWEBアプリとPythonで作った機械学習モデルを連携するには?

の5.簡単な学習モデルを作る を参考に同じ機械学習モデルを作成しました。

この記事と全く同じ機械学習モデルを作成しlearning.pyを行うと

xpected 2D array, got scalar array instead:

というエラーが出現し調べてみたところ、learning.pyの最終行の記述が悪かったみたいなので、その箇所を上記のように修正したところ今回の質問のエラーが出ました。

修正前

print(clf.predict(send_data))

修正後

print(clf.predict([send_data]))

ツールのバージョンはpip freezeで確認すると下記の通りでした。

anaconda-client==1.7.2 anaconda-navigator==1.9.7 appnope==0.1.0 asn1crypto==1.2.0 attrs==19.3.0 backcall==0.1.0 backports.functools-lru-cache==1.5 backports.tempfile==1.0 backports.weakref==1.0.post1 beautifulsoup4==4.8.1 bleach==3.1.0 certifi==2019.9.11 cffi==1.13.0 chardet==3.0.4 Click==7.0 clyent==1.2.2 conda==4.7.12 conda-build==3.18.9 conda-package-handling==1.6.0 conda-verify==3.4.2 cryptography==2.8 decorator==4.4.0 defusedxml==0.6.0 entrypoints==0.3 filelock==3.0.12 future==0.17.1 glob2==0.7 idna==2.8 importlib-metadata==0.23 ipykernel==5.1.2 ipython==7.8.0 ipython-genutils==0.2.0 ipywidgets==7.5.1 jedi==0.15.1 Jinja2==2.10.3 joblib==0.13.2 json5==0.8.5 jsonschema==3.1.1 jupyter-client==5.3.4 jupyter-core==4.6.0 jupyterlab==1.1.4 jupyterlab-server==1.0.6 libarchive-c==2.8 lief==0.9.0 MarkupSafe==1.1.1 mistune==0.8.4 mkl-fft==1.0.14 mkl-random==1.1.0 mkl-service==2.3.0 more-itertools==7.2.0 navigator-updater==0.2.1 nbconvert==5.6.0 nbformat==4.4.0 notebook==6.0.1 numpy==1.17.2 olefile==0.46 pandas==0.25.2 pandocfilters==1.4.2 parso==0.5.1 pexpect==4.7.0 pickleshare==0.7.5 Pillow==6.2.0 pkginfo==1.5.0.1 prometheus-client==0.7.1 prompt-toolkit==2.0.10 psutil==5.6.3 ptyprocess==0.6.0 pycosat==0.6.3 pycparser==2.19 Pygments==2.4.2 pyOpenSSL==19.0.0 pyrsistent==0.15.4 PySocks==1.7.1 python-dateutil==2.8.0 pytz==2019.3 PyYAML==5.1.2 pyzmq==18.1.0 QtPy==1.9.0 requests==2.22.0 ruamel-yaml==0.15.46 scikit-learn==0.21.3 scipy==1.3.1 Send2Trash==1.5.0 six==1.12.0 soupsieve==1.9.3 terminado==0.8.2 testpath==0.4.2 tornado==6.0.3 tqdm==4.36.1 traitlets==4.3.3 urllib3==1.24.2 wcwidth==0.1.7 webencodings==0.5.1 widgetsnbextension==3.5.1 zipp==0.6.0

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

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

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

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

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

meg_

2019/10/30 11:44

リンクは「リンクの挿入」で記入してください。
Homaresan

2019/10/30 12:04

了解しました!直ぐに編集します!
guest

回答1

0

ベストアンサー

predictのところを下記のように書き換えたところ動きました。
※参考サイトの出力とは異なりますので、これでOKかどうかは分かりません。

python

1print(clf.predict(pd.io.json.json_normalize(send_data))) 2 3#[2]

疑問点はサイト作成者へ質問するのが一番良いと思います。

投稿2019/10/30 15:05

meg_

総合スコア10580

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

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

Homaresan

2019/10/30 17:12

ご回答ありがとうございます!自分も試したところ[2]が返ってきました。もう少し考えてみて解決できなかったらサイト作成者へ質問します!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問