Iris Classification on Tensorflow

Neural Network

formula derivation

\[\begin{align}
a & = x \cdot w_1 \\
y & = a \cdot w_2 \\
& = x \cdot w_1 \cdot w_2 \\
y & = softmax(y)
\end{align}
\]

code (training only)

\[a = x \cdot w_1 \\
y = a \cdot w_2
\]

w1 = tf.Variable(tf.random_normal([4,5], stddev=1, seed=1))
w2 = tf.Variable(tf.random_normal([5,3], stddev=1, seed=1)) x = tf.placeholder(tf.float32, shape=(None, 4), name='x-input') a = tf.matmul(x, w1)
y = tf.matmul(a, w2)

既然是有监督学习,那就在训练阶段必须要给出 label,以此来计算交叉熵

# 用来存储数据的标签
y_ = tf.placeholder(tf.float32, shape=(None, 3), name='y-input')

隐藏层的激活函数是 sigmoid

y = tf.sigmoid(y)

softmax 与 交叉熵(corss entropy) 的组合函数,损失函数是交叉熵的均值

# softmax & corss_entropy
cross_entropy = tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_, logits=y)
# mean
cross_entropy_mean = tf.reduce_mean(cross_entropy)

为了防止神经网络过拟合,需加入正则化项,一般选取 “L2 正则化”

loss = cross_entropy_mean + \
tf.contrib.layers.l2_regularizer(regulation_lamda)(w1) + \
tf.contrib.layers.l2_regularizer(regulation_lamda)(w2)

为了加速神经网络的训练过程,需加入“指数衰减”技术

表示训练过程的计算图,优化方法选择了 Adam 算法,本质是反向传播算法。还可以选择“梯度下降法”(GradientDescentOptimizer)

train_step = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)

训练阶段

with tf.Session() as sess:  # Session 最好在“上下文机制”中开启,以防资源泄露
init_op = tf.global_variables_initializer() # 初始化网络中节点的参数,主要是 w1,w2
sess.run(init_op) steps = 10000
for i in range(steps):
beg = (i * batch_size) % dataset_size # 计算 batch
end = min(beg+batch_size, dataset_size) # 计算 batch sess.run(train_step, feed_dict={x:X[beg:end], y_:Y[beg:end]}) # 反向传播,训练网络
if i % 1000 == 0:
total_corss_entropy = sess.run( # 计算交叉熵
cross_entropy_mean, # 计算交叉熵
feed_dict={x:X, y_:Y} # 计算交叉熵
)
print("After %d training steps, cross entropy on all data is %g" % (i, total_corss_entropy))

在训练阶段中,需要引入“滑动平均模型”来提高模型在测试数据上的健壮性(这是书上的说法,而我认为是泛化能力)

全部代码

# -*- encoding=utf8 -*-

from sklearn.datasets import load_iris
import tensorflow as tf def label_convert(Y):
l = list()
for y in Y:
if y == 0:
l.append([1,0,0])
elif y == 1:
l.append([0, 1, 0])
elif y == 2:
l.append([0, 0, 1])
return l def load_data():
iris = load_iris()
X = iris.data
Y = label_convert(iris.target)
return (X,Y) if __name__ == '__main__':
X,Y = load_data() learning_rate = 0.001
batch_size = 10
dataset_size = 150
regulation_lamda = 0.001 w1 = tf.Variable(tf.random_normal([4,5], stddev=1, seed=1))
w2 = tf.Variable(tf.random_normal([5,3], stddev=1, seed=1)) x = tf.placeholder(tf.float32, shape=(None, 4), name='x-input')
y_ = tf.placeholder(tf.float32, shape=(None, 3), name='y-input') a = tf.matmul(x, w1)
y = tf.matmul(a, w2) y = tf.sigmoid(y) cross_entropy = tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_, logits=y)
cross_entropy_mean = tf.reduce_mean(cross_entropy)
loss = cross_entropy_mean + \
tf.contrib.layers.l2_regularizer(regulation_lamda)(w1) + \
tf.contrib.layers.l2_regularizer(regulation_lamda)(w2)
train_step = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss) with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op) steps = 10000
for i in range(steps):
beg = (i * batch_size) % dataset_size
end = min(beg+batch_size, dataset_size) sess.run(train_step, feed_dict={x:X[beg:end], y_:Y[beg:end]})
if i % 1000 == 0:
total_corss_entropy = sess.run(
cross_entropy_mean,
feed_dict={x:X, y_:Y}
)
print("After %d training steps, cross entropy on all data is %g" % (i, total_corss_entropy)) print(sess.run(w1))
print(sess.run(w2))

