无法针对 pandas 数据框绘制线性回归预测模型
Can't plot linear regression predicted model against pandas dataframe
我正在尝试使用世界银行 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)
代码为 运行,发现了多个问题。
- OP 想要针对
x_test
的 date
绘制预测的 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
以获得与每个数据点关联的正确日期,运行 线性模型具有 [=47= 的副本] 删除此列(因为日期不是自变量)。
- 高准确度是因为在自变量中包含了因变量。
X = data1[data1.columns[[1,2,3,4,5]]]
实际上包含'GDP'并省略了另一个可能的自变量。推荐的方法是从数据中明确删除 'GDP'。
- 在同一张图中用 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()
我正在尝试使用世界银行 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)
代码为 运行,发现了多个问题。
- OP 想要针对
x_test
的date
绘制预测的 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
以获得与每个数据点关联的正确日期,运行 线性模型具有 [=47= 的副本] 删除此列(因为日期不是自变量)。
- 高准确度是因为在自变量中包含了因变量。
X = data1[data1.columns[[1,2,3,4,5]]]
实际上包含'GDP'并省略了另一个可能的自变量。推荐的方法是从数据中明确删除 'GDP'。
- 在同一张图中用 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()