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



我正在尝试使用世界银行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. OP希望绘制预测的y值与x_testdate的关系图

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

x_test不再包含date(列0(。运行train_test_split(X, Y, test_size=0.1)和包含dateX,以获得与每个数据点关联的正确日期,并在删除该列的情况下运行带有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()

最新更新