我正在尝试通过逻辑回归进行预测,并使用Python和sklearn库测试准确性。我正在使用从这里下载的数据:
http://archive.ics.uci.edu/ml/datasets/concrete+compressive+strength
其excel文件。我写了一个代码,但是我总是遇到相同的错误,错误是:
ValueError: Unknown label type: 'continuous'
进行线性回归时,我使用了相同的逻辑,并且适用于线性回归。
这是代码:
import numpy as np
import pandas as pd
import xlrd
from sklearn import linear_model
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
#Reading data from excel
data = pd.read_excel("DataSet.xls").round(2)
data_size = data.shape[0]
#print("Number of data:",data_size,"\n",data.head())
my_data = data[(data["Superpl"] == 0) & (data["FlyAsh"] == 0) & (data["BlastFurSlag"] == 0)].drop(columns=["Superpl","FlyAsh","BlastFurSlag"])
my_data = my_data[my_data["Days"]<=28]
my_data_size = my_data.shape[0]
#print("Size of dataset for 28 days or less:", my_data_size, "\n", my_data.head())
def logistic_regression(data_input, cement, water,
coarse_aggr, fine_aggr, days):
variable_list = []
result_list = []
for column in data_input:
variable_list.append(column)
result_list.append(column)
variable_list = variable_list[:-1]
result_list = result_list[-1]
variables = data_input[variable_list]
results = data_input[result_list]
#accuracy of prediction (splittig dataframe in train and test)
var_train, var_test, res_train, res_test = train_test_split(variables, results, test_size = 0.3, random_state = 42)
#making logistic model and fitting the data into logistic model
log_regression = linear_model.LogisticRegression()
model = log_regression.fit(var_train, res_train)
input_values = [cement, water, coarse_aggr, fine_aggr, days]
#predicting the outcome based on the input_values
predicted_strength = log_regression.predict([input_values]) #adding values for prediction
predicted_strength = round(predicted_strength[0], 2)
#calculating accuracy score
score = log_regression.score(var_test, res_test)
score = round(score*100, 2)
prediction_info = "\nPrediction of future strenght: " + str(predicted_strength) + " MPa\n"
accuracy_info = "Accuracy of prediction: " + str(score) + "%\n"
full_info = prediction_info + accuracy_info
return full_info
print(logistic_regression(my_data, 376.0, 214.6, 1003.5, 762.4, 3)) #true value affter 3 days: 16.28 MPa
答案 0 :(得分:2)
尽管您没有提供数据的详细信息,但是从错误和代码最后一行的注释来看:
#true value affter 3 days: 16.28 MPa
我认为您处于回归(即数字预测)设置中。线性回归是适合此任务的模型,但逻辑回归不是不是:逻辑回归是针对分类问题的,因此它期望将二进制(或分类)数据作为目标变量,而不是连续值,因此会出错。
简而言之,您正在尝试应用不适合您的问题的模型。
更新(链接到数据之后):实际上,仔细阅读数据集描述,您会看到(添加了重点):
混凝土抗压强度是回归问题
在scikit-learn User's Guide中进行逻辑回归(再次强调):
逻辑回归(尽管有名称)是用于分类而不是回归的线性模型。