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前向传 ...
随机推荐
- 关于IOS给我的启发
用了将近一年半的iOS,从4到4S,iOS5到iOS6.这里谈谈自己对iOS的一些看法,以及这款移动操作系统给我的启发.我知道这个帖子发出来可能有点“危险”.我从不发水贴,这些积分都是大家给的,不是灌 ...
- NoSQL高级培训课程-HBase&&MongoDB(两天版)
课程大纲 主题 时间 主题 列数据库 (第1天) 上午 HBase发展简史-Google BigTable的开源实现 HBase基础:安装部署.管理命令.运行监控和开发接口: HBase专题:服务组件 ...
- 杂项:MSMQ
ylbtech-杂项:MSMQ MicroSoft Message Queuing(微软消息队列)是在多个不同的应用之间实现相互通信的一种异步传输模式,相互通信的应用可以分布于同一台机器上,也可以分布 ...
- 阿里云EC2+QEMU虚拟机+ROS完全教程!
---恢复内容开始--- 1.安装centos6.5 x64 同时记录,当前centos分配得到的IP,子网掩码,网关,以及MAC!!! 查看IP.mac命令ip add 查看网关命令cat /etc ...
- ThinkPHP框架学习摘要
框架在linux与win下区别 1.文件权限设置: 2.大小写不规范: 学习框架的基本思路 : 1.如何收入并配置框架: 2.Controller的命名规范与书写规范: 3.Model的命名规范与书写 ...
- Eclipse中安装及配置EGit插件
转载:https://jingyan.baidu.com/article/59703552dcc5ad8fc107407e.html
- 给iOS开发新手送点福利,简述UIImagePickerController的属性和用法
1.+(BOOL)isSourceTypeAvailable:(UIImagePickerControllerSourceType)sourceType; // 检查指定源是否在设备上 ...
- python中的logger模块详细讲解
logger 提供了应用程序可以直接使用的接口handler将(logger创建的)日志记录发送到合适的目的输出filter提供了细度设备来决定输出哪条日志记录formatter决定日志记录的最终输出 ...
- python读取文件中的字典
import ast def file_read(): with open('D:\\pytharm\\jichuyufa\\day2\\pro_cty_con.txt', 'r', encod ...
- 小朋友学C语言(8)
求圆周率 (一)圆周率简介 圆周率(Pi)是圆的周长与直径的比值,一般用希腊字母π表示,是一个在数学及物理学中普遍存在的数学常数.π也等于圆形之面积与半径平方之比.是精确计算圆周长.圆面积.球体积等几 ...