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

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

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

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

Q&A

解決済

1回答

1394閲覧

pythonでのRuntimeError

ruuruusann24

総合スコア16

Python 3.x

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

0グッド

0クリップ

投稿2017/11/24 06:08

編集2017/11/24 06:15

度々すみません
これの最後のshow_volonoi_with_metrics(dist.euclidean)でエラーが出てしまいます。
なにか良い方法はありますでしょうか
以下エラーです

RuntimeError Traceback (most recent call last)
<ipython-input-62-670a63d7ce7e> in <module>()
----> 1 show_volonoi_with_metrics(dist.euclidean)

<ipython-input-61-e1fd4304de1a> in show_volonoi_with_metrics(metrics)
15 xs = map(lambda p: p[0], cluster_points)
16 ys = map(lambda p: p[1], cluster_points)
---> 17 ax.scatter(xs, ys, color=cm.prism(i / float(len(c_means))), marker='.')
18
19 ax.scatter(map(lambda p: p[0], c_means), map(lambda p: p[1], c_means), color="g", marker='o')

~/anaconda3/envs/styletrans/lib/python3.6/site-packages/matplotlib/init.py in inner(ax, *args, **kwargs)
1708 warnings.warn(msg % (label_namer, func.name),
1709 RuntimeWarning, stacklevel=2)
-> 1710 return func(ax, *args, **kwargs)
1711 pre_doc = inner.doc
1712 if pre_doc is None:

~/anaconda3/envs/styletrans/lib/python3.6/site-packages/matplotlib/axes/_axes.py in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, **kwargs)
4007 edgecolors = 'face'
4008
-> 4009 self._process_unit_info(xdata=x, ydata=y, kwargs=kwargs)
4010 x = self.convert_xunits(x)
4011 y = self.convert_yunits(y)

~/anaconda3/envs/styletrans/lib/python3.6/site-packages/matplotlib/axes/_base.py in _process_unit_info(self, xdata, ydata, kwargs)
1967 # we only need to update if there is nothing set yet.
1968 if not self.xaxis.have_units():
-> 1969 self.xaxis.update_units(xdata)
1970
1971 if ydata is not None:

