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]))

最新文章

  1. Java开发环境搭建——Tomcat配置
  2. 利用Javascript判断操作系统的类型实现不同操作系统下的兼容性
  3. sqlserver索引与查询优化
  4. DataTable 和Json 字符串互转
  5. QDir路径的测试与创建-QT
  6. WIN7 如何关闭Aero
  7. 【腾讯Bugly干货分享】RecyclerView 必知必会
  8. BIT_COUNT()和BIT_OR()
  9. 动态Pivot(1)
  10. Get started - UIkit documentation
  11. 实用 .htaccess 用法大全
  12. centos6.5下redis安装步骤总结
  13. ubuntu12.04添加程序启动器到Dash Home
  14. git体验
  15. css--nth-child的注意点
  16. 《React Native 精解与实战》书籍连载「React 与 React Native 简介」
  17. python文档生成工具:pydoc、sphinx;django如何使用sphinx?
  18. 读写appSettings配置节方法
  19. jQuery使用cookie与json简单实现购物车功能
  20. window 下相关命令

热门文章

  1. hive复杂类型实战
  2. 【css】max-height,min-height,height一起使用时,优先级问题
  3. pytorch visdom可视化工具学习—1—详细使用-3-Generic Plots和Others
  4. Servlet简单概念和开发小总结
  5. 十二省联考 - JLOI2019 游记
  6. zookeepeer使用java api
  7. Java性能优化之String字符串优化
  8. SQL Server 分析函数和排名函数
  9. 容器互联(linking)
  10. Linq中比较字符串类型的日期