莫烦theano学习自修第八天【分类问题】
2024-08-20 02:39:34
1. 代码实现
from __future__ import print_function import numpy as np import theano import theano.tensor as T def compute_accuracy(y_target, y_predict): correct_prediction = np.equal(y_predict, y_target) accuracy = np.sum(correct_prediction)/len(correct_prediction) return accuracy rng = np.random N = 400 # training sample size feats = 784 # number of input variables # generate a dataset: D = (input_values, target_class) D = (rng.randn(N, feats), rng.randint(size=N, low=0, high=2)) # Declare Theano symbolic variables x = T.dmatrix("x") y = T.dvector("y") # initialize the weights and biases W = theano.shared(rng.randn(feats), name="w") b = theano.shared(0., name="b") # Construct Theano expression graph p_1 = T.nnet.sigmoid(T.dot(x, W) + b) # Logistic Probability that target = 1 (activation function) prediction = p_1 > 0.5 # The prediction thresholded xent = -y * T.log(p_1) - (1-y) * T.log(1-p_1) # Cross-entropy loss function # or # xent = T.nnet.binary_crossentropy(p_1, y) # this is provided by theano cost = xent.mean() + 0.01 * (W ** 2).sum()# The cost to minimize (l2 regularization) gW, gb = T.grad(cost, [W, b]) # Compute the gradient of the cost # Compile learning_rate = 0.1 train = theano.function( inputs=[x, y], outputs=[prediction, xent.mean()], updates=((W, W - learning_rate * gW), (b, b - learning_rate * gb))) predict = theano.function(inputs=[x], outputs=prediction) # Training for i in range(500): pred, err = train(D[0], D[1]) if i % 50 == 0: print('cost:', err) print("accuracy:", compute_accuracy(D[1], predict(D[0]))) print("target values for D:") print(D[1]) print("prediction on D:") print(predict(D[0]))
最新文章
- Java开发环境搭建——Tomcat配置
- 利用Javascript判断操作系统的类型实现不同操作系统下的兼容性
- sqlserver索引与查询优化
- DataTable 和Json 字符串互转
- QDir路径的测试与创建-QT
- WIN7 如何关闭Aero
- 【腾讯Bugly干货分享】RecyclerView 必知必会
- BIT_COUNT()和BIT_OR()
- 动态Pivot(1)
- Get started - UIkit documentation
- 实用 .htaccess 用法大全
- centos6.5下redis安装步骤总结
- ubuntu12.04添加程序启动器到Dash Home
- git体验
- css--nth-child的注意点
- 《React Native 精解与实战》书籍连载「React 与 React Native 简介」
- python文档生成工具:pydoc、sphinx;django如何使用sphinx?
- 读写appSettings配置节方法
- jQuery使用cookie与json简单实现购物车功能
- window 下相关命令