把上次建模校赛一个根据三围将女性分为四类(苹果型、梨形、报纸型、沙漏)的问题用逻辑回归实现了,包括从excel读取数据等一系列操作。

Excel的格式如下:假设有r列,则前r-1列为数据,最后一列为类别,类别需要从1开始1~k类

如上表所示,前10列是身高、胸围、臀围等数据(以及胸围和腰围、胸围和臀围的比值),最后一列1表示属于苹果型。

import tensorflow as tf
import os
import numpy
import xlrd XDATA = 0
YDATA = 0
one_hot_size = 0
M = 0 def readData():
global XDATA, YDATA, one_hot_size, M
workbook = xlrd.open_workbook('divdata.xlsx')
booksheet = workbook.sheet_by_index(0)
col = booksheet.ncols
row = booksheet.nrows
M = row
tempcol = []
for i in range(col - 1):
tempcol = tempcol + booksheet.col_values(i)
XDATA = numpy.array(tempcol).reshape(col - 1, row).T
one_hot_size = int(max(booksheet.col_values(col - 1)))
YDATA = numpy.zeros([row, one_hot_size])
for i in range(row):
YDATA[i, int(booksheet.cell_value(i, col - 1) - 1)] = 1 def getData(batch_size):
ran = numpy.random.randint(0, M - 1, [batch_size])
# print(ran)
return XDATA[ran], YDATA[ran] readData()
checkpoint_dir = 'modelsave/'
learning_rate = 0.0005
save_step = 100
total_step = 1000
batch_size = 1000
config = tf.ConfigProto()
config.gpu_options.allow_growth = True x = tf.placeholder(tf.float32, [None, 10], name='x')
y_data = tf.placeholder(tf.float32, [None, 4], name='data')
# y = tf.Variable(tf.zeros(4,1), dtype=tf.float32,name='y')
# w = tf.Variable(tf.zeros([10, 4], dtype=tf.float32))
w = tf.Variable(numpy.zeros([10, 4]),dtype=tf.float32)
# b = tf.Variable(tf.zeros([1, 4], dtype=tf.float32))
b = tf.Variable(numpy.zeros([1,4]),dtype=tf.float32)
y = tf.nn.softmax(tf.matmul(x, w) + b) loss = tf.reduce_mean(-tf.reduce_sum(y_data * tf.log(y), reduction_indices=1)) # 损失函数
optimizer = tf.train.GradientDescentOptimizer(learning_rate) # 选择梯度下降的方法
train_op = optimizer.minimize(loss) # 迭代的目标:最小化损失函数
sess = tf.InteractiveSession(config=config) # 设置按需使用GPU
saver = tf.train.Saver() # 用来存储训练结果 if not os.path.exists(checkpoint_dir):
os.mkdir(checkpoint_dir) #############################
# 读取并初始化:
ckpt = tf.train.get_checkpoint_state(checkpoint_dir)
if ckpt and ckpt.model_checkpoint_path:
saver.restore(sess, ckpt.model_checkpoint_path)
else:
sess.run(tf.global_variables_initializer())
############################## print(sess.run(b))
for i in range(total_step):
batch = getData(batch_size)
# print(batch[0])
# print(batch[1])
sess.run(train_op, feed_dict={x: batch[0], y_data: batch[1]})
if (i + 1) % save_step == 0:
print(i + 1, sess.run(w), sess.run(b))
saver.save(sess, checkpoint_dir + 'model.ckpt', global_step=i + 1) # 储存 writer = tf.summary.FileWriter('./my_graph', sess.graph) # tensorboard使用 writer.close()
sess.close() # 查看tensorboard的代码 在命令行输入:
# tensorboard --logdir=C:\Users\Rear82\PycharmProjects\MM_School_2018\my_graph

训练完成之后,使用以下代码读取并测试模拟:

import tensorflow as tf
import os
import numpy checkpoint_dir = 'modelsave/'
config = tf.ConfigProto()
config.gpu_options.allow_growth = True x = tf.placeholder(tf.float32, [None, 10], name='x')
w = tf.Variable(numpy.zeros([10, 4]),dtype=tf.float32)
b = tf.Variable(numpy.zeros([1,4]),dtype=tf.float32)
y = tf.nn.softmax(tf.matmul(x, w) + b) sess = tf.InteractiveSession(config=config) # 设置按需使用GPU
saver = tf.train.Saver() # 用来存储训练结果 if not os.path.exists(checkpoint_dir):
os.mkdir(checkpoint_dir) #############################
# 读取并初始化:
ckpt = tf.train.get_checkpoint_state(checkpoint_dir)
if ckpt and ckpt.model_checkpoint_path:
saver.restore(sess, ckpt.model_checkpoint_path)
else:
print("Can't find trained nn.")
############################## jdata = [[167,86,72,71.5,76.5,90.5,119.4444444,120.2797203,112.4183007,95.02762431]]
print(jdata)
print(sess.run(y,feed_dict={x:jdata})) sess.close()

训练了3000次后:

w:

b:

Logistic回归 逻辑回归 练习——以2018建模校赛为数据源的更多相关文章

  1. Coursera DeepLearning.ai Logistic Regression逻辑回归总结

    既<Machine Learning>课程后,Andrew Ng又推出了新一系列的课程<DeepLearning.ai>,注册了一下可以试听7天.之后每个月要$49,想想还是有 ...

  2. Logistic Regression逻辑回归

    参考自: http://blog.sina.com.cn/s/blog_74cf26810100ypzf.html http://blog.sina.com.cn/s/blog_64ecfc2f010 ...

  3. Logistic Regression(逻辑回归)(二)—深入理解

    (整理自AndrewNG的课件,转载请注明.整理者:华科小涛@http://www.cnblogs.com/hust-ghtao/) 上一篇讲解了Logistic Regression的基础知识,感觉 ...

  4. Logistic Regression(逻辑回归)

    分类是机器学习的一个基本问题, 基本原则就是将某个待分类的事情根据其不同特征划分为两类. Email: 垃圾邮件/正常邮件 肿瘤: 良性/恶性 蔬菜: 有机/普通 对于分类问题, 其结果 y∈{0,1 ...

  5. 机器学习简要笔记(五)——Logistic Regression(逻辑回归)

    1.Logistic回归的本质 逻辑回归是假设数据服从伯努利分布,通过极大似然函数的方法,运用梯度上升/下降法来求解参数,从而实现数据的二分类. 1.1.逻辑回归的基本假设 ①伯努利分布:以抛硬币为例 ...

  6. Deep Learning 学习笔记(4):Logistic Regression 逻辑回归

    逻辑回归主要用于解决分类问题,在现实中有更多的运用, 正常邮件or垃圾邮件 车or行人 涨价or不涨价 用我们EE的例子就是: 高电平or低电平 同时逻辑回归也是后面神经网络到深度学习的基础. (原来 ...

  7. 【原】Coursera—Andrew Ng机器学习—Week 3 习题—Logistic Regression 逻辑回归

    课上习题 [1]线性回归 Answer: D A 特征缩放不起作用,B for all 不对,C zero error不对 [2]概率 Answer:A [3]预测图形 Answer:A 5 - x1 ...

  8. HDU 6312 - Game - [博弈][杭电2018多校赛2]

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6312 Problem Description Alice and Bob are playing a ...

  9. HDU 6318 - Swaps and Inversions - [离散化+树状数组求逆序数][杭电2018多校赛2]

    题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=6318 Problem Description Long long ago, there was an ...

随机推荐

  1. 系统构架篇之基于SSDB的二级缓存

    1.什么是ssdb 你可以把ssdb理解成redis.不同之处在于redis缓存的数据是在内存中的,所能缓存的数据大小受内存大小的限制,一般不适合缓存大量的数据.而ssdb将数据保存在磁盘中,数据量大 ...

  2. PHP导入Excel表

    初始化参数,先导入PHPExcel类 /** * 读出Excel表格数据 * @param $filename 文件名 * @param string $encode 编码格式 * @return a ...

  3. STM32F4寄存器编写跑马灯例程

    最近由于在学习STM32看到别人用寄存器编程控制跑马灯,于是自己也想试一试.可是试了好久终究弄不出来.回头看了下库函数的调用关系才搞明白.首先通过查看GPIOA的设置函数发现设置如下: void GP ...

  4. coinmarketcap.com爬虫

    coinmarketcap.com爬虫 写的真是蛋疼 # -*- coding:utf-8 -*- import requests from lxml import etree headers = { ...

  5. LIFO栈 ADT接口 链表实现

    LIFO 链栈结构 typedef int ElemType; struct node{ ElemType data; struct node* next; }; typedef struct nod ...

  6. Go语言中结构体的使用-第1部分结构体

    1 概述 结构体是由成员构成的复合类型.Go 语言使用结构体和结构体成员来描述真实世界的实体和实体对应的各种属性.结构体成员,也可称之为成员变量,字段,属性.属性要满足唯一性.结构体的概念在软件工程上 ...

  7. 20155313 2016-2017-2 《Java程序设计》第二周学习总结

    20155313 2016-2017-2 <Java程序设计>第二周学习总结 教材学习内容总结 1.1 基本类型 整数:可细分为short整数(占2字节).int整数(占4字节)与long ...

  8. SupperSocket深入浅出(一)

    花了几天时间了解了SupperSocket工作原理,各各类之间的工作关系.SupperSocket大部资料网上都有,但写的都不适合初学者. 今天花点时间写下这几天的学习成果,一方面是为了将来更好的回顾 ...

  9. cv::Mat转换QImage

    cvtColor(img, img, CV_BGR2RGB); QImage image((uchar*)img.data,img.cols,img.rows,QImage::Format_RGB88 ...

  10. 一个奇怪的JS函数

    今天在分析一个jQuery插件源码的时候,发现了一个奇怪的函数. 这个函数的目的是为数字补零,如传入7,输出07,传入12输出12.由于是对时间补零,只截取后两位. // add leading ze ...