简体   繁体   English

Sklearn预测python3.5

[英]Sklearn predict python3.5

I am training a Logistic Regression model using sklearn LogisticRegression. 我正在使用sklearn LogisticRegression训练Logistic回归模型。 I am getting a TypeError when trying to predict for the test set. 尝试预测测试集时出现TypeError错误。

CODE: 码:

test_features=test[["Sex","Age","Pclass","Fare","Embarked"]].values
myprediction=myfit2.predict(test_features)

ERROR: 错误:

float() argument must be a string or a number float()参数必须是字符串或数字

I've checked the syntax a few times.Could this be because I'm using Python 3.5. 我已经检查过几次语法,可能是因为我使用的是Python 3.5。 Because this seems to work fine on python 2.7. 因为这似乎在python 2.7上正常工作。 Would greatly appreciate help to resolve this error. 非常感谢您帮助解决此错误。

The problem is that the data contain NaN: 问题在于数据包含NaN:

Code: 码:

import pandas as pd
from numpy import nanmean
import numpy as np
from sklearn.linear_model import LogisticRegression

train = pd.read_csv("train.csv") 
test = pd.read_csv("test.csv")

test["Sex"][test["Sex"]=="male"]=0
test["Sex"][test["Sex"]=="female"]=1
test["Embarked"][test["Embarked"]=='S']=0
test["Embarked"][test["Embarked"]=='C']=1
test["Embarked"][test["Embarked"]=='Q']=2

train["Sex"][train["Sex"]=="male"]=0
train["Sex"][train["Sex"]=="female"]=1
train["Embarked"][train["Embarked"]=='S']=0
train["Embarked"][train["Embarked"]=='C']=1
train["Embarked"][train["Embarked"]=='Q']=2

nan_mean_age = nanmean(test.iloc[:,4])
test = test.fillna(value = nan_mean_age)

nan_mean_age2 = nanmean(train.iloc[:,5])
train = train.fillna(value = nan_mean_age2)

train_features=train[["Sex","Age","Pclass","Fare","Embarked"]].values
test_features=test[["Sex","Age","Pclass","Fare","Embarked"]].values

train_features = np.asarray(train_features)
test_features = np.asarray(test_features)

lg = LogisticRegression()
#define your target variable y and then fit
y_train = train.iloc[:,1]

lg.fit(train_features,y_train)
lg.predict(test_features)

result: 结果:

array([0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1,
       1, 1, 0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1, 0, 1, 1, 0, 1,
       1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1,
       1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0,
       1, 0, 0, 0], dtype=int64)

Something like this should work fine 这样的事情应该可以正常工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM