【问题标题】:How can I plot a scatter graph and plot a prediction line for two features in Python?如何在 Python 中为两个特征绘制散点图并绘制预测线?
【发布时间】:2019-01-08 09:02:14
【问题描述】:

我试图根据 X 中包含的两个特征来预测 y。在读取我的 excel 文件并将我的数据分成列后,我的 X 值如下所示:

     SibSp  Parch
0        1      0
1        1      0
2        0      0
3        1      0
4        0      0
5        0      0
6        0      0
7        3      1
8        0      2
9        1      0

y表示存活率,1表示存活,0表示死亡。 X 有更多的行。我正在使用train_test_split(X, y, test_size=0.4, random_state=101) 来获取训练和测试数据拆分,并有一种方法来训练和测试。我的训练代码如下所示:

def train():
    # Get Data Split
    X_train, X_test, y_train, y_test = initData()

    # Create LinearRegression Instance
    lm = LinearRegression()

    # Fit Training Values
    lm.fit(X_train,y_train)

    visualise(X_test, y_test, lm.predict(X_test))

    # Return Trained Data With Testing Data
    return X_test, y_test, lm

我的测试代码如下所示:

def test():
    # Get The Trained Classifier
    X, y, lm = train()

    # Fit New Values
    lm.fit(X, y)

    visualise(X, y, lm.predict(X))

其中,似乎工作正常 - 至少我认为。我现在正在尝试将数据可视化为带有预测线图的散点图。

def visualise(X, y, predictions):
    features = X.shape[1]
    colors   = ['red', 'blue']
    i        = 0
    while i <= features -1:
        plt.scatter(X.iloc[:, i], y, color=colors[i])
        # Update: Forgot to add this line when posting question
        plt.plot(X.iloc[:, i], predictions, color=colors[i])
        i=+1

但这给了我疯狂的输出,到处都是线条。我尝试在网上查找并找到sklearn's example。这是我试图复制这个:

我想也许,因为我有两个特征,我可能需要分别识别它们。

def visualise(X, y, predictions):
    newY = np.zeros(X.shape[0], X.shape[1]);
    newY[:, 0:1] = newY.iloc[:, 0]
    plt.scatter(X, y, color='blue')
    plt.plot(X, predictions, color='red')

    plt.xticks(())
    plt.yticks(())

    plt.show()

我必须创建一个 newY 数组,因为 X 有两个特征,y 有 1,所以形状不同。但是现在我在newY = np.zeros(X.shape[0], X.shape[1]); 行遇到错误

TypeError: 数据类型不理解

更新

def visualise(X, y, predictions):
    newY = np.zeros((X.shape[0], X.shape[1]));
    newY[:, 0] = y
    newY[:, 1] = y
    plt.scatter(X, newY, color='blue')
    plt.plot(X, predictions, color='red')

现在修复错误,但这是我的输出:

如何绘制散点图并为预测绘制一条线?

【问题讨论】:

  • 请至少提供一个拒绝投票的理由,我提供了一个 MCVE,我尝试过的所有东西,研究过,我还在尝试吗?但是线条正在变得精神上

标签: python pandas numpy logistic-regression


【解决方案1】:

由于您有两个特征,您无法绘制预测线。如果有的话,您可能需要预测等高线图。

您的示例与此处的两个功能示例更相似 https://scikit-learn.org/stable/auto_examples/svm/plot_iris.html

【讨论】:

  • 我可以预测每个特征,计算整体预测分数,即特征 1:0.3456.. 2:0.256434 所以整体将是 0.3,然后画一条这样的线?或者将这些价值观结合在一起并称之为“家庭”是否更有意义,因为 SibSP 是兄弟姐妹,Parch 是配偶,使其成为一个特征?
  • 您可以将其中一个变量保持不变,然后将预测绘制为另一个变量的函数。您必须考虑绘图的 x 和 y 轴上的内容。如果预测在 y 轴上,则只能在 x 轴上绘制一个变量。这就是为什么我建议使用等高线图;变量可以绘制在 x 和 y 轴上,颜色代表预测值。
猜你喜欢
  • 2016-03-19
  • 1970-01-01
  • 1970-01-01
  • 2013-10-04
  • 2022-07-28
  • 2018-12-29
  • 1970-01-01
  • 1970-01-01
  • 2021-12-12
相关资源
最近更新 更多