附录一个: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. [Xamarin] 取得所有已安裝軟體清單 (转帖)

    最近會用到,簡單記錄一下,抓取所有該手機已經安裝的軟體清單 結果圖: 首先介紹一下Layout :  \Resources\Layout\Main.axml <?xml version=&quo ...

  2. hadoop+hive使用中遇到的问题汇总

    问题排查方式  一般的错误,查看错误输出,按照关键字google 异常错误(如namenode.datanode莫名其妙挂了):查看hadoop($HADOOP_HOME/logs)或hive日志 h ...

  3. Oracle Enterprise Manager打不开的解决方法

    之前OEM一直可以打开,但今天上班发现打不开了,输入http://localhost:1158/em 提示该网页无法打开. 那么检查一下: cmd进命令行 C:\Documents and Setti ...

  4. Java多线程18:线程池

    使用线程池与不使用线程池的差别 先来看一下使用线程池与不适应线程池的差别,第一段代码是使用线程池的: public static void main(String[] args) { long sta ...

  5. 一个App完成入门篇(二)-搭建主框架

    通过第一课的学习,你已经掌握了如何通过debug调试器来跟PC上的设计器联调来实时查看UI设计效果.调试代码了,接下来通过一系列的demo开发教学你将很快上手学习到如何开发一个真正的App. 要开发A ...

  6. git 合并分支

    当前git有PreRelease和Release两个分支,现在需要将前者合并到后者. Clone版本 在本地clone一个目标工程. 然后右键 Tortoise-->Switch/Checkou ...

  7. [.net 面向对象编程基础] (21) 委托

    [.net 面向对象编程基础] (20)  委托 上节在讲到LINQ的匿名方法中说到了委托,不过比较简单,没了解清楚没关系,这节中会详细说明委托. 1. 什么是委托? 学习委托,我想说,学会了就感觉简 ...

  8. python Web开发框架-Django (1)

    以前用web.py(另外一款轻量级web开发框架)做一个监控管理平台,没有做特别的记录就不好拾起来.最近做一个日志聚合系统,使用的是django,这次就记下来,方便查询. Django是一个高效的we ...

  9. java.sql.SQLException: JZ00L

    出现, java.sql.SQLException: JZ00L: 登录失败.检查与此异常现象有关的 SQL 警告以获得失败原因. at com.sybase.jdbc3.jdbc.ErrorMess ...

  10. php实现注册

    <?php header("Content-Type:text/html;charset=gb2312"); @mysql_connect('localhost','root ...