python中的逻辑回归Erorr:ValueError:无法将字符串转换为浮点:“凹度\u最差”

2024-09-28 20:16:56 发布

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

我正在尝试为一个数据集编写一个简单的逻辑回归程序,该数据集如下:https://imgur.com/a/dJvb8Sienter image description here

我的程序应该在数据集上使用逻辑回归,并输出一些关于回归结果的信息。使用一个示例,我编写了以下代码:

import matplotlib.pyplot as plt
from scipy import stats

import pandas as pd
col_names = ['id', 'diagnosis', 'radius_mean', 'texture_mean', 'perimeter_mean', 'area_mean', 'smoothness_mean','compactness_mean', 'symmetry_se', 'perimeter_worst', 'smoothness_worst', 'concavity_worst']

# load dataset
data = pd.read_csv("DatasetTest.csv", header=None, names=col_names)
data.head()

feature_cols = ['diagnosis', 'radius_mean','texture_mean','perimeter_mean','area_mean', 'smoothness_mean','compactness_mean', 'symmetry_se', 'perimeter_worst','smoothness_worst', 'concavity_worst']
X = data[feature_cols]
y = data.diagnosis

from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.25,random_state=0)

from sklearn.linear_model import LogisticRegression
logreg = LogisticRegression()
logreg.fit(X_train,y_train)
y_pred=logreg.predict(X_test)

from sklearn import metrics
cnf_matrix = metrics.confusion_matrix(y_test, y_pred)
cnf_matrix

运行代码时会发生以下错误:

could not convert string to float: 'concavity_worst'

在stackoverflow上找不到类似的问题。经过研究,我发现函数fit()显然不能接受字符串。但我不知道如何将字符串转换为浮点数。在做了一些谷歌搜索之后,我仍然找不到解决这种情况的方法

代码使用的示例:https://towardsdatascience.com/a-beginners-guide-to-linear-regression-in-python-with-scikit-learn-83a8f7ae2b4f


Tags: 数据代码fromtestimportdatanamestrain
1条回答
网友
1楼 · 发布于 2024-09-28 20:16:56

根据{}的熊猫{a1},您需要

Explicitly pass header=0 to be able to replace existing names

如果不这样做,它将把文件头作为数据的一部分。因此,现在所有列名都与数据混合在一起,并且所有列都包含一个字符串。这将使回归崩溃,因为它不能接受字符串作为输入

相关问题 更多 >