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

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

新規登録して質問してみよう
ただいま回答率
85.46%
Jupyter

Jupyter (旧IPython notebook)は、Notebook形式でドキュメント作成し、プログラムの記述・実行、その実行結果を記録するツールです。メモの作成や保存、共有、確認などもブラウザ上で行うことができます。

Matplotlib

MatplotlibはPythonのおよび、NumPy用のグラフ描画ライブラリです。多くの場合、IPythonと連携して使われます。

NumPy

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

Python

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

Q&A

解決済

1回答

1888閲覧

PythonでPCA(別名は主成分分析で、次元削減手法の一つ)を実行しましたが、エラーが出ています。

hiyoko-kun

総合スコア23

Jupyter

Jupyter (旧IPython notebook)は、Notebook形式でドキュメント作成し、プログラムの記述・実行、その実行結果を記録するツールです。メモの作成や保存、共有、確認などもブラウザ上で行うことができます。

Matplotlib

MatplotlibはPythonのおよび、NumPy用のグラフ描画ライブラリです。多くの場合、IPythonと連携して使われます。

NumPy

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

Python

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

0グッド

0クリップ

投稿2020/09/11 08:49

編集2020/09/11 11:11

前提・実現したいこと

PCA解説 sklearnで主成分分析を試してみよう!
上記のサイトのソースコードをコピペしてPCAを実行しましたが、
エラーがでましたのでそれを解決したいです。

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

--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-31-8a964de16c1f> in <module> 38 39 # embed3dはT-SNEで作った三次元のデータフレームです。 ---> 40 embed3d.iplot(kind="scatter3d", # 種類=3D散布図 41 x="X", y="Y", z="Z", # x軸,y軸,z軸を指定 42 mode="markers", # プロットの見た目を変える指定です ValueError: Invalid value of type 'numpy.int32' received for the 'name' property of scatter3d Received value: 0 The 'name' property is a string and must be specified as: - A string - A number that will be converted to a string

該当のソースコード

python

1from matplotlib import pyplot as plt 2 3import numpy as np # Pythonで機械学習をするならとりあえずimport 4from sklearn.decomposition import PCA # 今回の主役。scikit-learnのPCAクラス 5from sklearn import datasets # デモ用のデータセットを読み込むモジュール 6import seaborn as sns # 可視化用のライブラリ 7import pandas as pd # 便利なDataFrameを使うためのライブラリ 8import cufflinks as cf # おしゃれな可視化のために必要なライブラリ その2 9 10cf.go_offline() # cufflinksをオフラインで使うため 11 12wine = datasets.load_wine() # wineデータを読み込み 13df = pd.DataFrame(wine.data) # DataFrame形式に変換 14df["label"] = wine["target"] # データのクラスをDataFrameの列の一つとして追加 15df.head() # 試しにDataFrameの先頭5行を表示してみましょう 16 17sns.pairplot(df.iloc[:,:-1]) # df.iloc[:, :-1]にすることですべての行の 18 # 最後の列以外を指定して可視化します 19plt.show() 20 21pca = PCA(n_components=3) # 3次元に圧縮するPCAインスタンスを作成 22X = pca.fit_transform(df.iloc[:,:-1].values) # wineデータをPCAで次元圧縮 23embed3 = pd.DataFrame(X) # 可視化のためにデータフレームに変換 24embed3["label"] = df["label"] 25embed3.head() # データフレームの先頭を表示 26 27embed3.iplot(kind="scatter3d", x=0,y=1,z=2,categories="label")

試したこと

github
上記のサイトに似たエラーがありましたので参考にしましたが、
どこをいじればよいかわからず、解決されませんでした。

以下は上記のサイトに書いてあった解決方法です。

I have made a python script to draw a 3D scatter map. Usually I can draw it online by the code: x = [] y = [] z = [] hover = [] trace = {} layout = {} #creating trace for i in range(len(np.unique(y_le))): name = np.unique(y_random)[i] # color = range(len(X_tsne['Name'].unique))[i] color = c[i] x = X_tsne[y_random == name][:, 0] y = X_tsne[y_random == name][:, 1] z = X_tsne[y_random == name][:, 2] hover = filename_random[y_random == name] trace = dict( name=name, x=x, y=y, z=z, type="scatter3d", mode='markers', # colorscale='Viridis' text=hover, marker=dict(size=2, color=color, line=dict(width=0))) data.append(trace) #creating fig layout = dict( width=1600, height=1200, autosize=False, title='t-SNE embedding - hover', scene=dict( xaxis=dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)' ), yaxis=dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)' ), zaxis=dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)' ), aspectratio=dict(x=1, y=1, z=0.7), aspectmode='manual' ), ) fig = dict(data=data, layout=layout) url = py.plot(fig, filename='tSNE embedding') However, when I tried to draw them offline by this: plotly.offline.plot(fig)

it raises the error
ValueError:
Invalid value of type 'numpy.int64' received for the 'name' property of scatter3d
Received value: 0
The 'name' property is a string and must be specified as:

  • A string
  • A number that will be converted to a string

I tried to replace the line name = name in making trace by using name = '%d' % name but it still the same error

How can I draw offline plot by plotly in this case?

以下は問題に対する解決策です。