Experiment Result

random split cross validation

Iris Classification on Tensorflow的更多相关文章

  1. Iris Classification on Keras

    Iris Classification on Keras Installation Python3 版本为 3.6.4 : : Anaconda conda install tensorflow==1 ...

  2. Implementing a CNN for Text Classification in TensorFlow

    参考: 1.Understanding Convolutional Neural Networks for NLP 2.Implementing a CNN for Text Classificati ...

  3. [转] Implementing a CNN for Text Classification in TensorFlow

    Github上的一个开源项目,文档讲得极清晰 Github - https://github.com/dennybritz/cnn-text-classification-tf 原文- http:// ...

  4. Iris Classification on PyTorch

    Iris Classification on PyTorch code # -*- coding:utf8 -*- from sklearn.datasets import load_iris fro ...

  5. CNN tensorflow text classification CNN文本分类的例子

    from:http://deeplearning.lipingyang.org/tensorflow-examples-text/ TensorFlow examples (text-based) T ...

  6. python tensorflow model

    step01_formula # -*- coding: utf-8 -*- """ 단순 선형회귀방정식 : x(1) -> y - y = a*X + b (a ...

  7. Chinese-Text-Classification,用卷积神经网络基于 Tensorflow 实现的中文文本分类。

    用卷积神经网络基于 Tensorflow 实现的中文文本分类 项目地址: https://github.com/fendouai/Chinese-Text-Classification 欢迎提问:ht ...

  8. TensorFlow 中文资源全集,官方网站,安装教程,入门教程,实战项目,学习路径。

    Awesome-TensorFlow-Chinese TensorFlow 中文资源全集,学习路径推荐: 官方网站,初步了解. 安装教程,安装之后跑起来. 入门教程,简单的模型学习和运行. 实战项目, ...

  9. 在 TensorFlow 中实现文本分类的卷积神经网络

    在TensorFlow中实现文本分类的卷积神经网络 Github提供了完整的代码: https://github.com/dennybritz/cnn-text-classification-tf 在 ...

随机推荐

  1. nvm管理node之后,安装npm包出现的问题

    在学习Node.js连接MySQL时,使用nvm安装node6.10.0,在项目目录下npm install mysql 出问题. 在查询解决方法后,得知是因为配置文件有问题 package.json ...

  2. Windows jmeter配置

    JMeter是Apache软件基金会的产品,用于对提供静态的和动态的资源服务器性能的测试.是一款很方便的测试软件. JMeter 要依附Java SE 环境 所以在启用JMeter之前要安装JAVA ...

  3. webpack的使用二

    1.安装 Webpack可以使用npm安装,新建一个空的练习文件夹(此处命名为webpack sample project),在终端中转到该文件夹后执行下述指令就可以完成安装 //全局安装 npm i ...

  4. sqli-labs(十一)(二次注入)

    第二十四关: 这关考验的是sql的二次注入. 这关是一个登陆加注册的功能点,登陆的地方没有注入,账号密码都输入输入'",页面只会显示登陆失败. 但注册账号的地方没有做过滤可以注册带有单引符号 ...

  5. node中中间件body-parser的实现方式

    最近学习了Koa框架中用到了koa-bodyparser接收表单POST请求的参数,直接使用其API是很容易的,但却不知道其原生方法怎么实现的.故做些笔记 首先,是搭建了Koa的服务器不再赘述 其次, ...

  6. Oracle 23的用户管理

    创建用户的语法格式 Create user <user_name> Identified by<password> Default tabespace<default t ...

  7. git起步

    关于版本控制 什么是版本控制?为什么要版本控制? 版本控制是记录文件内容变化,以便在将来查阅特定版本的系统.有了版本控制,我们就可以将某个文件或是整个项目回退到之前的某个时间段,查看现在和之前相比项目 ...

  8. 31网络通信之Select模型

    多路复用并发模型  -- select #include<sys/select.h> #include<sys/time.h> int select(int maxfd,  f ...

  9. sitecore系统教程之媒体库

    您可以管理媒体库中的所有媒体项目,例如要嵌入网页的图像或供访问者下载的图像.媒体库包含所有媒体项目,例如图像,文档,视频和音频文件. 在媒体库中,您可以: 将所有媒体文件保存在一个位置,并将其组织在与 ...

  10. [NOIP2005普及组]采药(01背包)

    题目描述 描述 辰辰是个很有潜能.天资聪颖的孩子,他的梦想是称为世界上最伟大的医师.为此,他想拜附近最有威望的医师为师.医师为了判断他的资质,给他出了一个难题.医师把他带到个到处都是草药的山洞里对他说 ...