Homework1-classification model on Titanic survival data(6.9update)

本文记录了一位学生基于Kaggle Titanic数据集使用Python实现逻辑回归模型的过程,包括批量和随机梯度下降的实现,数据预处理,特征工程,以及在Pycharm中提高开发效率的探讨。
摘要由CSDN通过智能技术生成

昨天B老师给我布置了第一个作业,基于kaggle上经典的titanic生存数据做分类模型。

要求

data:https://www.kaggle.com/c/titanic
要求:
1. 用python脚本实现一个简单的逻辑回归,模型学习过程需要自己实现。
2. 记录模型学习的过程,绘制学习曲线、准确率曲线
3. 可以参考别人的作业

5.26

  1. 了解了一下线性回归的批量梯度下降:
    https://www.cnblogs.com/wallacup/p/6017378.html
  2. 学习一下python常用数据统计包:numpy/pandas
    https://morvanzhou.github.io

6.3

  1. 利用周末两天的时间封闭写作业
  2. 结果:
    1. 用网上的case数据集实现了逻辑回归的批量/随机梯度下降求解函数定义
    2. 利用pandas、numpy包对Titanic的training set进行描述性统计(统计量计算、scatter plot)、数据预处理(缺失值处理、特征工程)
    3. 没有找到将pandas特征处理过后的数据集转换成自建函数input数据格式(array/list)的方法,因此没有将处理后的数据集放到自定义函数中实现模型计算。Simon:【方法1】dataframe直接转input list;【方法2】dataframe转csv转input
    4. cross validation 和 learning curve 还未开始写
  3. 问题:
    1. 花了较多时间在理解和推导逻辑回归的梯度下降的vectorization(向量化,看书时能看懂,但编程时发现有特殊处理。同理,其他算法是否可以有显示的向量化结果,不然求和求导会爆炸?) Simon:向量化过程是基础能力,处理的模型多了自然能一眼看出向量化的方法,尤其是运用TensorFlow的过程中,都需要向量化处理。
    2. 花了较多时间在学习pandas、numpy的数据处理函数(矩阵运算、基于dataframe的数据透视和处理),处理数据特性(边查边看边学边写)
    3. 花了较多时间适应pycharm的开发和调试环境,不知道自己的调试方式是否正确,开发效率较低(在R中每次运行的结果会保存,在pycharm中每次运行不生成特定的解释器,无法继续基于上次开发的结果进行编译,每次都要重新来= =)Simon:可以在ipython中的python interpreter中直接编写,通过history命令整理代码。
  4. Action:请教一下专业的算法同学,看一下实际数据处理过程一般是以哪种数据格式进行存储(数据预处理、建模),如何在pycharm中提高开发效率?Simon:要有这种思维:将数据预处理/特征工程 和 建模 的过程分开对待。数据预处理过程如果数据量小可以在pandas中实现,如果数据量大,在线上通过sql实现。而建模过程和数据预处理是独立的。

贴一下这两天的劳动成果

logistics regression的gd、sgd


from numpy import *
import matplotlib.pyplot as plt
import time

def loadtrainingata():
    train_x = []
    train_y = []
    fileIn = open(r'D:\ML\h1_Tianic\testset.txt')
    for line in fileIn.readlines():
        lineArr = line.strip().split()
        train_x.append([1.0, float(lineArr[0]), float(lineArr[1])])
        train_y.append(float(lineArr[2]))
    return mat(train_x), mat(train_y).transpose()

#Sigmod Function
def sigmoid(inX):
    return 1.0 / (1 + exp(-inX))

