tflearn 实现DNN 全连接
https://github.com/tflearn/tflearn/blob/master/examples/others/recommender_wide_and_deep.py
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import tflearn
from tflearn.data_utils import to_categorical
#matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray' # for auto-reloading extenrnal modules
# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython
#%load_ext autoreload
#%autoreload 2 # 模块1-1 画图 展示样本形式
np.random.seed(0)
N = 100 # number of points per class
D = 2 # dimensionality
K = 3 # number of classes
X = np.zeros((N*K,D))
y = np.zeros(N*K, dtype='uint8')
for j in range(K):
ix = range(N*j,N*(j+1))
r = np.linspace(0.0,1,N) # radius
t = np.linspace(j*4,(j+1)*4,N) + np.random.randn(N)*0.2 # theta
X[ix] = np.c_[r*np.sin(t), r*np.cos(t)]
y[ix] = j
fig = plt.figure()
plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral)
plt.xlim([-1,1])
plt.ylim([-1,1])
#fig.savefig('spiral_raw.png') #模块1-2 训练 两层
import tensorflow as tf
import tflearn
from tflearn.data_utils import to_categorical with tf.Graph().as_default():
net = tflearn.input_data([None, 2])
net = tflearn.fully_connected(net, 100, activation='relu', weights_init='normal',
regularizer='L2', weight_decay=0.001)
net = tflearn.fully_connected(net, 3, activation='softmax')
sgd = tflearn.SGD(learning_rate=1.0, lr_decay=0.96, decay_step=500)
net = tflearn.regression(net, optimizer=sgd, loss='categorical_crossentropy') # gd=tf.train.GradientDescentOptimizer(learning_rate=1.0)
# net = tflearn.regression(net, optimizer=gd, loss='categorical_crossentropy') Y = to_categorical(y, 3)
model = tflearn.DNN(net)
model.fit(X, Y, show_metric=True, batch_size=len(X), n_epoch=100, snapshot_epoch=False)
#print model.predict(X)
Z = np.argmax(model.predict(X))
#print Z # 模块1-3 画图展示效果 plot the resulting classifier
h = 0.02
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
Z = np.argmax(model.predict(np.c_[xx.ravel(), yy.ravel()]), axis=1)
Z = Z.reshape(xx.shape)
fig = plt.figure()
plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral, alpha=0.8)
plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
#fig.savefig('spiral_net.png')
print("Accuracy: {}%".format(100 * np.mean(y == np.argmax(model.predict(X), axis=1))))
代码2 自己的数据
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import tflearn
from tflearn.data_utils import to_categorical
import os label=[]
feature=[]
f_tain=open("smp_pub_50d",'r')
for line in f_tain.readlines()[0:50000]:
samp=eval(line)
gender=int(samp[2])
feature1=samp[5:]
feature.append(feature1)
label.append(gender)
f_tain.close() X=np.array(feature)
Y=np.array(label) #模块1-2 训练 两层
import tensorflow as tf
import tflearn
from tflearn.data_utils import to_categorical with tf.Graph().as_default():
net = tflearn.input_data([None, 50])
net = tflearn.fully_connected(net, 100, activation='relu', weights_init='normal',
regularizer='L2', weight_decay=0.001)
net = tflearn.fully_connected(net, 2, activation='softmax')
sgd = tflearn.SGD(learning_rate=1.0, lr_decay=0.96, decay_step=500)
net = tflearn.regression(net, optimizer=sgd, loss='categorical_crossentropy') # gd=tf.train.GradientDescentOptimizer(learning_rate=1.0)
# net = tflearn.regression(net, optimizer=gd, loss='categorical_crossentropy') Y = to_categorical(Y, 2)
model = tflearn.DNN(net)
model.fit(X, Y, validation_set=0.3,show_metric=True, batch_size=20000, n_epoch=100, snapshot_epoch=False)
#print model.predict(X)
Z = np.argmax(model.predict(X))
#print Z
tflearn 实现DNN 全连接的更多相关文章
- TensorFlow之DNN(二):全连接神经网络的加速技巧(Xavier初始化、Adam、Batch Norm、学习率衰减与梯度截断)
在上一篇博客<TensorFlow之DNN(一):构建“裸机版”全连接神经网络>中,我整理了一个用TensorFlow实现的简单全连接神经网络模型,没有运用加速技巧(小批量梯度下降不算哦) ...
- TensorFlow之DNN(一):构建“裸机版”全连接神经网络
博客断更了一周,干啥去了?想做个聊天机器人出来,去看教程了,然后大受打击,哭着回来补TensorFlow和自然语言处理的基础了.本来如意算盘打得挺响,作为一个初学者,直接看项目(不是指MINIST手写 ...
- PyTorch全连接ReLU网络
PyTorch全连接ReLU网络 1.PyTorch的核心是两个主要特征: 一个n维张量,类似于numpy,但可以在GPU上运行 搭建和训练神经网络时的自动微分/求导机制 本文将使用全连接的ReLU网 ...
- Linq连接查询之左连接、右连接、内连接、全连接、交叉连接、Union合并、Concat连接、Intersect相交、Except与非查询
内连接查询 内连接与SqL中inner join一样,即找出两个序列的交集 Model1Container model = new Model1Container(); //内连接 var query ...
- SQL多表查询:内连接、外连接(左连接、右连接)、全连接、交叉连接
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPgAAADCCAIAAADrUpiXAAAGYklEQVR4nO3dQXqjuAJFYa1LC9J6tB
- SQL Server之内连接 左连接 右连接 全连接 交叉连接
SELECT * FROM Table_A GO SELECT * FROM Table_B GO --内连接 SELECT a.*, b.* FROM Table_A a JOIN Table_B ...
- SQL 四种连接:内连接、左外连接、右外连接、全连接--转载
原文:http://zwdsmileface.iteye.com/blog/2191730 个人理解 内连接(INNER JOIN)(典型的连接运算,使用像 = 或 <> ...
- caffe之(四)全连接层
在caffe中,网络的结构由prototxt文件中给出,由一些列的Layer(层)组成,常用的层如:数据加载层.卷积操作层.pooling层.非线性变换层.内积运算层.归一化层.损失计算层等:本篇主要 ...
- 全连接的BP神经网络
<全连接的BP神经网络> 本文主要描述全连接的BP神经网络的前向传播和误差反向传播,所有的符号都用Ng的Machine learning的习惯.下图给出了某个全连接的神经网络图. 1前向传 ...
随机推荐
- HTTP Status 500 - The absolute uri: http://java.sun.com/jsp/jstl/core cannot-报错解决方法
操作:jsp文件里面添加<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" % ...
- 【转载】Vmware Vconverter从物理机迁移系统到虚拟机P2V
本文完整记录了如何从物理服务器,保持所有环境配置信息,纹丝不动的迁移到虚拟机上,俗称 P2V .采用的工具是VMware公司的 VMware vcenter vconverter standalone ...
- MySQL 特殊参数
###开发规范 开发规范:关键字大写,库名字小写,要有字符集 CREATE DATABSE oldboy CHARSET utf8; ###建议采用第一种 CREATE DATABSE oldb ...
- 利用python,简单的词语纠错
利用python,编写一个简单的词语纠正修改器. 原文:http://norvig.com/spell-correct.html #!/usr/bin/env python # coding=utf- ...
- pyplot 绘图与可视化
1. 基本使用 #!/usr/bin/env python # coding=utf-8 import matplotlib.pyplot as plt from numpy.random impor ...
- [UE4]Character,飞行模式。
Character 是pawn的子类,可以行走.跳跃.游泳.飞行的Pawn.
- google浏览器清除缓存
google浏览器设置不缓存的方法 摘要:我们在做web开发的时候特别是在调试js时,会经常使用的google浏览器,这个时候就要我们修改过的代码可能不能生效.这是因为我们的浏览器默认是有缓存的,但是 ...
- TACACS+简单说明
1 TACACS+概述 1.1 什么是TACACS+ TACACS+(Terminal Access Controller Access Control System,终端访问控制器控制系统协议)是在 ...
- javascript继承之原型链(一)
function Father() { this.fatherValue = "爸爸"; } Father.prototype.getFatherValue = function ...
- Executor框架(四)周期/延时任务ScheduleThreadPoolExecutor
ScheduledThreadPoolExecutor 介绍 ScheduledThreadPoolExecutor 是一个可以实现定时任务的 ThreadPoolExecutor(线程池).比 ...