gpt4 book ai didi

python - 如何将 pandas.core.series.Series 类型转换为二维数组?

转载 作者:行者123 更新时间:2023-11-30 09:43:39 26 4
gpt4 key购买 nike

我正在尝试使用 KNNClassifier 训练模型。我将数据拆分如下:

X_train, X_test, y_train, y_test = train_test_split(X_bow, y, test_size=0.30, random_state=42)

y_train= y_train.astype('int')

neigh = KNeighborsClassifier(n_neighbors=3)
neigh.fit(X_train, y_train)

当我尝试测试它时,出现值错误。

pre = neigh.predict(y_test)

Expected 2D array, got 1D array instead:
array=[0. 1. 1. ... 0. 0. 0.].
Reshape your data either using array.reshape(-1, 1) if your data has a
single feature or array.reshape(1, -1) if it contains a single sample.

我的 y_test 类型为 pandas.core.series.Series

那么如何将 pandas.core.series.Series 转换为 2D 数组以使此测试有效?

我尝试将 y_test 转换为数据帧,然后转换为数组,但出现另一个值错误,并且陷入困境。

y_test = pd.DataFrame(y_test)
y_test = y_test.as_matrix().reshape(-1,1)
pre = neigh.predict(y_test)

ValueError: Incompatible dimension for X and Y matrices: X.shape[1] == 1 while Y.shape[1] == 6038

最佳答案

我想你需要使用你的X_test变量/数组,而不是y_test

X_test 是用于测试模型准确性的独立变量/特征,y_test 是实际的目标 将与预测值进行比较的值。

示例:

pre = neigh.predict(X_test)

测量准确性:

from sklearn.metrics import accuracy_score
accuracy_score(y_test, pre)

关于python - 如何将 pandas.core.series.Series 类型转换为二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55644465/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com