The error message is talking about about the name property that you specify on this line: trace = dict( name=name, # <- Here x=x, y=y, z=z, ... ) This property must be a Python string or a Python number (int or float) and it's receiving a numpy int64 object. Try casting the numpy int to a Python int like this: trace = dict( name=int(name), # <- Here x=x, y=y, z=z, ... )

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

windows10を使用。

jupyter notebookに出力された詳細なエラー内容を追記しました。

ValueError Traceback (most recent call last) <ipython-input-25-edb1ce2e1dfc> in <module> 25 embed3.head() # データフレームの先頭を表示 26 ---> 27 embed3.iplot(kind="scatter3d", x=0,y=1,z=2,categories="label") ~\anaconda3\lib\site-packages\cufflinks\plotlytools.py in _iplot(self, kind, data, layout, filename, sharing, title, xTitle, yTitle, zTitle, theme, colors, colorscale, fill, width, dash, mode, interpolation, symbol, size, barmode, sortbars, bargap, bargroupgap, bins, histnorm, histfunc, orientation, boxpoints, annotations, keys, bestfit, bestfit_colors, mean, mean_colors, categories, x, y, z, text, gridcolor, zerolinecolor, margin, labels, values, secondary_y, secondary_y_title, subplots, shape, error_x, error_y, error_type, locations, lon, lat, asFrame, asDates, asFigure, asImage, dimensions, asPlot, asUrl, online, **kwargs) 796 else: 797 _size=size --> 798 _data=Scatter3d(x=_x,y=_y,mode=mode,name=_, 799 marker=dict(color=colors[_],symbol=symbol,size=_size,opacity=opacity, 800 line=dict(width=width)),textfont=tools.getLayout(theme=theme)['xaxis']['titlefont']) ~\anaconda3\lib\site-packages\plotly\graph_objs\_scatter3d.py in __init__(self, arg, connectgaps, customdata, customdatasrc, error_x, error_y, error_z, hoverinfo, hoverinfosrc, hoverlabel, hovertemplate, hovertemplatesrc, hovertext, hovertextsrc, ids, idssrc, legendgroup, line, marker, meta, metasrc, mode, name, opacity, projection, scene, showlegend, stream, surfaceaxis, surfacecolor, text, textfont, textposition, textpositionsrc, textsrc, texttemplate, texttemplatesrc, uid, uirevision, visible, x, xcalendar, xsrc, y, ycalendar, ysrc, z, zcalendar, zsrc, **kwargs) 2327 _v = name if name is not None else _v 2328 if _v is not None: -> 2329 self["name"] = _v 2330 _v = arg.pop("opacity", None) 2331 _v = opacity if opacity is not None else _v ~\anaconda3\lib\site-packages\plotly\basedatatypes.py in __setitem__(self, prop, value) 4017 # ### Handle simple property ### 4018 else: -> 4019 self._set_prop(prop, value) 4020 else: 4021 # Make sure properties dict is initialized ~\anaconda3\lib\site-packages\plotly\basedatatypes.py in _set_prop(self, prop, val) 4335 return 4336 else: -> 4337 raise err 4338 4339 # val is None ~\anaconda3\lib\site-packages\plotly\basedatatypes.py in _set_prop(self, prop, val) 4330 4331 try: -> 4332 val = validator.validate_coerce(val) 4333 except ValueError as err: 4334 if self._skip_invalid: ~\anaconda3\lib\site-packages\_plotly_utils\basevalidators.py in validate_coerce(self, v) 1080 v = str(v) 1081 else: -> 1082 self.raise_invalid_val(v) 1083 1084 if self.no_blank and len(v) == 0: ~\anaconda3\lib\site-packages\_plotly_utils\basevalidators.py in raise_invalid_val(self, v, inds) 273 name += "[" + str(i) + "]" 274 --> 275 raise ValueError( 276 """ 277 Invalid value of type {typ} received for the '{name}' property of {pname} ValueError: Invalid value of type 'numpy.int32' received for the 'name' property of scatter3d Received value: 0 The 'name' property is a string and must be specified as: - A string - A number that will be converted to a string

よろしくお願いいたします。

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

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

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

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

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

meg_

2020/09/11 10:52

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

2020/09/11 11:11

ご指導下さりありがとうございます。 承知しました。
guest

回答1

0

ベストアンサー

google colabで試したところ、確かにエラーが出ますね。

ValueError: Invalid value of type 'numpy.int64' received for the 'name' property of scatter3d Received value: 0 The 'name' property is a string and must be specified as: - A string - A number that will be converted to a string

エラーメッセージに従い下記コードを加えるとエラーは出なくなりましたが、google colabではグラフは描画されませんでしたので動作確認までは出来ませんでした。

Python

1embed3['label'] = embed3['label'].astype(str) 2embed3.iplot(kind="scatter3d", x=0,y=1,z=2,categories="label")

エラーは出なくなったので、google colab以外の環境ではおそらく動作するのではないかと思います。

投稿2020/09/11 11:29

meg_

総合スコア10602

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

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

hiyoko-kun

2020/09/11 15:05

夜分遅くに失礼いたします。 jupyter notebookで確認したところ、正しく動きました。 丁寧に教えて下さり、ありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.46%

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

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

質問する

関連した質問