【Python-ML】神经网络-Theano张量库(GPU版的Numpy)
2018-01-26 17:06
399 查看
# -*- coding: utf-8 -*- ''' Created on 2018年1月26日 @author: Jason.F @summary: pip install Theano, Theano,对于张量能够高效地实现、编译和评估数学表达式,支持在GPU上运行,利用GPU中巨大内存带宽及浮点数运算能力 实现一个基于最小二乘法的线性回归 ''' import theano from theano import tensor as T import numpy as np import matplotlib.pyplot as plt print(theano.config.floatX)#查看浮点变量的设置 theano.config.floatX='float32' print(theano.config.device)#查看是在CPU还是GPU上 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) def train_linreg(X_train,y_train,eta,epochs): costs=[] #initial arrays 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') #calculate cost net_input = T.dot(X,w[1:])+w[0] errors=y-net_input cost = T.sum(T.pow(errors,2)) #perform gradient update gradient = T.grad(cost,wrt=w) update =[(w,w-eta0*gradient)] #compile model train = theano.function(inputs=[eta0],outputs=cost,updates=update,givens={X:X_train,y:y_train}) for _ in range(epochs): costs.append(train(eta)) return costs,w 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() 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) 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()
结果:
相关文章推荐
- 用python的numpy实现神经网络 实现 手写数字识别
- 神经网络环境python2.7+tensorflow(gpu)+keras+cuda toolkit8.0+cudnn5.1+anaconda(ubuntu 16.04desktop64位)
- 【Python-ML】神经网络-多层感知器增加梯度检验
- 【Python-ML】神经网络-多层感知器
- 【Python-ML】神经网络激励函数-Sigmoid
- 神经网络与深度学习第二周-1- Python Basics With Numpy
- Coursera 深度学习 deep learning.ai 吴恩达 神经网络和深度学习 第一课 第二周 编程作业 Python Basics with Numpy
- 【Python-ML】自适应线性神经网络(Adaline)
- 【Python-ML】神经网络激励函数-Softmax
- Python基于numpy灵活定义神经网络结构的方法
- 【Python-ML】神经网络-深度学习库Keras
- 【Python-ML】神经网络激励函数-双曲正切(hyperbolic tangent,tanh)函数
- 循环神经网络教程-第二部分 用python numpy theano实现RNN
- 《神经网络和深度学习》之神经网络基础(第二周)课后作业——Python与Numpy基础知识
- coursera 吴恩达 -- 第一课 神经网络和深度学习 :第二周课后习题 Python Basics with numpy (optional)
- [置顶] 用Python+numpy实现单隐层神经网络
- 循环神经网络教程第二部分-用python,numpy,theano实现一个RNN
- 循环神经网络在Python 、Numpy和Theano中的实现
- 神经网络与深度学习学习笔记:numpy基础
- python构建深度神经网络(DNN)续