我对python很陌生,所以我调整了在线资源中的代码,试图创建这个回归。我从中提取的代码运行良好,除了数据源之外,我几乎没有更改任何内容,所以我不确定我做错了什么。任何帮助都是难以置信的!这是我正在使用的代码:
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
dfgmatgpa = df[["GradGPA", "GMATscore"]]
dfgmatgpa = dfgmatgpa.dropna()
dfgmatgpa.head()
GradGPA GMATscore
17 2.80000 340.0
18 2.80000 340.0
32 4.15000 660.0
36 3.88143 570.0
41 3.28571 540.0
# Load the diabetes dataset
gmatgpa_X, gmatgpa_y = dfgmatgpa(return_X_y=True)
# Use only one feature
gmatgpa_X = gmatgpa_X[:, np.newaxis, 2]
# Split the data into training/testing sets
gmatgpa_X_train = gmatgpa_X[:-20]
gmatgpa_X_test = gmatgpa_X[-20:]
# Split the targets into training/testing sets
gmatgpa_y_train = gmatgpa_y[:-20]
gmatgpa_y_test = gmatgpa_y[-20:]
# Create linear regression object
regr = linear_model.LinearRegression()
# Train the model using the training sets
regr.fit(gmatgpa_X_train, gmatgpa_y_train)
# Make predictions using the testing set
gmatgpa_y_pred = regr.predict(gmatgpa_X_test)
# The coefficients
print('Coefficients: n', regr.coef_)
# The mean squared error
print('Mean squared error: %.2f'
% mean_squared_error(gmatgpa_y_test, gmatgpa_y_pred))
# The coefficient of determination: 1 is perfect prediction
print('Coefficient of determination: %.2f'
% r2_score(gmatgpa_y_test, gmatgpa_y_pred))
# Plot outputs
plt.scatter(gmatgpa_X_test, gmatgpa_y_test, color='black')
plt.plot(gmatgpa_X_test, gmatgpa_y_pred, color='blue', linewidth=3)
plt.xticks(())
plt.yticks(())
plt.show()
错误:
TypeError Traceback (most recent call last)
<ipython-input-321-b5f145507243> in <module>
----> 1 gmatgpa_X, gmatgpa_y = dfgmatgpa(return_X_y=True)
2
3 # Use only one feature
4 gmatgpa_X = gmatgpa_X[:, np.newaxis, 2]
5
TypeError: 'DataFrame' object is not callable
也许您指的是这样的示例代码:
from sklearn.datasets import load_iris
data = load_iris(return_X_y=True)
这里的load_iris()
是一个函数,当return_X_y为True时,它返回一个(data,target(元组。
https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html
在您的情况下,您将dfgmatgpa
定义为一个数据帧,而不是一个函数,这就是您出现错误的原因。但是您可以根据需要分别定义X和y:gmatgpa_X
作为数据帧,gmatgpa_y
作为目标列表。