无法针对熊猫数据框绘制线性回归预测模型

时间:2018-07-18 17:22:19

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

我正在尝试使用世界银行API针对大熊猫中的数据框绘制预测线性回归模型。我想使用自变量输入和预测该日期的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)

1 个答案:

答案 0 :(得分:1)

代码已运行,并确定了多个问题。

  1. OP希望针对date的{​​{1}}绘制y预测值。

此行的结果:x_test

X = data1[data1.columns[[1,2,3,4,5]]]不再包含x_test(第0列)。在包含date的{​​{1}}中运行train_test_split(X, Y, test_size=0.1),以获取与每个数据点相关的正确日期,并在删除此列的情况下运行带有x_test副本的线性模型(因为日期不是独立的)变量)。

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

X实际上包含“ GDP”,并省略了另一个可能的自变量。推荐的方法是从数据中明确删除“ GDP”。

  1. 在同一图中绘制包含熊猫的折线图和散点图

OP需要一个实际GDP与年份的线图:date,然后是一个散点图X = data1[data1.columns[[1,2,3,4,5]]]。为此,请使用data1.plot.line(x='date', y='GDP')定义一个轴对象,并在同一子图上绘制它们。

plt.scatter(X_test['date'], predictions)