~/anaconda3/envs/styletrans/lib/python3.6/site-packages/matplotlib/axis.py in update_units(self, data)
1430 """
1431
-> 1432 converter = munits.registry.get_converter(data)
1433 if converter is None:
1434 return False

~/anaconda3/envs/styletrans/lib/python3.6/site-packages/matplotlib/units.py in get_converter(self, x)
160 if converter is None:
161 try:
--> 162 thisx = safe_first_element(x)
163 except (TypeError, StopIteration):
164 pass

~/anaconda3/envs/styletrans/lib/python3.6/site-packages/matplotlib/cbook/init.py in safe_first_element(obj)
2310 except TypeError:
2311 pass
-> 2312 raise RuntimeError("matplotlib does not support generators "
2313 "as input")
2314 return next(iter(obj))

RuntimeError: matplotlib does not support generators as input

以下コードです

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import scipy.spatial.distance as dist
%matplotlib inline

def label_cluster_num(means, mesh_points, metrics):
def label(point):
cluster_label = np.argmin(map(lambda mean: metrics(mean, point), means))
return point, cluster_label
return map(label, mesh_points)

c_means = np.array([[1, 2], [-3, 4], [-5, -6], [7, -8]])
xs = np.linspace(-10, 10, 100)
ys = np.linspace(-10, 10, 100)
xx, yy = np.meshgrid(xs, ys)
mesh_points = np.c_[xx.ravel(), yy.ravel()]

def show_volonoi_with_metrics(metrics):
labeled_mesh_points = label_cluster_num(c_means, mesh_points, metrics=metrics)
plt.figure()
fig, ax = plt.subplots()

ax.set_aspect('equal') ax.grid(True, which='both') ax.axhline(y=0, color='k') ax.axvline(x=0, color='k') ax.set_xlim([-10, 10]) ax.set_ylim([-10, 10]) for i in range(0, len(c_means)): cluster_points = map(lambda p, label: p, filter(lambda p, label: label == i, labeled_mesh_points)) xs = map(lambda p: p[0], cluster_points) ys = map(lambda p: p[1], cluster_points) ax.scatter(xs, ys, color=cm.prism(i / float(len(c_means))), marker='.') ax.scatter(map(lambda p: p[0], c_means), map(lambda p: p[1], c_means), color="g", marker='o') plt.show()

show_volonoi_with_metrics(dist.euclidean)

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

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

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

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

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

mkgrei

2017/11/24 06:13

高度の嫌がらせですか…RuntimeErrorの詳細がないと、手元で実行しないとデバッグは無理ですよ。
LouiS0616

2017/11/24 06:36

ネットで拾ってきたコードを、ろくに調べず/考えず動かそうとして失敗するのは当たり前です。拾い食いして腹を壊すようなものです。
guest

回答1

0

ベストアンサー

仮説ですが、オリジナルのコードはPython2.xでmapがlistを返していたのです。
そして今、Python3.xを使っているせいで、mapがイテレータを返してきているので、matplotlibは困惑している状況です。

すべてのmap(...)をlist(map(...))のようにlistで囲むと解決する可能性が高いです。


追記
古いlambda関数の挙動を初めて知りました。
簡潔な解決法はpython2.xを使用することでした。

以下にpython3.xで動くコードを載せます。

python

1import numpy as np 2import matplotlib.pyplot as plt 3import matplotlib.cm as cm 4import scipy.spatial.distance as dist 5%matplotlib inline 6 7def label_cluster_num(means, mesh_points, metrics): 8 def label(point): 9 cluster_label = np.argmin(list(map(lambda mean: metrics(mean, point), means))) 10 return point, cluster_label 11 return list(map(label, mesh_points)) 12 13c_means = np.array([[1, 2], [-3, 4], [-5, -6], [7, -8]]) 14xs = np.linspace(-10, 10, 100) 15ys = np.linspace(-10, 10, 100) 16xx, yy = np.meshgrid(xs, ys) 17mesh_points = np.c_[xx.ravel(), yy.ravel()] 18 19def show_volonoi_with_metrics(metrics): 20 labeled_mesh_points = label_cluster_num(c_means, mesh_points, metrics=metrics) 21 plt.figure() 22 fig, ax = plt.subplots() 23 24 ax.set_aspect('equal') 25 ax.grid(True, which='both') 26 ax.axhline(y=0, color='k') 27 ax.axvline(x=0, color='k') 28 ax.set_xlim([-10, 10]) 29 ax.set_ylim([-10, 10]) 30 31 for i in range(0, len(c_means)): 32 cluster_points = list(map(lambda p: p[0], filter(lambda p: p[1] == i, labeled_mesh_points))) 33 xs = list(map(lambda p: p[0], cluster_points)) 34 ys = list(map(lambda p: p[1], cluster_points)) 35 ax.scatter(xs, ys, color=cm.prism(i / float(len(c_means))), marker='.') 36 37 ax.scatter(list(map(lambda p: p[0], c_means)), list(map(lambda p: p[1], c_means)), color="g", marker='o') 38 39 plt.show() 40 41show_volonoi_with_metrics(dist.euclidean)

読みやすいバージョン

python

1import numpy as np 2import matplotlib.pyplot as plt 3import matplotlib.cm as cm 4import scipy.spatial.distance as dist 5%matplotlib inline 6 7def label_cluster_num(means, mesh_points, metrics): 8 def label(point): 9 cluster_label = np.argmin([metrics(p, point) for p in means]) 10 return cluster_label 11 return np.array([label(p) for p in mesh_points]) 12 13c_means = np.array([[1, 2], [-3, 4], [-5, -6], [7, -8]]) 14xs = np.linspace(-10, 10, 100) 15ys = np.linspace(-10, 10, 100) 16xx, yy = np.meshgrid(xs, ys) 17mesh_points = np.c_[xx.ravel(), yy.ravel()] 18 19def show_volonoi_with_metrics(metrics): 20 labels = label_cluster_num(c_means, mesh_points, metrics=metrics) 21 fig, ax = plt.subplots() 22 23 ax.set_aspect('equal') 24 ax.grid(True, which='both') 25 ax.axhline(y=0, color='k') 26 ax.axvline(x=0, color='k') 27 ax.set_xlim([-10, 10]) 28 ax.set_ylim([-10, 10]) 29 30 for i in range(0, len(c_means)): 31 cluster_points = mesh_points[labels==i] 32 xs = cluster_points[:, 0] 33 ys = cluster_points[:, 1] 34 ax.scatter(xs, ys, color=cm.prism(i / float(len(c_means))), marker='.') 35 36 ax.scatter(c_means[:, 0], c_means[:, 0], color="g", marker='o') 37 38 plt.show() 39 40show_volonoi_with_metrics(dist.euclidean)

投稿2017/11/24 06:29

編集2017/11/24 06:38
mkgrei

総合スコア8560

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

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

LouiS0616

2017/11/24 06:42

コピー元のサイトに『環境:python: anaconda-4.0.0』って書いてあるあたりお察しですね。 動けばいい類のコードみたいです。
ruuruusann24

2017/11/24 06:44

ありがとうございます!無事解決しました!今後ともよろしくお願いします!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問