附录一个:Keras学习随笔 http://blog.csdn.net/niuwei22007/article/details/49045909

参考 《Python Machine Learning》这本书的第13章

Theano是Bengio大神课题组弄得。

一、Theano初步

Theano编程三个步骤: 初始化、编译和执行,就是定义符号(变量对象)、编译代码和执行代码

举个例子:计算 z=x1*w1+wo 代码如下:

 # -*- coding: utf-8 -*-
__author__ = 'Administrator' import theano
import theano.tensor as T
import random
import numpy as np
from itertools import izip
import matplotlib.pyplot as plt #初始化
x1 = T.scalar()
w1 = T.scalar()
w0 = T.scalar()
z = w1*x1+w0 #编译 net_input = theano.function(
inputs=[w1, x1, w0],
outputs=z
) #执行 print 'net input %.2f'% (net_input(2.0, 1.0 ,0.5))

在写Theano代码时,要注意变量的类型 dtype ,要分清楚我们要使用 64或者32为的int or floats

二、 配置Theano

一般来说 采用CPU时,我们设置float64 ,采用GPU时,需要设置float32

print (theano.config.floatX)
print (theano.config.device)

在window中设置CPU or GPU模式,是在运行cmd后出现的路径下,新建一个.theanorc.txt的文件。文件内容如下图所示

三、使用array结构

一个简单的求和例子

 #初始化
x = T.fmatrix(name ='x')
x_sum = T.sum(x, axis=1) # 0 是按列 1 是按行 #编译
calc_sum = theano.function(
inputs=[x],
outputs=x_sum
) #执行
ary = np.array([[1,2,4],[1,2,3]],dtype=theano.config.floatX)
print calc_sum(ary)

shared variable 和 权值更新

 #初始化
x = T.fmatrix('x')
w = theano.shared(np.asarray([[0.0,0.0,0.0]],dtype=theano.config.floatX)) z = T.dot(x,w.T) # 这个就是两个矩阵相乘 w是1*3 x是1*3 update = [[w, w+1.0]] # 编译
net_input = theano.function(
inputs=[x],
updates=update,
outputs=z
) # 执行 data = np.array([[1,2,3]],dtype=theano.config.floatX)
for i in range(5):
print w.get_value()
print '%d %.2f' % (i,net_input(data))

可以提取指定数据,代码如下

 #初始化
data = np.array([[1,2,3]],dtype=theano.config.floatX)
x = T.fmatrix('x')
w = theano.shared(np.asarray([[0.0,0.0,0.0]],dtype=theano.config.floatX)) z = T.dot(x,w.T) # 这个就是两个矩阵相乘 w是1*3 x是1*3 update = [[w, w+1.0]] # 编译
net_input = theano.function(
inputs=[],
updates=update,
givens={x : data},
outputs=z
) # 执行 for i in range(5):
print w.get_value()
print '%d %.2f' % (i,net_input())

四、 一个线性回归的例子

 X_train = np.asarray(
[ [0,0] , [1, 0],
[2,0] , [3, 0],
[4,0] , [5, 0],
[6,0] , [7, 0],
[8,0] , [9, 0]],
dtype= theano.config.floatX
) y_train = np.asarray(
[ 1.0,1.3,3.1,2.0,
5.0,6.3,6.6,7.4,
8.0,9.0],
dtype= theano.config.floatX
) y_train_new = np.asarray(
[ [1.0],[1.3],[3.1],[2.0],
[5.0],[6.3],[6.6],[7.4],
[8.0],[9.0]],
dtype= theano.config.floatX
)
print X_train.shape[1] # shape 0 获取行 shape 1 获取列 def train_linreg(X_train, y_train ,eta, epochs):
costs = []
#初始化array0
eta0 = T.fscalar('eta0')
y = T.fvector(name='y')
X = T.fmatrix(name='X')
w = theano.shared(np.zeros(
shape=(X_train.shape[1] +1 ),dtype= theano.config.floatX), name = 'w') #计算损失函数
net_input = T.dot(X, w[1:]) + w[0] # w[1:] 从第二个到最后一个数据
errors = y - net_input
cost = T.sum(T.pow(errors,2)) #梯度更新
gradient = T.grad(cost,wrt=w)
update = [(w, w- eta0* gradient)] #定义模型
train = theano .function(inputs=[eta0],
outputs=cost,
updates=update,
givens={X:X_train,
y: y_train}) for i in range(epochs):
costs.append(train(eta))
print w.get_value()
return costs, w def predict_linreg(X,w):
Xt = T.matrix(name='X')
net_input = T.dot(Xt, w[1:])+w[0]
predict = theano.function(inputs=[Xt],
givens={w:w},
outputs= net_input)
return predict(X) costs,w= train_linreg(X_train,y_train,eta=0.001,epochs=10)
plt.plot(range(1,len(costs)+1),costs)
plt.tight_layout()
plt.xlabel("epoch")
plt.ylabel('cost')
plt.show()
#
#plt.scatter(X_train, y_train ,marker='s',s=50)
plt.plot(range(X_train.shape[0]),predict_linreg(X_train,w),color='gray',marker='o',markersize=4,linewidth=3)
plt.xlabel("x")
plt.ylabel('y')
plt.show()

