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

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

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

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

Q&A

解決済

1回答

1131閲覧

Python3年生 機械学習のしくみ P191 LESSON23(教師なし学習を利用して、データをイメージしよう) リスト5.17の出力結果でエラー表示されます。解決方法を教示ください。

Risekorise

総合スコア1

Python

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

0グッド

0クリップ

投稿2023/04/16 00:26

実現したいこと

・数字画像データがどのようなものなのかイメージするため、次元削減を
使って3Dグラフで表示したい。(テキストのこのLESSONで実現しようとし
ていること)

前提

テキストの指示に従いコードを入力しました。
その結果、以下のエラーが表示されます。
ValueError: 'color' kwarg must be a color or sequence of color specs. For a sequence of values to be color-mapped, use the 'c' argument instead.

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

以下のとおりValueErrorが表示されます。

エラーメッセージ

ValueError Traceback (most recent call last)
File ~\anaconda3\lib\site-packages\matplotlib\axes_axes.py:4378, in Axes._parse_scatter_color_args(c, edgecolors, kwargs, xsize, get_next_color_func)
4377 try:
-> 4378 mcolors.to_rgba_array(kwcolor)
4379 except ValueError as err:

File ~\anaconda3\lib\site-packages\matplotlib\colors.py:485, in to_rgba_array(c, alpha)
484 else:
--> 485 rgba = np.array([to_rgba(cc) for cc in c])
486 else:

File ~\anaconda3\lib\site-packages\matplotlib\colors.py:485, in <listcomp>(.0)
484 else:
--> 485 rgba = np.array([to_rgba(cc) for cc in c])
486 else:

File ~\anaconda3\lib\site-packages\matplotlib\colors.py:299, in to_rgba(c, alpha)
298 if rgba is None: # Suppress exception chaining of cache lookup failure.
--> 299 rgba = _to_rgba_no_colorcycle(c, alpha)
300 try:

File ~\anaconda3\lib\site-packages\matplotlib\colors.py:374, in _to_rgba_no_colorcycle(c, alpha)
373 return c, c, c, alpha if alpha is not None else 1.
--> 374 raise ValueError(f"Invalid RGBA argument: {orig_c!r}")
375 # turn 2-D array into 1-D array

ValueError: Invalid RGBA argument: 'GLAY'

The above exception was the direct cause of the following exception:

ValueError Traceback (most recent call last)
Cell In[20], line 5
3 ax = fig.add_subplot(projection='3d')
4 # 各点の数字に対する色で散布図を描画
----> 5 ax.scatter(df[0], df[1], df[2], color=colors)
7 # 数字がどの色か見本を描画
8 ty = 0

File ~\anaconda3\lib\site-packages\matplotlib_init_.py:1442, in _preprocess_data.<locals>.inner(ax, data, *args, **kwargs)
1439 @functools.wraps(func)
1440 def inner(ax, *args, data=None, **kwargs):
1441 if data is None:
-> 1442 return func(ax, *map(sanitize_sequence, args), **kwargs)
1444 bound = new_sig.bind(ax, *args, **kwargs)
1445 auto_label = (bound.arguments.get(label_namer)
1446 or bound.kwargs.get(label_namer))

File ~\anaconda3\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py:2275, in Axes3D.scatter(self, xs, ys, zs, zdir, s, c, depthshade, *args, **kwargs)
2272 if np.may_share_memory(zs_orig, zs): # Avoid unnecessary copies.
2273 zs = zs.copy()
-> 2275 patches = super().scatter(xs, ys, s=s, c=c, *args, **kwargs)
2276 art3d.patch_collection_2d_to_3d(patches, zs=zs, zdir=zdir,
2277 depthshade=depthshade)
2279 if self._zmargin < 0.05 and xs.size > 0:

File ~\anaconda3\lib\site-packages\matplotlib_init_.py:1442, in _preprocess_data.<locals>.inner(ax, data, *args, **kwargs)
1439 @functools.wraps(func)
1440 def inner(ax, *args, data=None, **kwargs):
1441 if data is None:
-> 1442 return func(ax, *map(sanitize_sequence, args), **kwargs)
1444 bound = new_sig.bind(ax, *args, **kwargs)
1445 auto_label = (bound.arguments.get(label_namer)
1446 or bound.kwargs.get(label_namer))

File ~\anaconda3\lib\site-packages\matplotlib\axes_axes.py:4602, in Axes.scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, edgecolors, plotnonfinite, **kwargs)
4599 if edgecolors is None:
4600 orig_edgecolor = kwargs.get('edgecolor', None)
4601 c, colors, edgecolors =
-> 4602 self._parse_scatter_color_args(
4603 c, edgecolors, kwargs, x.size,
4604 get_next_color_func=self._get_patches_for_fill.get_next_color)
4606 if plotnonfinite and colors is None:
4607 c = np.ma.masked_invalid(c)

File ~\anaconda3\lib\site-packages\matplotlib\axes_axes.py:4380, in Axes._parse_scatter_color_args(c, edgecolors, kwargs, xsize, get_next_color_func)
4378 mcolors.to_rgba_array(kwcolor)
4379 except ValueError as err:
-> 4380 raise ValueError(
4381 "'color' kwarg must be a color or sequence of color "
4382 "specs. For a sequence of values to be color-mapped, use "
4383 "the 'c' argument instead.") from err
4384 if edgecolors is None:
4385 edgecolors = kwcolor

ValueError: 'color' kwarg must be a color or sequence of color specs. For a sequence of values to be color-mapped, use the 'c' argument instead.

該当のソースコード

ソースコード

from sklearn.datasets import load_digits
from sklearn import decomposition
from mpl_toolkits.mplot3d import Axes3D

digits = load_digits()
X = digits.data
y = digits.target

#0~9の色名を用意する
numbercolor = ["BLACK","BROWN","RED","DARKORANGE","GOLD","GREEN","BLUE","PURPLE","GLAY","SKYBLUE"]

# yの値を色名に変えて、colorsリストを作る
colors = []
for i in y:
colors.append(numbercolor[i])

# 主成分分析で、64個の特徴量を3個へと次元を減らす
pca = decomposition.PCA(n_components=3)
feature3 = pca.fit_transform(X)

# 3個へ減らしたデータ(features3)で、データフレームを作る
df = pd.DataFrame(feature3)

# 3D散布図の準備
fig = plt.figure(figsize=(12, 12))
ax = fig.add_subplot(projection='3d')

# 3個の特徴量をX,Y,Zにして、各点の数字に対する色で散布図を描画
ax.scatter(df[0], df[1], df[2], color=colors)

# 数字がどの色かの見本を描画
ty = 0
for col in numbercolor:
ax.text(50, 30, 30-ty*5, str(ty), size=20, color=col)
ty+=1
plt.show

試したこと

上記エラーでGoogleで検索して表示される対処方法は試してみましたが
が改善しませんでした。

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

バージョン Python 3.6.1

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

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

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

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

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

can110

2023/04/16 00:40

コードはコードブロックで囲んで提示ください。 なお、書籍サンプルをColab上で動作させましたが、正常に動作しました。 提示コードがサンプルと同じである場合は OS、Python、各パッケージのバージョンなど実行環境に関する情報も記載ください。
meg_

2023/04/16 02:10 編集

コードはインデントが判るように「コードの挿入」で記入してください。 また、「Googleで検索して表示される対処方法は試してみました」についても試したことを具体的に書きましょう。(同じ内容の回答を避けるためです)
meg_

2023/04/16 02:17 編集

質問のコードを試したところ下記エラーが発生しました。実際に質問者さんが実行されたコードを掲載いただけませんか? NameError: name 'pd' is not defined 【追記】下記エラーもです。 NameError: name 'plt' is not defined
guest

回答1

0

ベストアンサー

ChatGPT先生に聞いてみました。色名の綴り間違いが原因のようです。
誤)GLAY
正)GRAY
あと、ChatGPT先生の回答だと小文字に変更する必要があると書かれていますが、実際は大文字・小文字、どちらでも問題ないようです。


質問内容:
テキストの指示に従いコードを入力しました。
その結果、以下のエラーが表示されます。エラーン原因と対処方法を教えて下さい。

回答内容:
エラーメッセージから、問題はax.scatter(df[0], df[1], df[2], color=colors)color=colors引数で発生していることがわかります。color引数は、有効な色名、色コード、または色のシーケンスが必要です。エラーは「GLAY」という無効な色名が原因です。正しいスペルは「GRAY」です。また、"SKYBLUE" は "skyblue"(すべて小文字)に変更する必要があります。

次のようにnumbercolorリストを修正してください。

python

1numbercolor = ["black", "brown", "red", "darkorange", "gold", "green", "blue", "purple", "gray", "skyblue"]

修正後のコードは以下の通りです。

python

1from sklearn.datasets import load_digits 2from sklearn import decomposition 3from mpl_toolkits.mplot3d import Axes3D 4import pandas as pd 5import matplotlib.pyplot as plt 6 7digits = load_digits() 8X = digits.data 9y = digits.target 10 11numbercolor = ["black", "brown", "red", "darkorange", "gold", "green", "blue", "purple", "gray", "skyblue"] 12 13colors = [] 14for i in y: 15 colors.append(numbercolor[i]) 16 17pca = decomposition.PCA(n_components=3) 18feature3 = pca.fit_transform(X) 19 20df = pd.DataFrame(feature3) 21 22fig = plt.figure(figsize=(12, 12)) 23ax = fig.add_subplot(projection='3d') 24 25ax.scatter(df[0], df[1], df[2], color=colors) 26 27ty = 0 28for col in numbercolor: 29 ax.text(50, 30, 30-ty*5, str(ty), size=20, color=col) 30 ty+=1 31plt.show()

この修正により、エラーが解決され、3D散布図が正しく表示されるはずです。

投稿2023/04/16 00:47

編集2023/04/16 00:59
cx20

総合スコア4633

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

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

Risekorise

2023/04/16 08:04

解決できました! 無事3D散布図が表示されました。ChatGPTを使ったアドバイスありがとうございました。助かりました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問