在Python中将CSV转换为CLF

2024-03-28 10:24:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到一个TypeError“TypeError:只有整数标量数组可以转换为标量索引”。你知道吗

我不太清楚为什么,我找不到任何东西来解释为什么我会犯那个错误。有人能解释一下我做错了什么并提出改正的方法吗?你知道吗

import numpy as np
from sklearn.metrics import accuracy_score
from sklearn.neural_network import MLPClassifier

data1 = np.loadtxt('0003_1.csv', delimiter=",")

indices = np.random.permutation(len(data1.data))

split = round(len(indices) * 0.8)
x_train = data1.data[indices[:split]]
y_train = data1.target[indices[:split]]
x_test = data1.data[indices[split:]]
y_test = data1.target[indices[split:]]


clf = MLPClassifier(hidden_layer_sizes=(100, 100, 100), max_iter=500, alpha=0.0001, solver='sgd', verbose=10, random_state=21, tol=0.000000001)
clf.fit(x_train, y_train)
y_pred = clf.predict(x_test)
accuracy_score(y_test, y_pred)

Tags: fromtestimportdatanptrainsklearnsplit
1条回答
网友
1楼 · 发布于 2024-03-28 10:24:50

假设您没有逐行尝试这段代码,查看沿途的结果,这公平吗?你知道吗

您没有提供csv文件,但是以这种方式调用的loadtxt只能生成一个二维浮点数组,因此让我们用np.ones来模拟:

In [637]: data1 = np.ones((10,10))

这样的数组确实具有data属性,即memoryview

In [638]: data1.data
Out[638]: <memory at 0x7fc5b6916c18>

它没有target属性。您的csv可能有这样名称的列(但是您没有读取标题),但是loadtxt没有这样加载它们。你知道吗

In [639]: data1.target
                                     -
AttributeError                            Traceback (most recent call last)
<ipython-input-639-43b9ce1927aa> in <module>()
  > 1 data1.target

AttributeError: 'numpy.ndarray' object has no attribute 'target'

但让我们向前看你的错误。.data有一个len就像data1,所以indices工作:

In [640]: indices = np.random.permutation(len(data1.data))
In [641]: indices
Out[641]: array([0, 7, 6, 4, 8, 5, 2, 1, 9, 3])
In [642]: split = round(len(indices) * 0.8)
In [643]: split
Out[643]: 8
In [644]: indices[:split]
Out[644]: array([0, 7, 6, 4, 8, 5, 2, 1])

但是memoryview不能用切片索引:

In [645]: data1.data[indices[:split]]
                                     -
TypeError                                 Traceback (most recent call last)
<ipython-input-645-b6cf2f74578c> in <module>()
  > 1 data1.data[indices[:split]]

TypeError: only integer scalar arrays can be converted to a scalar index

可以使用此切片索引2d数组:

In [646]: data1[indices[:split]]
Out[646]: 
array([[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]])

所以问题的根源是认为data1.datadata1.target是有用的表达式。实际上,您没有按预期加载数据对象,或者没有按预期的方式加载数据对象。你没有检查data1。你知道吗

相关问题 更多 >