#Logistic Regression
def trainLogicReg(train_x, train_y, opts):
    # calculate training time
    startTime = time.time()
    # train_x= mat(train_x)

    numSamples, numFeatures = shape(train_x)
    alpha = opts['alpha'];
    maxIter = opts['maxIter']
    weights = ones((numFeatures, 1))  #initialzing weights

    # optimize through gradient descent algorilthm
    for k in range(maxIter):
        if opts['optimizeType'] == 'GD':  # gradient descent
            h = sigmoid(train_x * weights)
            error = train_y - h
            weights = weights + alpha * train_x.transpose() * error
        elif opts['optimizeType'] == 'SGD':  # stochastic gradient descent
            for i in range(numSamples):
                h = sigmoid(train_x[i, :] * weights)
                error = train_y[i, 0] - h
                weights = weights + alpha * train_x[i, :].transpose() * error
        else:
            raise NameError('Not support optimize method type!')

    print 'Congratulations, training complete! Took %fs!' % (time.time() - startTime)
    # print weights
    return weights

# test your trained Logistic Regression model given test set
def testLogicReg(weights, test_x, test_y):
    numSamples, numFeatures = shape(test_x)
    matchCount = 0
    for i in xrange(numSamples):  #xrange for uncertain hugenum of testdata
        predict = sigmoid(test_x[i, :] * weights)[0, 0] > 0.5
        print test_x[i,:], sigmoid(test_x[i, :] * weights), test_y[i,0]
        if predict == bool(test_y[i, 0]):
            matchCount += 1
    accuracy = float(matchCount) / numSamples
    print accuracy
    return accuracy

## step 1: load data
print "step 1: load data..."
train_x, train_y = loadtrainingata()
test_x = train_x
test_y = train_y

print train_x
print train_y

## step 2: training...
print "step 2: training..."
opts = {'alpha': 0.01, 'maxIter': 20, 'optimizeType': 'GD'}
optimalWeights = trainLogicReg(train_x, train_y, opts)

## step 3: testing
print "step 3: testing..."
testLogicReg(optimalWeights, test_x, test_y)

基于pandas、numpy处理Titanic的traing set

#Homework topc:Titanic: Machine Learning from Disaster
#Description:https://www.kaggle.com/c/titanic#evaluation

#Date:June.2nd 2018
#Auther:tinghui

'''
1、特征分析:是否遇难和其中的某些特征没有可解释性的直接关系。根据电影情节,当沉船事故发生时,是否survive最关键的因素应该是:
①道德因素下优先上救生船(老人、妇女、幼童),该因素可通过training set中的age、sex刻画。
②非道德因素下优先救生船(有钱人、开救生艇的人/提前预知沉船事故发生上船的人),该因素可通过收入、职业直观体现,但training set中无相关特征指标表述,可通过pcclass、fare这两个与收入水平正相关特征进行体现(二者是否共线性?)
③未上救生船但坚持到获救(会游泳、有体力、有毅力、找到可漂浮的载体),该因素可通过职业、兴趣爱好、年龄、性别来刻画,但training set中无相关特征表述,可通过age=青壮年、sex=男性体现(也许不同embarked的人水性差异不同,可计算相关性看看)
④逃离时间充裕且未被船直接砸死(座位靠近逃生点),该因素可通过座位体现,但traning set中只有cabin信息,cabin未必和座位顺序有直接相关。

综上所述,初步推测对passenger是否survive
①影响最大的因素是:
Sex:女性有优先上救生船机会
Age:老人、小孩有优先上救生船机会,年轻人体力好可坚持到救生船
②其次是:
Pclass/Fare/Cabin:仓位信息,仓位越高说明该passenger越有钱,越容易获得优先上救生船的机会
③再次是:
Embarked:上船的位置,可能某些地方的人就是很擅长游泳
④再次是:
SibSp、Parch:可能有配偶、亲戚的人,能有更多的能力去争抢救生船的位置(人多力量大)
⑤最后是:
Name、Ticket:可能没什么用

2、数据分析
①分类变量:Pclass、Sex、SibSp、Parch、Ticket、Cabin、Embarked
②数值型变量:Age、Fare
③缺数情况:Age少量缺失、Cabin大量缺失

3、特征工程
①衍生变量

4、模型拟合

5、learning curve效果评估

6、模型优化

'''

