iris数据集demo
iris数据集demo
KYO4321 发表于11个月前
iris数据集demo
• 发表于 11个月前
• 阅读 12
• 收藏 0
• 评论 0
``````#!/usr/bin/env python
##K-means操作
import numpy as np
import pandas as pd
from sklearn import cluster #机器学习库
np.random.seed(1024) #设置随机数种子

print(iris.shape) #输出数据维度

print(iris.describe())
print(iris.describe().T)

irisK3 = cluster.KMeans(n_clusters=3, random_state=1)
irisFeatures = iris.ix[:, 1:4]
irisK3.fit(irisFeatures)

#############
##K-means:Method two
from sklearn import metrics
from sklearn.metrics import pairwise_distances
from sklearn import datasets
X = dataset.data
y = dataset.target

import numpy as np
from sklearn.cluster import KMeans
kmeans_model = KMeans(n_clusters=3, random_state=1).fit(X)
labels = kmeans_model.labels_
metrics.silhouette_score(X, labels, metric='euclidean')
#####################

#############################################
##决策树操作
from sklearn import cross_validation
from sklearn import tree
target = iris.target #目标变量
data = iris.data[:, 1:4] #自变量

train_data, test_data, train_target, test_target = cross_validation.train_test_split(data,
target, test_size = 0.24, random_state = 0) #分成训练集、测试集（占0.24）

clf = tree.DecisionTreeClassifier(criterion='gini', max_depth=6,
min_samples_split=5) #CART算法

clf_fit = clf.fit(train_data, train_target) #开始fit
#print clf_fit
train_est=clf.predict(train_data) #预测训练集
test_est=clf.predict(test_data) #预测测试集

sum=0
for i in range(36):
if test_est[i] == test_target[i]:
sum = sum + 1
print('test_accuracy=',"%.2f%%"%(sum*1.0/36*100)) #测试集预测正确率

sum=0
for i in range(114):
if train_est[i] == train_target[i]:
sum = sum + 1
print('tarin_accuracy=',"%.2f%%"%(sum*1.0/114*100)) #训练集预测正确率

#############
from sklearn.cross_validation import cross_val_score
from sklearn.tree import DecisionTreeClassifier
clf = DecisionTreeClassifier(random_state=0)