我刚刚完成了逻辑回归。数据可以从下面的链接下载:请点击此链接下载数据
以下是逻辑回归的代码。
from sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScalerfrom sklearn.metrics import roc_auc_scoreimport pandas as pdscaler = StandardScaler()data = pd.read_csv('data.csv')dataX = data.drop('outcome',axis =1).values.astype(float)X = scaler.fit_transform(dataX)dataY = data[['outcome']]Y = dataY.valuesX_train,X_test,y_train,y_test = train_test_split (X,Y,test_size = 0.25, random_state = 33)lr = LogisticRegression()lr.fit(X_train,y_train)# Predict the probability of the testing samples to belong to 0 or 1 classpredicted_probs = lr.predict_proba(X_test)print(predicted_probs[0:3])print(lr.coef_)
我可以打印逻辑回归的系数,并且可以计算事件发生的概率为1或0。
当我使用这些系数编写一个Python函数并计算发生1的概率时,与使用以下方法得到的结果不一致:lr.predict_proba(X_test)
我编写的函数如下:
def xG(bodyPart,shotQuality,defPressure,numDefPlayers,numAttPlayers,shotdist,angle,chanceRating,type):coeff = [0.09786083,2.30523761, -0.05875112,0.07905136, -0.1663424 ,-0.73930942,-0.10385882,0.98845481,0.13175622]return (coeff[0]*bodyPart+ coeff[1]*shotQuality+coeff[2]*defPressure+coeff[3]*numDefPlayers+coeff[4]*numAttPlayers+coeff[5]*shotdist+ coeff[6]*angle+coeff[7]*chanceRating+coeff[8]*type)
我得到了奇怪的结果。我知道函数计算中出了问题。
由于我对机器学习和统计学是新手,我可以寻求您的建议吗?
回答:
我想你在xG
中漏掉了intercept_
。你可以从lr.intercept_
中获取它,并在最终公式中进行求和:
return 1/(1+e**(-(intercept + coeff[0]*bodyPart+ coeff[1]*shotQuality+coeff[2]*defPressure+coeff[3]*numDefPlayers+coeff[4]*numAttPlayers+coeff[5]*shotdist+ coeff[6]*angle+coeff[7]*chanceRating+coeff[8]*type))