结果图:

 

Theano入门神经网络(三)的更多相关文章

  1. Theano入门神经网络(一)

    Theano是一个Python库,专门用于定义.优化.求值数学表达式,效率高,适用于多维数组.特别适合做机器学习.一般来说,使用时需要安装python和numpy. 首先回顾一下机器学习的东西,定义一 ...

  2. Theano入门神经网络(四)

    这一部分主要介绍用Theano 实现softmax函数. 在多分类任务中经常用到softmax函数,首先上几个投影片解释一下 假设目标输出是y_hat ,激活函数后的Relu y 一个是1.2 一个是 ...

  3. Theano入门神经网络(二) 实现一个XOR门

    与非门的图片如下 示意图 详细解释: 1 定义变量的代码,包括了输入.权值.输出等.其中激活函数采用的是sigmod函数 # -*- coding: utf-8 -*- __author__ = 'A ...

  4. Theano入门——CIFAR-10和CIFAR-100数据集

    Theano入门——CIFAR-10和CIFAR-100数据集 1.CIFAR-10数据集介绍 CIFAR-10数据集包含60000个32*32的彩色图像,共有10类.有50000个训练图像和1000 ...

  5. 无废话ExtJs 入门教程三[窗体:Window组件]

    无废话ExtJs 入门教程三[窗体:Window组件] extjs技术交流,欢迎加群(201926085) 1.代码如下: 1 <!DOCTYPE html PUBLIC "-//W3 ...

  6. RequireJS入门(三)转

    这篇来写一个具有依赖的事件模块event.event提供三个方法bind.unbind.trigger来管理DOM元素事件. event依赖于cache模块,cache模块类似于jQuery的$.da ...

  7. RequireJS入门(三)

    这篇来写一个具有依赖的事件模块event.event提供三个方法bind.unbind.trigger来管理DOM元素事件. event依赖于cache模块,cache模块类似于jQuery的$.da ...

  8. 【SSRS】入门篇(三) -- 为报表定义数据集

    原文:[SSRS]入门篇(三) -- 为报表定义数据集 通过前两篇文件 [SSRS]入门篇(一) -- 创建SSRS项目 和 [SSRS]入门篇(二) -- 建立数据源 后, 我们建立了一个SSRS项 ...

  9. Bootstrap入门(三十)JS插件7:警告框

    Bootstrap入门(三十)JS插件7:警告框 通过这个插件可以为警告信息添加点击以及消失的功能. 当使用一个.close按钮,它必须是第一个子元素.alert-dismissible,并没有文字内 ...

随机推荐

  1. [leetcode 27]Implement strStr()

    1 题目: Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if ...

  2. mac下android环境搭建笔记(android studio)

    本文记录了本人在mac上配置android开发环境的一些过程,为了方便直接选用了官方的IDE– Android Studio .本文包括了android studio的安装.创建第一个hello wo ...

  3. 前端自动化测试工具doh学习总结(二)

    一.robot简介 robot是dojo框架中用来进行前端自动化测试的工具,doh主要目的在于单元测试,而robot可以用来模仿用户操作来测试UI.总所周知,Selenium也是一款比较流行的前端自动 ...

  4. 谈谈.net模块依赖关系及程序结构

    技术为解决问题而生. 上面这个命题并非本文重点,我将来有空再谈这个.本文也并非什么了不起的技术创新,只是分享一下我对.net模块依赖关系及程序结构方面的一些看法.先看一个最最简单的hello worl ...

  5. [ACM_几何] Fishnet

      http://acm.hust.edu.cn/vjudge/contest/view.action?cid=28417#problem/C 本题大意:有一个1X1的矩形,每边按照从小到大的顺序给n ...

  6. 使用CSS sprites减少HTTP请求

    sprites是鬼怪,小妖精,调皮鬼的意思,初听这个高端洋气的名字我被震慑住了,一步步掀开其面纱后发觉很简单的东西,作用却很大 神马是CSS 小妖精 CSS sprites是指把网页中很多小图片(很多 ...

  7. axis

    http://www.cnblogs.com/liyanblog/archive/2011/11/29/2266942.html 报错: D:\ws\la\WSofSMNS\WebRoot\WEB-I ...

  8. 深度解析SDN——利益、战略、技术、实践(实战派专家力作,业内众多专家推荐)

    深度解析SDN——利益.战略.技术.实践(实战派专家力作,业内众多专家推荐) 张卫峰 编   ISBN 978-7-121-21821-7 2013年11月出版 定价:59.00元 232页 16开 ...

  9. 《Wireshark数据包分析实战》 - http背后,tcp/ip抓包分析

    作为网络开发人员,使用fiddler无疑是最好的选择,方便易用功能强. 但是什么作为爱学习的同学,是不应该止步于http协议的,学习wireshark则可以满足这方面的需求.wireshark作为抓取 ...

  10. spring 学习

    一.spring框架介绍 Spring 是一个开源框架,是为了解决企业应用程序开发复杂性而创建的.框架的主要优势之一就是其分层架构,分层架构允许您选择使用哪一个组件,同时为 J2EE 应用程序开发提供 ...