您的位置:首页 > 其它

机器学习--Logistic Regression(scikit-learn_ 预测疝气病症病马死亡率问题)

2017-12-03 21:21 302 查看
据说,心情不好的时候,整理东西可以让好心情回归,那么同理,懒散得想要沉沦时候,总结知识可以召回学习的神龙。

学习回顾:

认识sklearn:scikit-learn,Python库之一,Scipy(Scientific Python,Python科学计算)工具集的一部分,该库整合了多种机器学习算法,因此可用scikit-learn库实现机器学习,可用来预测模型的创建和验证。

scikit-learn的所有模型都被称作有监督估计器,训练估计器要用到fit(x,y)函数,其中x指观察到的特征,y指的是目标。估计器经过训练后,可以预测任何标签未知的新数据x的y指,其中预测是通过predict(x)函数完成

练习机器学习算法,没有现成数据的可以用Iris数据集

1、认识iris数据集:

#导入
from sklearn import datasets
#鸢尾花卉数据集的所有数据和元数据(注1)都加载到iris变量中
iris = datasets.load_iris()


注1:元数据

数据是指实际数据,而元数据指描述数据的数据,描述一个数据特征的系统数据,如访问权限、存储位置、文件拥有者等……

#使用iris变量的data属性,查看所含数据
iris.data


#150个 元素,每个元素四个数值
Out[3]:
array([[ 5.1,  3.5,  1.4,  0.2],
[ 4.9,  3. ,  1.4,  0.2],
[ 4.7,  3.2,  1.3,  0.2],
[ 4.6,  3.1,  1.5,  0.2],
[ 5. ,  3.6,  1.4,  0.2],
[ 5.4,  3.9,  1.7,  0.4],
[ 4.6,  3.4,  1.4,  0.3],
[ 5. ,  3.4,  1.5,  0.2],
[ 4.4,  2.9,  1.4,  0.2],
[ 4.9,  3.1,  1.5,  0.1],
[ 5.4,  3.7,  1.5,  0.2],
[ 4.8,  3.4,  1.6,  0.2],
[ 4.8,  3. ,  1.4,  0.1]
......
])


#查看花卉种类
iris.target
Out[4]:
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])


#查看花卉类别
iris.target_names
Out[5]:
array(['setosa', 'versicolor', 'virginica'],
dtype='<U10')
#0代表Setosa  1代表Versicolour   2代表 Virginica


#散点图
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from sklearn import datasets

iris = datasets.load_iris()
x = iris.data[:,3]#萼片长度(数据集第四列元素赋值给变量x)
y = iris.data[:,2]#宽度
#可更改查看区别,当长度为第四列,宽度为第三列时效果最明显

#花卉类别
target = iris.target

#计算散点图x轴最小值,最大值
x_min,x_max = x.min() - 0.5,x.max()+0.5
y_min,y_max = y.min() - 0.5,y.max()+0.5

plt.figure()
plt.title("Iris dataset classification",size = 15)
plt.scatter(x,y,c=target)
plt.xlable("length")
plt.ylabel("width")
plt.xlim(x_min,x_max)
plt.ylim(y_min,y_max)
plt.xticks(())
plt.yticks(())
plt.plot()

#保存为png图片
plt.savefig('iris.png')

plt.show()




更多练习可参考:

http://blog.csdn.net/sileixinhua/article/details/70477303

2、scikit-learn中的metrics以及logistic预测疝气病症病马死亡率问题

(参考《机器学习实战》)

from sklearn import linear_model
from sklearn import metrics
from sklearn.metrics import accuracy_score

#训练集
frtrain = open('horseColicTraining.txt')
train_data = []
train_target = []
for line in frtrain.readlines():
lineArr = line.strip().split('\t')
train_data.append([float(inst) for inst in lineArr[:-1]])
train_target.append(float(lineArr[-1]))

#测试集
frtest = open('horseColicTest.txt')
test_data = []
test_target = []
for line in frtest.readlines():
lineArr = line.strip().split('\t')
test_data.append([float(inst) for inst in lineArr[:-1]])
test_target.append(float(lineArr[-1]))

#利用logistic回归模型训练数据
clf = linear_model.LogisticRegression()
clf = clf.fit(train_data,train_target)

predicted=clf.predict(test_data)
expected=test_target
print(metrics.classification_report(expected, predicted))
print(metrics.confusion_matrix(expected, predicted))
print('The accuracy of logistic is :',accuracy_score(test_target,predicted))


precision    recall  f1-score   support

0.0       0.54      0.65      0.59        20
1.0       0.84      0.77      0.80        47

avg / total       0.75      0.73      0.74        67

[[13  7]
[11 36]]
The accuracy of logistic is : 0.731343283582


2.2、函数实现

可以发现测试集和训练集的操作雷同,所以用函数实现,更方便

from sklearn import linear_model
from sklearn import metrics
from sklearn.metrics import accuracy_score

def loadData(filename):
fr = open(filename).readlines()
data = []
target = []
for line in fr:
lineArr = line.strip().split('\t')
data.append([float(inst) for inst in lineArr[:-1]])
target.append(float(lineArr[-1]))
return data,target

train_data,train_target = loadData('horseColicTraining.txt')
test_data,test_target = loadData('horseColicTest.txt')

clf = linear_model.LogisticRegression()
clf = clf.fit(train_data,train_target)

predicted=clf.predict(test_data)
expected=test_target
print(metrics.classification_report(expected, predicted))
print(metrics.confusion_matrix(expected, predicted))
print('The accuracy of logistic is :',accuracy_score(test_target,predicted))


结果相同:

precision    recall  f1-score   support

0.0       0.54      0.65      0.59        20
1.0       0.84      0.77      0.80        47

avg / total       0.75      0.73      0.74        67

[[13  7]
[11 36]]
The accuracy of logistic is : 0.731343283582


错误回顾:

问题1:

TypeError: Cannot cast array data from dtype('float64') to dtype('<U32') according to the rule 'safe'


解决思路:

result = [float(i) for i in list]

问题2:

'range' object doesn't support item deletion


原因:

python3.x range返回的是range对象,不返回数组对象

解决思路:

data = range(m) 改为 data = list(range(m))

问题3:

Could not convert string to float:’young’


原因:

fit函数不支持字符串形式

思路:

运用pandas库的数据类型进行转
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