详解用TensorFlow实现逻辑回归算法

本文将实现逻辑回归算法,预测低出生体重的概率。

# Logistic Regression
# 逻辑回归
#----------------------------------
#
# This function shows how to use TensorFlow to
# solve logistic regression.
# y = sigmoid(Ax + b)
#
# We will use the low birth weight data, specifically:
# y = 0 or 1 = low birth weight
# x = demographic and medical history data

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import requests
from tensorflow.python.framework import ops
import os.path
import csv

ops.reset_default_graph()

# Create graph
sess = tf.Session()

###
# Obtain and prepare data for modeling
###

# name of data file
birth_weight_file = 'birth_weight.csv'

# download data and create data file if file does not exist in current directory
if not os.path.exists(birth_weight_file):
  birthdata_url = 'https://github.com/nfmcclure/tensorflow_cookbook/raw/master/01_Introduction/07_Working_with_Data_Sources/birthweight_data/birthweight.dat'
  birth_file = requests.get(birthdata_url)
  birth_data = birth_file.text.split('\r\n')
  birth_header = birth_data[0].split('\t')
  birth_data = [[float(x) for x in y.split('\t') if len(x)>=1] for y in birth_data[1:] if len(y)>=1]
  with open(birth_weight_file, "w") as f:
    writer = csv.writer(f)
    writer.writerow(birth_header)
    writer.writerows(birth_data)
    f.close()

# read birth weight data into memory
birth_data = []
with open(birth_weight_file, newline='') as csvfile:
   csv_reader = csv.reader(csvfile)
   birth_header = next(csv_reader)
   for row in csv_reader:
     birth_data.append(row)

birth_data = [[float(x) for x in row] for row in birth_data]

# Pull out target variable
y_vals = np.array([x[0] for x in birth_data])
# Pull out predictor variables (not id, not target, and not birthweight)
x_vals = np.array([x[1:8] for x in birth_data])

# set for reproducible results
seed = 99
np.random.seed(seed)
tf.set_random_seed(seed)

# Split data into train/test = 80%/20%
# 分割数据集为测试集和训练集
train_indices = np.random.choice(len(x_vals), round(len(x_vals)*0.8), replace=False)
test_indices = np.array(list(set(range(len(x_vals))) - set(train_indices)))
x_vals_train = x_vals[train_indices]
x_vals_test = x_vals[test_indices]
y_vals_train = y_vals[train_indices]
y_vals_test = y_vals[test_indices]

# Normalize by column (min-max norm)
# 将所有特征缩放到0和1区间(min-max缩放),逻辑回归收敛的效果更好
# 归一化特征
def normalize_cols(m):
  col_max = m.max(axis=0)
  col_min = m.min(axis=0)
  return (m-col_min) / (col_max - col_min)

x_vals_train = np.nan_to_num(normalize_cols(x_vals_train))
x_vals_test = np.nan_to_num(normalize_cols(x_vals_test))

###
# Define Tensorflow computational graph¶
###

# Declare batch size
batch_size = 25

# Initialize placeholders
x_data = tf.placeholder(shape=[None, 7], dtype=tf.float32)
y_target = tf.placeholder(shape=[None, 1], dtype=tf.float32)

# Create variables for linear regression
A = tf.Variable(tf.random_normal(shape=[7,1]))
b = tf.Variable(tf.random_normal(shape=[1,1]))

# Declare model operations
model_output = tf.add(tf.matmul(x_data, A), b)

# Declare loss function (Cross Entropy loss)
loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=model_output, labels=y_target))

# Declare optimizer
my_opt = tf.train.GradientDescentOptimizer(0.01)
train_step = my_opt.minimize(loss)

###
# Train model
###

# Initialize variables
init = tf.global_variables_initializer()
sess.run(init)

# Actual Prediction
# 除记录损失函数外,也需要记录分类器在训练集和测试集上的准确度。
# 所以创建一个返回准确度的预测函数
prediction = tf.round(tf.sigmoid(model_output))
predictions_correct = tf.cast(tf.equal(prediction, y_target), tf.float32)
accuracy = tf.reduce_mean(predictions_correct)

# Training loop
# 开始遍历迭代训练,记录损失值和准确度
loss_vec = []
train_acc = []
test_acc = []
for i in range(1500):
  rand_index = np.random.choice(len(x_vals_train), size=batch_size)
  rand_x = x_vals_train[rand_index]
  rand_y = np.transpose([y_vals_train[rand_index]])
  sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y})

  temp_loss = sess.run(loss, feed_dict={x_data: rand_x, y_target: rand_y})
  loss_vec.append(temp_loss)
  temp_acc_train = sess.run(accuracy, feed_dict={x_data: x_vals_train, y_target: np.transpose([y_vals_train])})
  train_acc.append(temp_acc_train)
  temp_acc_test = sess.run(accuracy, feed_dict={x_data: x_vals_test, y_target: np.transpose([y_vals_test])})
  test_acc.append(temp_acc_test)
  if (i+1)%300==0:
    print('Loss = ' + str(temp_loss))

