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

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

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

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

Q&A

解決済

1回答

2793閲覧

sklearnの初歩的質問

tonyy

総合スコア1

Python

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

0グッド

0クリップ

投稿2021/08/13 07:52

前提・実現したいこと

Pythonでsklearnを使い始めたばかりで理解の不足が原因だと思います。どこが間違えか教えていただけませんか?よろしくお願いします。

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

--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-18-67d42641997b> in <module> 14 #print("a",model.coef_[0],"b",model.intercept_) 15 ---> 16 print('coefficient = ', model.coef_[0]) # 説明変数の係数を出力 17 print('intercept = ', model.intercept_) # 切片を出力 18 AttributeError: 'LinearRegression' object has no attribute 'coef_'

該当のソースコード

Pyton

1import pandas as pd 2import numpy as np 3import matplotlib.pyplot as plt 4from sklearn.linear_model import LinearRegression 5 6icecream = [[1,464],[2,397],[3,493],[4,617],[5,890],[6,883],[7,1292],[8,1387],[9,843],[10,621],[11,459],[12,561]] 7tempreture = [[1,10.6],[2,12,2],[3,14.9],[4,20.3],[5,25.2],[6,26.3],[7,29.7],[8,31.6],[9,27.7],[10,22.6],[11,15.5],[12,13.8]] 8 9X = pd.DataFrame([u[1] for u in tempreture]) 10Y = pd.DataFrame([u[1] for u in icecream]) 11 12model = LinearRegression() 13 14 15print('coefficient = ', model.coef_[0]) # 説明変数の係数を出力 16print('intercept = ', model.intercept_) # 切片を出力 17 18 19 20 21plt.scatter(X, Y) 22plt.plot(X, model.predict(X),plot = "red") 23plt.title("2016年の気温と一世帯当たりのアイスクリームの支出") 24plt.xlabel("月間平均気温") 25plt.ylabel("月間アイスクリーム支出") 26plt.grid() 27plt.show() 28

試したこと

書き直しなどしましたが、うまくいきません。

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

ここにより詳細な情報を記載してください。

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

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

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

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

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

guest

回答1

0

ベストアンサー

model = LinearRegression()の後にmodel.fit(X, Y)が必要です。


【ご参考】

Python

1import pandas as pd 2import numpy as np 3import matplotlib.pyplot as plt 4from sklearn.linear_model import LinearRegression 5 6icecream = [[1,464],[2,397],[3,493],[4,617],[5,890],[6,883],[7,1292],[8,1387],[9,843],[10,621],[11,459],[12,561]] 7tempreture = [[1,10.6],[2,12,2],[3,14.9],[4,20.3],[5,25.2],[6,26.3],[7,29.7],[8,31.6],[9,27.7],[10,22.6],[11,15.5],[12,13.8]] 8 9X = pd.DataFrame([u[1] for u in tempreture]) 10Y = pd.DataFrame([u[1] for u in icecream]) 11 12model = LinearRegression() 13model.fit(X, Y) 14 15plt.scatter(X, Y) 16plt.plot(X, model.predict(X),"red") 17plt.grid() 18plt.show()

イメージ説明

pandas 1.0.5
numpy 1.18.5
matplotlib 3.2.2
scikit-learn 0.23.1
Python 3.8.3

投稿2021/08/13 07:59

編集2021/08/13 10:47
meg_

総合スコア10607

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

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

meg_

2021/08/13 08:08

修正したコードを実行すると「AttributeError: 'Line2D' object has no property 'plot'」が発生しますが、こちらについては別のエラーになりますので一度質問者さんの方で原因を調べてみてください。
tonyy

2021/08/13 08:36

回答ありがとうございます。 修正コードを入れると回答者様の言うエラーとは異なるエラー文が出てきました。グラフに点は描写されるのですが、回帰直線が出てきません。どういった問題が考えられますか?よろしくお願いします。
meg_

2021/08/13 08:44

> 修正コードを入れると回答者様の言うエラーとは異なるエラー文が出てきました。 何のエラーでしょうか?
tonyy

2021/08/13 09:01

--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-20-46f15bb1f663> in <module> 20 21 plt.scatter(X, Y) ---> 22 plt.plot(X, model.predict(X),plot = "red") 23 plt.title("2016年の気温と一世帯当たりのアイスクリームの支出") 24 plt.xlabel("月間平均気温") ~\anaconda3\lib\site-packages\matplotlib\pyplot.py in plot(scalex, scaley, data, *args, **kwargs) 2838 @_copy_docstring_and_deprecators(Axes.plot) 2839 def plot(*args, scalex=True, scaley=True, data=None, **kwargs): -> 2840 return gca().plot( 2841 *args, scalex=scalex, scaley=scaley, 2842 **({"data": data} if data is not None else {}), **kwargs) ~\anaconda3\lib\site-packages\matplotlib\axes\_axes.py in plot(self, scalex, scaley, data, *args, **kwargs) 1741 """ 1742 kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D) -> 1743 lines = [*self._get_lines(*args, data=data, **kwargs)] 1744 for line in lines: 1745 self.add_line(line) ~\anaconda3\lib\site-packages\matplotlib\axes\_base.py in __call__(self, data, *args, **kwargs) 271 this += args[0], 272 args = args[1:] --> 273 yield from self._plot_args(this, kwargs) 274 275 def get_next_color(self): ~\anaconda3\lib\site-packages\matplotlib\axes\_base.py in _plot_args(self, tup, kwargs) 386 387 if len(tup) == 2: --> 388 x = _check_1d(tup[0]) 389 y = _check_1d(tup[-1]) 390 else: ~\anaconda3\lib\site-packages\matplotlib\cbook\__init__.py in _check_1d(x) 1316 message='Support for multi-dimensional indexing') 1317 -> 1318 ndim = x[:, None].ndim 1319 # we have definitely hit a pandas index or series object 1320 # cast to a numpy array. ~\anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key) 2900 if self.columns.nlevels > 1: 2901 return self._getitem_multilevel(key) -> 2902 indexer = self.columns.get_loc(key) 2903 if is_integer(indexer): 2904 indexer = [indexer] ~\anaconda3\lib\site-packages\pandas\core\indexes\range.py in get_loc(self, key, method, tolerance) 356 except ValueError as err: 357 raise KeyError(key) from err --> 358 raise KeyError(key) 359 return super().get_loc(key, method=method, tolerance=tolerance) 360 KeyError: (slice(None, None, None), None) こういったエラーでした。
meg_

2021/08/13 09:13

plt.plot(X, model.predict(X))にするとエラーは消えますか?
tonyy

2021/08/13 10:09

消えませんでした。
tonyy

2021/08/13 10:59

ありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.46%

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

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

質問する

関連した質問