'''
Refference:
描述统计
数据透视表:https://blog.csdn.net/lll1528238733/article/details/75111428
titanic:https://blog.csdn.net/guoxinian/article/details/73740746

逻辑回归
https://blog.csdn.net/sun_shengyun/article/details/53788230
https://blog.csdn.net/csqazwsxedc/article/details/69690655
https://blog.csdn.net/zouxy09/article/details/20319673
https://blog.csdn.net/zj360202/article/details/78688070
http://blog.csdn.net/xiaoxiangzi222/article/details/55097570  (花了很多时间推导 vectorization) 

三种随机梯度下降
https://blog.csdn.net/hdg34jk/article/details/78864070

数据可视化-scatter
https://blog.csdn.net/u013634684/article/details/49646311

'''
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import csv
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt


# csv_reader = csv.reader(open(r'D:\ML\h1_Tianic\train.csv'))
# Load the data as pd.DataFrame
train_df = pd.read_csv(r'D:\ML\h1_Tianic\train.csv', header=0)
test_df = pd.read_csv(r'D:\ML\h1_Tianic\train.csv', header=0)

#dataframe维度太多,显示省略号
pd.set_option('display.max_rows', None)  # 设置显示最大行
pd.set_option('display.max_columns', None)  # 设置显示最大行
np.set_printoptions(threshold='nan')

#描述统计分析
# print train_df
# print train_df.head()
# print train_df.describe()

# #统计频数分布
# # 构造计算任意两个col频数分布的函数calcolfreq
# train_col = ['Pclass','Sex','SibSp','Parch','Embarked']
# for col in train_col:
#     #单个col
#     # print col
#     # print train_df[col].value_counts()
#     #交叉
#     print col
#     print pd.crosstab(train_df['Survived'],train_df[col])

'''
   根据频数分布,如何统计频率?
   Pclass:class=1的乘客的生存率比class=3的高,说明class越高越有钱的人并非越有钱
   Sex:sex=female的乘客的生存率显著高于sex=male,说明女性更容易生存,尊老爱幼
   Embarked:embarked=C的乘客生存率显著高于embarked=Q/S,说明从C市上船的用户更容易生存
'''

# 相关性检验
# # 检验fare/pclass/cabin之间的相关性
# # # 构造检验任意两个col相关系数的函数calcolcorr
# def calcolcorr(dfset,collist):
#     if len(collist)<=1:
#         print 'Please input at least two columns.'
#     else:
#         for col1 in collist:
#             for col2 in collist[collist.index(col1)+1:]:
#                 print dfset.loc[:,[col1,col2]].corr(method='pearson')
#                 x=dfset.loc[:,[col1]]
#                 y=dfset.loc[:,[col2]]
#                 plt.xlabel(col1)
#                 plt.ylabel(col2)
#                 plt.scatter(x, y)
#                 plt.show()
# train_corr_col = ['Pclass','Fare','Age']
# calcolcorr(train_df,train_corr_col)

#吊炸天,还有透视表的功能!
# print pd.pivot_table(train_df, index=['Pclass','Sex'], values=['Fare'], columns=['Embarked'], aggfunc=[np.mean,np.max,np.min], fill_value=0, margins=True)
# print pd.pivot_table(train_df, index=['Pclass'], values=['Fare'],  aggfunc=[np.mean,np.max,np.min])
'''
    根据相关系数和散点图结果,知除Pclass和Fare之外,其他变量Age、Fare之间无明显的相关关系
    根据Pivottable结果显示,Pclass=1和Pclss=2/3的价格间差异最大,推测Pclass是头等舱
'''

#数据预处理
#剔除Name、Ticket、Cabin
dropcol = ['PassengerId','Name','Ticket','Cabin']
train_df.drop(dropcol, axis=1, inplace=True)
test_df.drop(dropcol, axis=1, inplace=True)

#剔除空值
train_x = train_df.dropna()
test_x = test_df.dropna()
# print train_df

