如何在Python中使用Plotly绘制线性回归?

时间:2019-04-13 04:50:51

标签: python anaconda regression plotly

我是Python和Anaconda的新手,我正在尝试使用Plotly在Python数据集上绘制线性回归。我遵循了一些在线指南(即https://plot.ly/scikit-learn/plot-ols/

编辑:我必须使用Plotly而不是Matplotlib这样做,因为我也需要交互性。

到目前为止,这是我尝试过的:

import numpy as np
import pandas as pd
import seaborn as sb

from plotly import tools
import plotly as py
import plotly.graph_objs as go

import numpy as np
from sklearn import datasets, linear_model

py.offline.init_notebook_mode(connected=True)

# Import LinearRegression model from Scikit-Learn
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error

# Create a Linear Regression object
linreg = LinearRegression()


regline_x = x_train
regline_y = linreg.intercept_ + linreg.coef_ * y_train

from plotly import tools
import plotly as py
import plotly.graph_objs as go

py.offline.init_notebook_mode(connected=True)

def data_to_plotly(x):
    k = []

    for i in range(0, len(x)):
        k.append(x[i][0])

    return k

p1 = go.Scatter(x=data_to_plotly(x_test), 
                y=y_test, 
                mode='markers',
                marker=dict(color='black')
               )

p2 = go.Scatter(x=data_to_plotly(x_test), 
                y=linreg.predict(x_test),
                mode='lines',
                line=dict(color='blue', width=3)
                )

layout = go.Layout(xaxis=dict(ticks='', showticklabels=False,
                              zeroline=False),
                   yaxis=dict(ticks='', showticklabels=False,
                              zeroline=False),
                   showlegend=False, hovermode='closest')

fig = go.Figure(data=[p1, p2], layout=layout)

py.offline.iplot(fig)

但是,我不断收到以下错误消息:

KeyError                                  Traceback (most recent call last)
~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2656             try:
-> 2657                 return self._engine.get_loc(key)
   2658             except KeyError:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 0

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-54-dbba31d9eead> in <module>
     14 
     15     return k
---> 16 p1 = go.Scatter(x=data_to_plotly(x_test), 
     17                 y=y_test,
     18                 mode='markers',

<ipython-input-54-dbba31d9eead> in data_to_plotly(x)
     11 
     12     for i in range(0, len(x)):
---> 13         k.append(x[i][0])
     14 
     15     return k

~\Anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2925             if self.columns.nlevels > 1:
   2926                 return self._getitem_multilevel(key)
-> 2927             indexer = self.columns.get_loc(key)
   2928             if is_integer(indexer):
   2929                 indexer = [indexer]

~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2657                 return self._engine.get_loc(key)
   2658             except KeyError:
-> 2659                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2660         indexer = self.get_indexer([key], method=method, tolerance=tolerance)
   2661         if indexer.ndim > 1 or indexer.size > 1:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 0

如何解决此错误并使数据集在上面的链接中显示?

0 个答案:

没有答案