逻辑斯特回归tensorflow实现
calss
#!/usr/bin/python2.7
#coding:utf-8
from __future__ import print_function
import tensorflow as tf
# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("../Mnist_data/", one_hot=True)
print(mnist)
# Parameters setting
learning_rate = 0.01
training_epochs = 25 # 训练迭代的次数
batch_size = 100 # 一次输入的样本
display_step = 1
# set the tf Graph Input & set the model weights
x = tf.placeholder(dtype=tf.float32, shape=[None,784], name="input_x")
y = tf.placeholder(dtype=tf.float32, shape=[None,10], name="input_y")
#set models weights,bias
W=tf.Variable(tf.zeros([784,10]))
b=tf.Variable(tf.zeros([10]))
# Construct the model
pred=tf.nn.softmax(tf.matmul(x,W)+b) # 归一化,the possibility of getting the right value
# Minimize error using cross entropy & set the gradient descent
cost=tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred),reduction_indices=1)) #交叉熵,reducion_indices=1横向求和
optimizer=tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
# Initialize the variables (i.e. assign their default value)
init = tf.global_variables_initializer()
# Start training
with tf.Session() as sess:
# Run the initializer
sess.run(init)
# Training cycle
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = int(mnist.train.num_examples/batch_size)
# Loop over all batches
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
# Run optimization op (backprop) and cost op (to get loss value)
_, c = sess.run([optimizer, cost], feed_dict={x: batch_xs,
y: batch_ys})
# Compute average loss
avg_cost += c / total_batch
# Display logs per epoch step
if (epoch+1) % display_step == 0:
print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))
print("Optimization Finished!")
# Test model
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
# Calculate accuracy
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))
linear regression
from __future__ import print_function
import tensorflow as tf
import numpy as np
def add_layer(inputs, in_size, out_size, activation_function=None):
# add one more layer and return the output of this layer
Weights = tf.Variable(tf.random_normal([in_size, out_size]))
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
Wx_plus_b = tf.matmul(inputs, Weights) + biases
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b)
return outputs
# 1.训练的数据 # Make up some real data
x_data = np.linspace(-1,1,300)[:, np.newaxis]
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise
# 2.定义节点准备接收数据
# define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 1])
ys = tf.placeholder(tf.float32, [None, 1])
# 3.定义神经层:隐藏层和预测层
# add hidden layer 输入值是 xs,在隐藏层有 10 个神经元
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)
# add output layer 输入值是隐藏层 l1,在预测层输出 1 个结果
prediction = add_layer(l1, 10, 1, activation_function=None)
# 4.定义 loss 表达式
# the error between prediciton and real data
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1]))
# 5.选择 optimizer 使 loss 达到最小
# 这一行定义了用什么方式去减少 loss,学习率是 0.1
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
# important step 对所有变量进行初始化
init = tf.initialize_all_variables()
with tf.Session() as sess:
# 上面定义的都没有运算,直到 sess.run 才会开始运算
sess.run(init)
# 迭代 1000 次学习,sess.run optimizer
for epoch in range(1000):
# training train_step 和 loss 都是由 placeholder 定义的运算,所以这里要用 feed 传入参数
_, cost = sess.run([train_step, loss], feed_dict={xs: x_data, ys: y_data})
if (epoch+1) % 50 == 0:
# to see the step improvement
print("Epoch:", '%04d' % (epoch + 1), "cost=", "{:.9f}".format(cost))
逻辑斯特回归tensorflow实现的更多相关文章
- [置顶] 局部加权回归、最小二乘的概率解释、逻辑斯蒂回归、感知器算法——斯坦福ML公开课笔记3
转载请注明:http://blog.csdn.net/xinzhangyanxiang/article/details/9113681 最近在看Ng的机器学习公开课,Ng的讲法循循善诱,感觉提高了不少 ...
- 【分类器】感知机+线性回归+逻辑斯蒂回归+softmax回归
一.感知机 详细参考:https://blog.csdn.net/wodeai1235/article/details/54755735 1.模型和图像: 2.数学定义推导和优化: 3.流程 ...
- 【转】机器学习笔记之(3)——Logistic回归(逻辑斯蒂回归)
原文链接:https://blog.csdn.net/gwplovekimi/article/details/80288964 本博文为逻辑斯特回归的学习笔记.由于仅仅是学习笔记,水平有限,还望广大读 ...
- 机器学习之LinearRegression与Logistic Regression逻辑斯蒂回归(三)
一 评价尺度 sklearn包含四种评价尺度 1 均方差(mean-squared-error) 2 平均绝对值误差(mean_absolute_error) 3 可释方差得分(explained_v ...
- spark机器学习从0到1逻辑斯蒂回归之(四)
逻辑斯蒂回归 一.概念 逻辑斯蒂回归(logistic regression)是统计学习中的经典分类方法,属于对数线性模型.logistic回归的因变量可以是二分类的,也可以是多分类的.logis ...
- python机器学习实现逻辑斯蒂回归
逻辑斯蒂回归 关注公众号"轻松学编程"了解更多. [关键词]Logistics函数,最大似然估计,梯度下降法 1.Logistics回归的原理 利用Logistics回归进行分类的 ...
- 【项目实战】pytorch实现逻辑斯蒂回归
视频指导:https://www.bilibili.com/video/BV1Y7411d7Ys?p=6 一些数据集 在pytorch框架下,里面面有配套的数据集,pytorch里面有一个torchv ...
- 【TensorFlow入门完全指南】模型篇·逻辑斯蒂回归模型
import库,加载mnist数据集. 设置学习率,迭代次数,batch并行计算数量,以及log显示. 这里设置了占位符,输入是batch * 784的矩阵,由于是并行计算,所以None实际上代表并行 ...
- 逻辑斯蒂回归(Logistic Regression)
逻辑回归名字比较古怪,看上去是回归,却是一个简单的二分类模型. 逻辑回归的模型是如下形式: 其中x是features,θ是feature的权重,σ是sigmoid函数.将θ0视为θ0*x0(x0取值为 ...
随机推荐
- vue过渡动画
概述 Vue 在插入.更新或者移除 DOM 时,提供多种不同方式的应用过渡效果.包括以下工具: 在 CSS 过渡和动画中自动应用 class 可以配合使用第三方 CSS 动画库,如 Animate.c ...
- Loj #3057. 「HNOI2019」校园旅行
Loj #3057. 「HNOI2019」校园旅行 某学校的每个建筑都有一个独特的编号.一天你在校园里无聊,决定在校园内随意地漫步. 你已经在校园里呆过一段时间,对校园内每个建筑的编号非常熟悉,于是你 ...
- php面试题整理(一)
str_split() print_r(str_split("Shanghai"));Array ( [0] => S [1] => h [2] => a [3] ...
- 第二十六篇:USB3.0高带宽ISO(48KBytes/125us)实战
USB3.1技术已经推出, 10Gbps的速率足以满足数据, HD视频传输的要求. 要步入USB3.1的研发, 还得将USB3.0的基础打扎实. 微软提供的SUPER MUTT仅仅包括一个接口0, 其 ...
- 关于connect by rownum与connect by leve
http://www.itpub.net/forum.php?mod=viewthread&tid=1570306 http://www.itpub.net/forum.php?mod=vie ...
- 2017-2018-2 20155314《网络对抗技术》Exp7 网络欺诈防范
2017-2018-2 20155314<网络对抗技术>Exp7 网络欺诈防范 目录 实验目标 实验内容 实验环境 基础问题回答 预备知识 实验步骤 1 利用setoolkit建立冒名网站 ...
- Spark性能优化指南——基础篇(转载)
前言 在大数据计算领域,Spark已经成为了越来越流行.越来越受欢迎的计算平台之一.Spark的功能涵盖了大数据领域的离线批处理.SQL类处理.流式/实时计算.机器学习.图计算等各种不同类型的计算操作 ...
- 【原创】JAVA8之妙用Optional解决NPE问题
引言 在文章的开头,先说下NPE问题,NPE问题就是,我们在开发中经常碰到的NullPointerException.假设我们有两个类,他们的UML类图如下图所示 在这种情况下,有如下代码 user. ...
- FineUIPro v3.6.0 发布了(3 年助力 200 家企业的信息化建设)!
FineUI(专业版)自从 2014-07-30 发布第一个版本以来,3 年来已经持续更新了 25 个版本,我们的坚持有目共睹,同时也受到了 200 家企业的青睐和信任,感谢一路有你. FineUI( ...
- 企业IT架构转型之道,阿里巴巴中台战略思想与架构实战
前言: 晚上11点多闲来无事,打开QQ技术群,发现有关 '中心化与引擎化' 的话题,本着学习的心态向大佬咨询,大佬推荐一本书,我大概看了有四分之一的样子,对于我这种对架构迷茫的人来说,如鱼得水,于是特 ...