【机器学习】Random Forest(随机森林)入门和实战(一)先写个项目

准备条件
  • seaborn: 一个可视化工具,不会用参见:数据可视化工具seaborn
  • matplotlib.pyplot: 也是一个可视化工具
  • sklearn
  • pandas
  • numpy
  • jupyter notebook
实践项目
  • 项目地址
    Kaggle上面的一个项目:digit-recognizer
  • 项目描述
    简单说下就是train.csv训练数据里面是42000条手写数字图片的数据。
    • train.csv一共42000行*785列
    • 每个数字图片包含28*28像素点,即 一个图片784个像素点,每个像素点的明暗程度用0-255之间的数字表示,数字越高,表示越暗
    • 785列数据中,第一列就是识别正确的数字,取名为lable,后面784列即为每个像素点明暗值
    • test.csv相比于train.csv就是少了lable
  • 项目思路
    使用随机森林算法,定义为100tree, 训练模型时,用train.csv的前2/3行数据(28000行)作为训练数据,后1/3行数据(14000行)作为测试数据。
  • 项目代码
    SmileLikeYe-RandomForest
#!/usr/bin/env python
# coding=utf8

import sys
reload(sys)
sys.setdefaultencoding('utf8')

'''
Competition URL: https://www.kaggle.com/c/digit-recognizer
Solution:  Random Forest
'''


# 引入需要的包包
# 数据处理的常用包包
import numpy as np
import pandas as pd

# 随机森林的包包
import sklearn as skl
from sklearn.ensemble import RandomForestClassifier

# 画图的包包
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(color_codes=True)

# 读取数据(请先去 https://www.kaggle.com/c/digit-recognizer/data 上下载数据)
# 读取成DataFrame的数据
train_df = pd.read_csv('train.csv')
# 将DataFrame的数据转换成Array
train_data = train_df.values

test_df = pd.read_csv('test.csv')
test_data = test_df.values

print train_df.head()
print train_data

# 画图
plt.figure(figsize=(12,8))
sns.countplot(x='label', data=train_df)
plt.title('Distribution of Numbers')
plt.xlabel('Numbers');

# 2/3的train_data作为训练数据,1/3的train_data作为测试数据来训练模型
num_features = train_data.shape[0] # 拿到train_data的行数,也就是所有数据的个数作为特征值
print("Number of all features: \t\t", num_features)
split = int(num_features * 2/3) # 这里是取2/3行也就是前28000行作为训练 后1/3也就是14000作为测试

train = train_data[:split] # 取出前28000行作为训练数据
test = train_data[split:] # 取出后14000行作为测试数据

print("Number of features used for training: \t", len(train),
      "\nNumber of features used for testing: \t", len(test))

# 开始使用随机森林分类器
clf = RandomForestClassifier(n_estimators=100) # 定义决策树的个数为100

# 开始训练,训练的X数据格式为[[]],训练的y值为[]也就是经过ravel后的数据
# 如果你问我ravel()的作用是什么,就是不管什么数据格式的数据都转成一个一维的array,这样每个元素都是一个平等且顺序的位置
model = clf.fit(train[:,1:], train[:,0].ravel())

# 然后预测
output = model.predict(test[:,1:])

# 计算准确度
acc = np.mean(output == test[:,0].ravel()) *100
print("The accuracy of the pure RandomForest classifier is: \t", acc, "%")

# 利用
clf = RandomForestClassifier(n_estimators=100) # 100 trees

# 用全部训练数据来做训练
target = train_data[:,0].ravel()
train = train_data[:,1:]
model = clf.fit(train, target)


# 用测试集数据来预测最终结果
output = model.predict(test_data)
print output

# 输出预测结果
pd.DataFrame({"ImageId": range(1, len(output)+1), "Label": output}).to_csv('out.csv', index=False, header=True)

最后 提交上去的准确路为96.793% 那个运用这个不知名国外同学排到了前五。

参考资料

我的相关文章

  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值