###
# Display model performance
###

# 绘制损失和准确度
plt.plot(loss_vec, 'k-')
plt.title('Cross Entropy Loss per Generation')
plt.xlabel('Generation')
plt.ylabel('Cross Entropy Loss')
plt.show()

# Plot train and test accuracy
plt.plot(train_acc, 'k-', label='Train Set Accuracy')
plt.plot(test_acc, 'r--', label='Test Set Accuracy')
plt.title('Train and Test Accuracy')
plt.xlabel('Generation')
plt.ylabel('Accuracy')
plt.legend(loc='lower right')
plt.show()

数据结果:

Loss = 0.845124
Loss = 0.658061
Loss = 0.471852
Loss = 0.643469
Loss = 0.672077

迭代1500次的交叉熵损失图

迭代1500次的测试集和训练集的准确度图

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

您可能感兴趣的文章:

  • 用TensorFlow实现lasso回归和岭回归算法的示例
  • TensorFlow实现Softmax回归模型
  • 运用TensorFlow进行简单实现线性回归、梯度下降示例
  • 用tensorflow构建线性回归模型的示例代码
  • 用tensorflow实现弹性网络回归算法
  • 用TensorFlow实现戴明回归算法的示例
(0)

相关推荐

  • 运用TensorFlow进行简单实现线性回归、梯度下降示例

    线性回归属于监督学习,因此方法和监督学习应该是一样的,先给定一个训练集,根据这个训练集学习出一个线性函数,然后测试这个函数训练的好不好(即此函数是否足够拟合训练集数据),挑选出最好的函数(cost function最小)即可. 单变量线性回归: a) 因为是线性回归,所以学习到的函数为线性函数,即直线函数: b) 因为是单变量,因此只有一个x. 我们能够给出单变量线性回归的模型: 我们常称x为feature,h(x)为hypothesis. 上面介绍的方法中,我们肯定有一个疑问,怎样能够看出线性

  • 用TensorFlow实现lasso回归和岭回归算法的示例

    也有些正则方法可以限制回归算法输出结果中系数的影响,其中最常用的两种正则方法是lasso回归和岭回归. lasso回归和岭回归算法跟常规线性回归算法极其相似,有一点不同的是,在公式中增加正则项来限制斜率(或者净斜率).这样做的主要原因是限制特征对因变量的影响,通过增加一个依赖斜率A的损失函数实现. 对于lasso回归算法,在损失函数上增加一项:斜率A的某个给定倍数.我们使用TensorFlow的逻辑操作,但没有这些操作相关的梯度,而是使用阶跃函数的连续估计,也称作连续阶跃函数,其会在截止点跳跃扩

  • TensorFlow实现Softmax回归模型

    一.概述及完整代码 对MNIST(MixedNational Institute of Standard and Technology database)这个非常简单的机器视觉数据集,Tensorflow为我们进行了方便的封装,可以直接加载MNIST数据成我们期望的格式.本程序使用Softmax Regression训练手写数字识别的分类模型. 先看完整代码: import tensorflow as tf from tensorflow.examples.tutorials.mnist imp

  • 用tensorflow构建线性回归模型的示例代码

    用tensorflow构建简单的线性回归模型是tensorflow的一个基础样例,但是原有的样例存在一些问题,我在实际调试的过程中做了一点自己的改进,并且有一些体会. 首先总结一下tf构建模型的总体套路 1.先定义模型的整体图结构,未知的部分,比如输入就用placeholder来代替. 2.再定义最后与目标的误差函数. 3.最后选择优化方法. 另外几个值得注意的地方是: 1.tensorflow构建模型第一步是先用代码搭建图模型,此时图模型是静止的,是不产生任何运算结果的,必须使用Session

  • 用TensorFlow实现戴明回归算法的示例

    如果最小二乘线性回归算法最小化到回归直线的竖直距离(即,平行于y轴方向),则戴明回归最小化到回归直线的总距离(即,垂直于回归直线).其最小化x值和y值两个方向的误差,具体的对比图如下图. 线性回归算法和戴明回归算法的区别.左边的线性回归最小化到回归直线的竖直距离:右边的戴明回归最小化到回归直线的总距离. 线性回归算法的损失函数最小化竖直距离:而这里需要最小化总距离.给定直线的斜率和截距,则求解一个点到直线的垂直距离有已知的几何公式.代入几何公式并使TensorFlow最小化距离. 损失函数是由分

  • 用tensorflow实现弹性网络回归算法

    本文实例为大家分享了tensorflow实现弹性网络回归算法,供大家参考,具体内容如下 python代码: #用tensorflow实现弹性网络算法(多变量) #使用鸢尾花数据集,后三个特征作为特征,用来预测第一个特征. #1 导入必要的编程库,创建计算图,加载数据集 import matplotlib.pyplot as plt import tensorflow as tf import numpy as np from sklearn import datasets from tensor

  • 详解用TensorFlow实现逻辑回归算法

    本文将实现逻辑回归算法,预测低出生体重的概率. # Logistic Regression # 逻辑回归 #---------------------------------- # # This function shows how to use TensorFlow to # solve logistic regression. # y = sigmoid(Ax + b) # # We will use the low birth weight data, specifically: # y

  • 一文详解Vue 的双端 diff 算法

    目录 前言 diff 算法 简单 diff 双端 diff 总结 前言 Vue 和 React 都是基于 vdom 的前端框架,组件渲染会返回 vdom,渲染器再把 vdom 通过增删改的 api 同步到 dom. 当再次渲染时,会产生新的 vdom,渲染器会对比两棵 vdom 树,对有差异的部分通过增删改的 api 更新到 dom. 这里对比两棵 vdom 树,找到有差异的部分的算法,就叫做 diff 算法. diff 算法 我们知道,两棵树做 diff,复杂度是 O(n^3) 的,因为每个节

  • Python实现的逻辑回归算法示例【附测试csv文件下载】

    本文实例讲述了Python实现的逻辑回归算法.分享给大家供大家参考,具体如下: 使用python实现逻辑回归 Using Python to Implement Logistic Regression Algorithm 菜鸟写的逻辑回归,记录一下学习过程 代码: #encoding:utf-8 """ Author: njulpy Version: 1.0 Data: 2018/04/10 Project: Using Python to Implement Logisti

  • 详解Java Fibonacci Search斐波那契搜索算法代码实现

    一, 斐波那契搜索算法简述 斐波那契搜索(Fibonacci search) ,又称斐波那契查找,是区间中单峰函数的搜索技术. 斐波那契搜索采用分而治之的方法,其中我们按照斐波那契数列对元素进行不均等分割.此搜索需要对数组进行排序. 与二进制搜索不同,在二进制搜索中,我们将元素分成相等的两半以减小数组范围-在斐波那契搜索中,我们尝试使用加法或减法来获得较小的范围. 斐波那契数列的公式是: Fibo(N)=Fibo(N-1)+Fibo(N-2) 此系列的前两个数字是Fibo(0) = 0和Fibo

  • 详解C++实现链表的排序算法

    一.链表排序 最简单.直接的方式(直接采用冒泡或者选择排序,而且不是交换结点,只交换数据域) //线性表的排序,采用冒泡排序,直接遍历链表 void Listsort(Node* & head) { int i = 0; int j = 0; //用于变量链表 Node * L = head; //作为一个临时量 Node * p; Node * p1; //如果链表为空直接返回 if (head->value == 0)return; for (i = 0; i < head->

  • tensorflow实现逻辑回归模型

    逻辑回归模型 逻辑回归是应用非常广泛的一个分类机器学习算法,它将数据拟合到一个logit函数(或者叫做logistic函数)中,从而能够完成对事件发生的概率进行预测. import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data #下载好的mnist数据集存在F:/mnist/data/中 m

  • 详解Java实现的k-means聚类算法

    需求 对MySQL数据库中某个表的某个字段执行k-means算法,将处理后的数据写入新表中. 源码及驱动 kmeans_jb51.rar 源码 import java.sql.*; import java.util.*; /** * @author tianshl * @version 2018/1/13 上午11:13 */ public class Kmeans { // 源数据 private List<Integer> origins = new ArrayList<>()

  • 详解用java描述矩阵求逆的算法

    今天很开心把困扰几天的问题解决了,在学习线性代数这门课程的时候.想通过程序实现里面的计算方法,比如矩阵求逆,用java代码该如何描述呢? 首先,咱们先用我们所交流语言描述一下算法思路: 1.求出一个矩阵A对应的行列式在第i,j(i表示行,j表示列)位置的余子式(余子式前面乘以-1^(i+j)即得代数余子式): 2.根据代数余子式求得矩阵A行列式的值.(行列式展开法): 3.根据代数余子式和行列式的值求出伴随矩阵: 4.由伴随矩阵和矩阵行列式值求逆矩阵.(A^-1 = A* / |A|). 了解上

  • 详解.net循环、逻辑语句块(基础知识)

    循环.逻辑语句块 好久不写博客了,断更了好几天了,从上周五到今天,从北京到上海,跨越了1213.0公里,从一个熟悉的城市到陌生的城市,还好本人适应力比较好,还有感谢小伙伴的接风咯,一切都不是事,好了,进入正题: 本篇还是.NET 基础部分咯,主要简述循环,判断: 循环: for循环 语法: for(表达式1;表达式2;表达式3) { 循环体; } 表达式1一般为声明循环变量,记录循环的次数(int i=0;) 表达式2一般为循环条件(i<10) 表达式3一般为改变循环条件的代码,使循环条件终有一

  • 详解js数组的完全随机排列算法

    Array.prototype.sort 方法被许多 JavaScript 程序员误用来随机排列数组.最近做的前端星计划挑战项目中,一道实现 blackjack 游戏的问题,就发现很多同学使用了 Array.prototype.sort 来洗牌. 洗牌 以下就是常见的完全错误的随机排列算法: function shuffle(arr){ return arr.sort(function(){ return Math.random() - 0.5; }); } 以上代码看似巧妙利用了 Array.

随机推荐