#生成哑变量
#trainset
dummies_Pclass = pd.get_dummies(train_x['Pclass'], prefix= 'Pclass')
dummies_Sex = pd.get_dummies(train_x['Sex'], prefix= 'Sex')
dummies_Embarked = pd.get_dummies(train_x['Embarked'], prefix= 'Embarked')
train_df = pd.concat([train_x, dummies_Embarked, dummies_Sex, dummies_Pclass], axis=1)
train_df.drop(['Pclass','Sex','Embarked'], axis=1, inplace=True)
# print train_df
#
# #testset
# dummies_Pclass = pd.get_dummies(test_x['Pclass'], prefix= 'Pclass')
# dummies_Sex = pd.get_dummies(test_x['Sex'], prefix= 'Sex')
# dummies_Embarked = pd.get_dummies(test_x['Embarked'], prefix= 'Embarked')
# test_df = pd.concat([test_x, dummies_Embarked, dummies_Sex, dummies_Pclass], axis=1)
# test_df.drop(['Pclass','Sex','Embarked'], axis=1, inplace=True)
#
# #用正则提取对应属性,并转换成list
train_df = train_df.filter(regex='Survived|Age|SibSp|Parch|Fare|Embarked_.*|Sex_.*|Pclass_.*')
print train_df.loc[100].values[0]
# # print train_df.loc[100].values
# print train_df
train_x=[]
train_y=[]
for indexs in train_df.index:
    # train_x.append([1.0, train_df.loc[indexs].values[1:]])
    train_y.append(float(train_df.loc[indexs].values[0]))
# print train_x
print train_y
#妈的,怎么把dataframe里的字段抽出来变成list的list!!
'''
构造Logistic Regression
'''

逻辑回归梯度下降向量化推导

这里写图片描述
这里写图片描述
这里写图片描述

6.6

今天和B老师对了一下作业,有新的任务

特征工程

  • 在逻辑回归中加入 kernel函数 将线性模型变成非线性,观察模型优化结果
  • 将连续特征变成离散化特征,使特征高维
  • 学习特征离散化,特征交叉:https://blog.csdn.net/lujiandong1/article/details/52412123
  • 学习广告业务的ctr预估模型,了解 PAI-parameter-server的用法

submit

由于在特征处理时对部分特征为空的乘客进行了过滤,testdata不满足418 row,无法submit,需要调整。(不能随意删除样本)

6.8

Submit了第一份predicting result,准确率有待提高!
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
目标检测(Object Detection)是计算机视觉领域的一个核心问题,其主要任务是找出图像中所有感兴趣的目标(物体),并确定它们的类别和位置。以下是对目标检测的详细阐述: 一、基本概念 目标检测的任务是解决“在哪里?是什么?”的问题,即定位出图像中目标的位置并识别出目标的类别。由于各类物体具有不同的外观、形状和姿态,加上成像时光照、遮挡等因素的干扰,目标检测一直是计算机视觉领域最具挑战性的任务之一。 二、核心问题 目标检测涉及以下几个核心问题: 分类问题:判断图像中的目标属于哪个类别。 定位问题:确定目标在图像中的具体位置。 大小问题:目标可能具有不同的大小。 形状问题:目标可能具有不同的形状。 三、算法分类 基于深度学习的目标检测算法主要分为两大类: Two-stage算法:先进行区域生成(Region Proposal),生成有可能包含待检物体的预选框(Region Proposal),再通过卷积神经网络进行样本分类。常见的Two-stage算法包括R-CNN、Fast R-CNN、Faster R-CNN等。 One-stage算法:不用生成区域提议,直接在网络中提取特征来预测物体分类和位置。常见的One-stage算法包括YOLO系列(YOLOv1、YOLOv2、YOLOv3、YOLOv4、YOLOv5等)、SSD和RetinaNet等。 四、算法原理 以YOLO系列为例,YOLO将目标检测视为回归问题,将输入图像一次性划分为多个区域,直接在输出层预测边界框和类别概率。YOLO采用卷积网络来提取特征,使用全连接层来得到预测值。其网络结构通常包含多个卷积层和全连接层,通过卷积层提取图像特征,通过全连接层输出预测结果。 五、应用领域 目标检测技术已经广泛应用于各个领域,为人们的生活带来了极大的便利。以下是一些主要的应用领域: 安全监控:在商场、银行
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值