tensorflow 实现逻辑回归——原以为TensorFlow不擅长做线性回归或者逻辑回归,原来是这么简单哇!

实现的是预测 低 出生 体重 的 概率。
尼克·麦克卢尔(Nick McClure). TensorFlow机器学习实战指南 (智能系统与技术丛书) (Kindle 位置 1060-1061). Kindle 版本.

# 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
###

# Set 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‘, newline=‘‘) 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)
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(15000):
    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
###

# Plot loss over time
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()

原文地址:https://www.cnblogs.com/bonelee/p/8996496.html

时间: 2024-07-31 15:12:40

tensorflow 实现逻辑回归——原以为TensorFlow不擅长做线性回归或者逻辑回归,原来是这么简单哇!的相关文章

统计学习方法:罗杰斯特回归及Tensorflow入门

作者:桂. 时间:2017-04-21  21:11:23 链接:http://www.cnblogs.com/xingshansi/p/6743780.html 前言 看到最近大家都在用Tensorflow,一查才发现火的不行.想着入门看一看,Tensorflow使用手册第一篇是基于MNIST的手写数字识别的,用到softmax regression,而这个恰好与我正在看的<统计信号处理>相关.本文借此梳理一下: 1)罗杰斯特回归 2)Softmax Regression 3)基于Tenso

Matlab实现线性回归和逻辑回归: Linear Regression &amp; Logistic Regression

原文:http://blog.csdn.net/abcjennifer/article/details/7732417 本文为Maching Learning 栏目补充内容,为上几章中所提到单参数线性回归.多参数线性回归和 逻辑回归的总结版.旨在帮助大家更好地理解回归,所以我在Matlab中分别对他们予以实现,在本文中由易到难地逐个介绍. 本讲内容: Matlab 实现各种回归函数 ========================= 基本模型 Y=θ0+θ1X1型---线性回归(直线拟合) 解决

谈谈NG视频里面单线性回归、多线性回归、逻辑回归等等

明天第一节课8.55才上,还是把今天看的东西整理一下吧. 今天主要是看了NG前几章讲的单线性回归.多线性回归.逻辑回归的matlab实现,之前觉得那些东西理解还好,但是写代码好难的样子,但是今天看了大牛的代码发现真的很easy... 但是是很有技巧的用的矩阵去实现. 比如单线性回归里面的j=0和j=1这两种情况,直接把x转换成x = [ones(m, 1) x] , 第一列全是1了,刚好可以把j=0时x=1代入去运算,这样子梯度 grad = (1/m).* x' * ((x * theta) 

线性回归,逻辑回归的学习(包含最小二乘法及极大似然函数等)

博文参考了以下两位博主的文章:http://blog.csdn.net/lu597203933/article/details/45032607,http://blog.csdn.net/viewcode/article/details/8794401 回归问题的前提: 1) 收集的数据 2) 假设的模型,即一个函数,这个函数里含有未知的参数,通过学习,可以估计出参数.然后利用这个模型去预测/分类新的数据. 1. 线性回归 假设 特征 和 结果 都满足线性.即不大于一次方.这个是针对 收集的数据

线性回归与逻辑回归

本文转自:http://blog.csdn.net/itplus/article/details/10857843 本文详细的介绍了线性回归和逻辑回归是怎么一回事,很好的介绍了线性回归的原理和逻辑回归的原理.针对逻辑回归,最后参数的求解过程中,还可以用到牛顿法和拟牛顿法,具体可以参考:http://www.cnblogs.com/ljy2013/p/5129294.html 从上面可以看出,标准梯度下降法每一次利用所有的训练样本数据来更新一个参数的一个纬度的分量:而随即梯度下降方法是针对每一个训

对线性回归、逻辑回归、各种回归的概念学习

http://blog.csdn.net/viewcode/article/details/8794401 回归问题的条件/前提: 1) 收集的数据 2) 假设的模型,即一个函数,这个函数里含有未知的参数,通过学习,可以估计出参数.然后利用这个模型去预测/分类新的数据. 1. 线性回归 假设 特征 和 结果 都满足线性.即不大于一次方.这个是针对 收集的数据而言.收集的数据中,每一个分量,就可以看做一个特征数据.每个特征至少对应一个未知的参数.这样就形成了一个线性模型函数,向量表示形式: 这个就

机器学习系列:(四)从线性回归到逻辑回归

从线性回归到逻辑回归 在第2章,线性回归里面,我们介绍了一元线性回归,多元线性回归和多项式回归.这些模型都是广义线性回归模型的具体形式,广义线性回归是一种灵活的框架,比普通线性回归要求更少的假设.这一章,我们讨论广义线性回归模型的具体形式的另一种形式,逻辑回归(logistic regression). 和前面讨论的模型不同,逻辑回归是用来做分类任务的.分类任务的目标是找一个函数,把观测值匹配到相关的类和标签上.学习算法必须用成对的特征向量和对应的标签来估计匹配函数的参数,从而实现更好的分类效果

线性回归和 逻辑回归 的思考(参考斯坦福 吴恩达的课程)

还是不习惯这种公式的编写,还是直接上word.... 对上面的(7)式取log后并最大化即可得到最小二乘法,即 argmaxθ J(θ) 思考二:线性回归到逻辑回归的转变: 1) 引入逻辑回归,假设用线性回归来做分类问题,设为二分类,即y取0或1. 则会出现如下的情况: 这种情况下是能很好的分类的,但若数据是如下所示呢: 则分类很不好. 思考三:逻辑回归损失函数的得来(解释):     答,也是通过最大似然得到的.y的取值为0,1:则认为这是一个伯努力的分布,也称为两点的分布,则公式表示如下:

机器学习总结(六)线性回归与逻辑回归

线性回归(Linear Regression) 是利用称为线性回归方程的最小平方函数对一个或多个自变量和因变量之间关系进行建模的一种回归分析.这种函数是一个或多个称为回归系数的模型参数的线性组合(自变量都是一次方).只有一个自变量的情况称为简单回归,大于一个自变量情况的叫做多元回归.线性回归的模型函数如下: 损失函数(基于均方误差最小化) 通过训练数据集寻找参数的最优解,即求解可以得minJ(θ)的参数向量θ,其中这里的参数向量也可以分为参数和w和b,分别表示权重和偏置值. 线性回归方程可通过两