【问题标题】:Can't plot linear regression predicted model against pandas dataframe无法针对熊猫数据框绘制线性回归预测模型
【发布时间】:2018-12-26 17:05:28
【问题描述】:

我正在尝试使用世界银行 API 针对 pandas 中的数据框绘制预测线性回归模型。我想使用自变量来输入和预测当前的 GDP 增长。更多的预测,但我真的很挣扎。此外,准确度得分为 1,这很奇怪,因为这肯定意味着它是一个完美的预测?到目前为止,这是我想出的:

#Connect to world bank api
!pip install wbdata

#Load libraries
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn import datasets, linear_model
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

#Load indicator data
indicators = {"NY.GDP.MKTP.CD": "GDP",
              "NE.CON.PRVT.ZS": "Households and NPISHs Final consumption expenditure (% of GDP)",
              "BX.KLT.DINV.WD.GD.ZS": "Foreign direct investment, net inflows (% of GDP)",
              "NE.CON.GOVT.ZS": "General government final consumption expenditure (% of GDP)",
              "NE.EXP.GNFS.ZS": "Exports of goods and services (% of GDP)",
              "NE.IMP.GNFS.ZS": "Imports of goods and services (% of GDP)" }

#Create dataframe
data = wbdata.get_dataframe(indicators, 
                            country=('GBR'), 
                            data_date=data_dates, 
                            convert_date=False, keep_levels=True)

#Round columns to 2dp
data1 = np.round(data, decimals=2)

#Convert datatype
data1['GDP'] = data1.GDP.astype(float)

#Format digits
data1['GDP'] = data1['GDP'].apply(lambda x: '{:.2f}'.format(x))

#Reset dataframe indexes
data1.reset_index(inplace=True) 

#Drop unused columns
data1.drop(data1.columns[[0]], axis=1, inplace=True)

#Converts all columns in dataframe to float datatypes
data1=data1.astype(float)

#data1.head(11)

#Dependent variable
Y = data1['GDP']

#Independent variable
X = data1[data1.columns[[1,2,3,4,5]]]

#Converts all columns in dataframe to float datatypes
data1=data1.astype(float)

#Create testing and training variables
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.1)

#Fit linear model
linear = linear_model.LinearRegression()
model = lm.fit(X_train, y_train)
predictions = lm.predict(X_test)

#Plot model
plt.scatter(y_test, predictions)
plt.xlabel('True Values')
plt.ylabel('Predictions')
plt.show()

#Print accuracy scores
accuracy = model.score(X_test, y_test)
print("Accuracy: ", accuracy)

【问题讨论】:

  • 什么是 data_dates?您的代码还有一些其他错误使其难以运行。
  • 你的测试集太小了,只有五个数据点,所以准确率达到 1 并不难。
  • data_dates 是来自世界银行 api 的年份值。代码对我来说运行良好?
  • 我想将它绘制在以下 data1.plot.line(x='date', y='GDP') 上,这样预测值将与实际值一致?
  • data_date=data_dates 给了我未定义的错误。请检查。

标签: python pandas scikit-learn linear-regression forecasting


【解决方案1】:

代码已运行并发现多个问题。

  1. OP 希望根据 datex_test 绘制预测的 y 值。

由于这一行:X = data1[data1.columns[[1,2,3,4,5]]]

x_test 不再包含 date(第 0 列)。运行train_test_split(X, Y, test_size=0.1)X 包含date 以获取与每个数据点关联的正确日期,并使用删除此列的x_test 副本运行线性模型(因为日期不是自变量)。

  1. 高精度是由于在自变量中包含了因变量。

X = data1[data1.columns[[1,2,3,4,5]]] 实际上包含“GDP”并省略了另一个可能的自变量。推荐的方法是从数据中明确删除“GDP”。

  1. 使用 Pandas 绘制折线图并在同一图中绘制散点图

OP 想要实际 GDP 与年份的线图:data1.plot.line(x='date', y='GDP'),然后是散点图 plt.scatter(X_test['date'], predictions)。为此,请使用 subplots 定义一个坐标区对象,并将两者绘制在同一个子图上。

f, ax = plt.subplots()
data1.plot.line(x='date', y='GDP', ax = ax)
ax.scatter(X_test['date'], predictions)
plt.show()

【讨论】:

    猜你喜欢
    • 2017-06-03
    • 2015-02-04
    • 2021-08-16
    • 2018-03-19
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 2021-12-11
    相关资源
    最近更新 更多