繁体   English   中英

如何绘制散点图并为 Python 中的两个特征绘制预测线?

[英]How can I plot a scatter graph and plot a prediction line for two features in Python?

我试图根据 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 的例子 这是我试图复制这个:

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

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]);

类型错误:无法理解数据类型

更新

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')

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

在此处输入图片说明

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

由于您有两个功能,因此无法绘制预测线。 如果有的话,您可能想要一个预测等高线图。

您的示例更类似于这里的两个功能示例https://scikit-learn.org/stable/auto_examples/svm/plot_iris.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM