利用TensorFlow实现多元逻辑回归,代码如下:

import tensorflow as tf
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn import preprocessing # Read x and y
x_data = np.loadtxt("ex4x.dat").astype(np.float32)
y_data = np.loadtxt("ex4y.dat").astype(np.float32) scaler = preprocessing.StandardScaler().fit(x_data)
x_data_standard = scaler.transform(x_data) # We evaluate the x and y by sklearn to get a sense of the coefficients.
reg = LogisticRegression(C=999999999, solver="newton-cg") # Set C as a large positive number to minimize the regularization effect
reg.fit(x_data, y_data)
print ("Coefficients of sklearn: K=%s, b=%f" % (reg.coef_, reg.intercept_)) # Now we use tensorflow to get similar results.
W = tf.Variable(tf.zeros([2, 1]))
b = tf.Variable(tf.zeros([1, 1]))
y = 1 / (1 + tf.exp(-tf.matmul(x_data_standard, W) + b))
loss = tf.reduce_mean(- y_data.reshape(-1, 1) * tf.log(y) - (1 - y_data.reshape(-1, 1)) * tf.log(1 - y)) optimizer = tf.train.GradientDescentOptimizer(1.3)
train = optimizer.minimize(loss) init = tf.initialize_all_variables() sess = tf.Session()
sess.run(init)
for step in range(100):
sess.run(train)
if step % 10 == 0:
print (step, sess.run(W).flatten(), sess.run(b).flatten()) print ("Coefficients of tensorflow (input should be standardized): K=%s, b=%s" % (sess.run(W).flatten(), sess.run(b).flatten()))
print ("Coefficients of tensorflow (raw input): K=%s, b=%s" % (sess.run(W).flatten() / scaler.scale_, sess.run(b).flatten() - np.dot(scaler.mean_ / scaler.scale_, sess.run(W)))) # Problem solved and we are happy. But...
# I'd like to implement the logistic regression from a multi-class viewpoint instead of binary.
# In machine learning domain, it is called softmax regression
# In economic and statistics domain, it is called multinomial logit (MNL) model, proposed by Daniel McFadden, who shared the 2000 Nobel Memorial Prize in Economic Sciences. print ("------------------------------------------------")
print ("We solve this binary classification problem again from the viewpoint of multinomial classification")
print ("------------------------------------------------") # As a tradition, sklearn first
reg = LogisticRegression(C=9999999999, solver="newton-cg", multi_class="multinomial")
reg.fit(x_data, y_data)
print ("Coefficients of sklearn: K=%s, b=%f" % (reg.coef_, reg.intercept_))
print ("A little bit difference at first glance. What about multiply them with 2?") # Then try tensorflow
W = tf.Variable(tf.zeros([2, 2])) # first 2 is feature number, second 2 is class number
b = tf.Variable(tf.zeros([1, 2]))
V = tf.matmul(x_data_standard, W) + b
y = tf.nn.softmax(V) # tensorflow provide a utility function to calculate the probability of observer n choose alternative i, you can replace it with `y = tf.exp(V) / tf.reduce_sum(tf.exp(V), keep_dims=True, reduction_indices=[1])` # Encode the y label in one-hot manner
lb = preprocessing.LabelBinarizer()
lb.fit(y_data)
y_data_trans = lb.transform(y_data)
y_data_trans = np.concatenate((1 - y_data_trans, y_data_trans), axis=1) # Only necessary for binary class loss = tf.reduce_mean(-tf.reduce_sum(y_data_trans * tf.log(y), reduction_indices=[1]))
optimizer = tf.train.GradientDescentOptimizer(1.3)
train = optimizer.minimize(loss) init = tf.initialize_all_variables() sess = tf.Session()
sess.run(init)
for step in range(100):
sess.run(train)
if step % 10 == 0:
print (step, sess.run(W).flatten(), sess.run(b).flatten()) print ("Coefficients of tensorflow (input should be standardized): K=%s, b=%s" % (sess.run(W).flatten(), sess.run(b).flatten()))
print ("Coefficients of tensorflow (raw input): K=%s, b=%s" % ((sess.run(W) / scaler.scale_).flatten(), sess.run(b).flatten() - np.dot(scaler.mean_ / scaler.scale_, sess.run(W))))

数据集下载:下载地址

利用TensorFlow实现多元逻辑回归的更多相关文章

  1. 利用TensorFlow实现多元线性回归

    利用TensorFlow实现多元线性回归,代码如下: # -*- coding:utf-8 -*- import tensorflow as tf import numpy as np from sk ...

  2. 逻辑回归原理_挑战者飞船事故和乳腺癌案例_Python和R_信用评分卡(AAA推荐)

    sklearn实战-乳腺癌细胞数据挖掘(博客主亲自录制视频教程) https://study.163.com/course/introduction.htm?courseId=1005269003&a ...

  3. scikit-learn 逻辑回归类库使用小结

    之前在逻辑回归原理小结这篇文章中,对逻辑回归的原理做了小结.这里接着对scikit-learn中逻辑回归类库的我的使用经验做一个总结.重点讲述调参中要注意的事项. 1. 概述 在scikit-lear ...

  4. scikit_learn逻辑回归类库

    来自:刘建平 1.概述 在scikit-learn中,与逻辑回归有关的主要有3个类.LogisticRegression, LogisticRegressionCV 和 logistic_regres ...

  5. Sklearn实现逻辑回归

    方法与参数 LogisticRegression类的各项参数的含义 class sklearn.linear_model.LogisticRegression(penalty='l2', dual=F ...

  6. 线性回归、逻辑回归(LR)

    线性回归 回归是一种极易理解的模型,就相当于y=f(x),表明自变量 x 和因变量 y 的关系.最常见问题有如 医生治病时的望.闻.问.切之后判定病人是否生了什么病,其中的望闻问切就是获得自变量x,即 ...

  7. 逻辑回归(Logistic Regression)算法小结

    一.逻辑回归简述: 回顾线性回归算法,对于给定的一些n维特征(x1,x2,x3,......xn),我们想通过对这些特征进行加权求和汇总的方法来描绘出事物的最终运算结果.从而衍生出我们线性回归的计算公 ...

  8. 通俗地说逻辑回归【Logistic regression】算法(二)sklearn逻辑回归实战

    前情提要: 通俗地说逻辑回归[Logistic regression]算法(一) 逻辑回归模型原理介绍 上一篇主要介绍了逻辑回归中,相对理论化的知识,这次主要是对上篇做一点点补充,以及介绍sklear ...

  9. sklearn逻辑回归(Logistic Regression,LR)调参指南

    python信用评分卡建模(附代码,博主录制) https://study.163.com/course/introduction.htm?courseId=1005214003&utm_ca ...

随机推荐

  1. (广度搜索)A - Prime Path(11.1.1)

    A - Prime Path(11.1.1) Time Limit:1000MS    Memory Limit:65536KB    64bit IO Format:%I64d & %I64 ...

  2. tomcat项目启动报错java.lang.ClassCastException: org.apache.xerces.parsers.XML11Configuration……

    周一上班启动项目,报错如图: 看到网上说的原因,有jar包冲突造成的,我这里的是: 情况:console打印信息有多次连接数据库,但该项目只需要连接一个库.再仔细看,发现有其他项目的信息,打开tomc ...

  3. poj3376 Finding Palindromes【exKMP】【Trie】

    Finding Palindromes Time Limit: 10000MS   Memory Limit: 262144K Total Submissions:4710   Accepted: 8 ...

  4. .NET Core错误:The specified framework 'Microsoft.NETCore.App', version '1.0.0-rc2-3002702' was not found.

    本地Dos命令行中,cd到你的项目目录下,生成, dotnet {U_Project_Name}.dll 发布 dotnet publish ,然后将发布的文件夹中的文件全部拷贝到服务器中,至此,问题 ...

  5. Steeltoe之Service Discovery篇

    在前文一窥Spring Cloud Eureka中,已经构建了基于Eureka的服务端与客户端,可用于实现服务注册与发现功能.而借助Steeltoe的类库,可以在.NET生态系统中使用Spring C ...

  6. 12.4 hdfs总结

    启动hdfs 需要在namenode 节点 上 s11 启动yarn 需要在resourceManager 节点上 namenode, resourceManager 都需要在整个集群中都是可以无密登 ...

  7. Codeforces 670E - Correct Bracket Sequence Editor - [对顶栈]

    题目链接:https://codeforces.com/contest/670/problem/E 题意: 给出一个已经匹配的括号串,给出起始的光标位置(光标总是指向某个括号). 有如下操作: 1.往 ...

  8. [No000013F]WPF学习之X名称空间详解

    X名称空间里面的成员(如X:Name,X:Class)都是写给XAML编译器看的.用来引导XAML代码将XAML代码编译为CLR代码. 4.1X名称空间里面到底都有些什么? x名称空间映射的是:htt ...

  9. SQL Server 查询数据库中被锁定的表

    在一次测试过程中,发现有些表一直被锁定,从网上搜集了下资料,可以使用一下语句查看数据库中那些表正被锁定: select request_session_id spid,OBJECT_NAME(reso ...

  10. 部署Java项目到阿里云服务器主机

    https://m.aliyun.com/jiaocheng/548684.html https://blog.csdn.net/qq_30865575/article/details/7827329 ...