60个字符解决fizzbuzz问题:

for x in range(101):print"fizz"[x%3*4::]+"buzz"[x%5*4::]or x

下面是用tensorflow解决,跟上面的比起来非常复杂,但很有意思,而且适合学习tensorflow,发散一下思维,拓展tensorflow的应用范围。

tensorflow 应用fizzbuzz

转载请注明地址:http://www.cnblogs.com/SSSR/p/5630497.html

直接上代码如下:

具体案例解释请参考:http://joelgrus.com/2016/05/23/fizz-buzz-in-tensorflow/

# -*- coding: utf-8 -*-
"""
Created on Wed Jun 29 10:57:41 2016@author: ubuntu
"""# Fizz Buzz in Tensorflow!
# see http://joelgrus.com/2016/05/23/fizz-buzz-in-tensorflow/import numpy as np
import tensorflow as tfNUM_DIGITS = 10# Represent each input by an array of its binary digits.
def binary_encode(i, num_digits):return np.array([i >> d & 1 for d in range(num_digits)])# One-hot encode the desired outputs: [number, "fizz", "buzz", "fizzbuzz"]
def fizz_buzz_encode(i):if   i % 15 == 0: return np.array([0, 0, 0, 1])elif i % 5  == 0: return np.array([0, 0, 1, 0])elif i % 3  == 0: return np.array([0, 1, 0, 0])else:             return np.array([1, 0, 0, 0])# Our goal is to produce fizzbuzz for the numbers 1 to 100. So it would be
# unfair to include these in our training data. Accordingly, the training data
# corresponds to the numbers 101 to (2 ** NUM_DIGITS - 1).
trX = np.array([binary_encode(i, NUM_DIGITS) for i in range(101, 2 ** NUM_DIGITS)])
trY = np.array([fizz_buzz_encode(i)          for i in range(101, 2 ** NUM_DIGITS)])# We'll want to randomly initialize weights.
def init_weights(shape):return tf.Variable(tf.random_normal(shape, stddev=0.01))# Our model is a standard 1-hidden-layer multi-layer-perceptron with ReLU
# activation. The softmax (which turns arbitrary real-valued outputs into
# probabilities) gets applied in the cost function.
def model(X, w_h, w_o):h = tf.nn.relu(tf.matmul(X, w_h))return tf.matmul(h, w_o)# Our variables. The input has width NUM_DIGITS, and the output has width 4.
X = tf.placeholder("float", [None, NUM_DIGITS])
Y = tf.placeholder("float", [None, 4])# How many units in the hidden layer.
NUM_HIDDEN = 100# Initialize the weights.
w_h = init_weights([NUM_DIGITS, NUM_HIDDEN])
w_o = init_weights([NUM_HIDDEN, 4])# Predict y given x using the model.
py_x = model(X, w_h, w_o)# We'll train our model by minimizing a cost function.
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(py_x, Y))
train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost)# And we'll make predictions by choosing the largest output.
predict_op = tf.argmax(py_x, 1)# Finally, we need a way to turn a prediction (and an original number)
# into a fizz buzz output
def fizz_buzz(i, prediction):return [str(i), "fizz", "buzz", "fizzbuzz"][prediction]BATCH_SIZE = 128# Launch the graph in a session
with tf.Session() as sess:tf.initialize_all_variables().run()for epoch in range(10000):# Shuffle the data before each training iteration.p = np.random.permutation(range(len(trX)))trX, trY = trX[p], trY[p]# Train in batches of 128 inputs.for start in range(0, len(trX), BATCH_SIZE):end = start + BATCH_SIZEsess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end]})# And print the current accuracy on the training data.print(epoch, np.mean(np.argmax(trY, axis=1) ==sess.run(predict_op, feed_dict={X: trX, Y: trY})))# And now for some fizz buzznumbers = np.arange(1, 101)teX = np.transpose(binary_encode(numbers, NUM_DIGITS))teY = sess.run(predict_op, feed_dict={X: teX})output = np.vectorize(fizz_buzz)(numbers, teY)print(output)

  

转载于:https://www.cnblogs.com/SSSR/p/5630497.html

tensorflow 应用fizzbuzz相关推荐

  1. Tensorflow学习——Eager Execution

    Eager Execution 目录 1.设置和基本用法 2.动态控制流 3.构建模型 4.Eager训练 计算梯度 训练模型 变量和优化器 5.在Eager Execution期间将对象用于状态 变 ...

  2. tensorflow 1.x Saver(保存与加载模型) 预测

    20201231 tensorflow 1.X 模型保存 https://blog.csdn.net/qq_35290785/article/details/89646248 保存模型 saver=t ...

  3. python 虚拟环境 tensorflow GPU

    拿到一个新的容器之后,怎么创建一个独立的GPU训练环境呢?之前弄的时候总是零零散散的,现在把它总结在这里,供自己以及有需要的朋友查阅. conda创建 1.1 下载anaconda wget -c h ...

  4. API pytorch tensorflow

    pytorch与tensorflow API速查表 方法名称 pytroch tensorflow numpy 裁剪 torch.clamp(x, min, max) tf.clip_by_value ...

  5. tensor转换 pytorch tensorflow

    一.tensorflow的numpy与tensor互转 1.数组(numpy)转tensor 利用tf.convert_to_tensor(numpy),将numpy转成tensor >> ...

  6. Tensorflow会话

    Tensorflow中的会话是来执行定义好的运算的.会话拥有并管理Tensorflow程序运行时的所有资源.当计算完成之后需要关闭会话来帮助系统回收资源,否则可能出现资源泄露的问题. Tensorfl ...

  7. tensorflow问题

    20210121 ImportError: No module named 'tensorflow.python' https://stackoverflow.com/questions/414156 ...

  8. tensorflow兼容处理 tensorflow.compat.v1 tf.contrib

    20201130 问题提出: v1版本中tensorflow中contrib模块十分丰富,但是发展不可控,因此在v2版本中将这个模块集成到其他模块中去了.在学习tensorflow经常碰到tf.con ...

  9. ImportError: No module named tensorflow.compat.v1 忽略已经安装的某个包版本 忽略已安装版本...

    ImportError: No module named tensorflow.compat.v1 版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声 ...

最新文章

  1. 深入理解Nginx工作原理
  2. 如何将usb连接到远程计算机,远程服务器怎么共享usb
  3. .NET Core使用FluentEmail发送邮件
  4. 用C语言实现:判断1000-2000年之间的闰年。
  5. C语言的struct和C++的class的区别
  6. Silverlight 异步单元测试
  7. jprofiler安装与使用
  8. Python精通-Python元组操作
  9. [Python+sklearn] 拆分数据集为训练和测试子集 sklearn.model_selection.train_test_split()
  10. Java中如何在窗口加一行字,如何在java中实现读文件(一行一行地读)和写文件(一行一行地追加写)...
  11. C#中获去一个字符串中的汉字的个数 C#获取字符串全角的个数
  12. it技术交流平台_IT协会向你招手了,不了解了解?
  13. [渝粤教育] 广东-国家-开放大学 21秋期末考试大学英语210262k2
  14. C#|GMap.NET控件基本使用-高德地图
  15. Unity3d发布WebPlayer版本遇到的问题的解决方法
  16. java实习生面试题
  17. 长沙优科软件开发有限公司招聘软件开发工程师
  18. CS5532 C51驱动程序
  19. 《全民学乒乓》学习笔记
  20. C语言编程b a化简,C语言编程,已知三角形的三边长a,b,c,计算求三角... 如果三角形三边长 a,b,c,满足( )那么这个三角形......

热门文章

  1. 雷赛运动控制卡_EeIE智博会展商推荐雷赛智能—智能装备运动控制领域的知名品牌和行业领军企业...
  2. Linux怎么调oracle存储,Linux 环境下Oracle安装与调试(四)之视图、存储过程
  3. mysql 树表查询所有子节点
  4. eclipse 设置workspace编码格式
  5. android o测试版,一加手机可升级!谷歌已正式推送Android O测试版系统
  6. python众数问题给定含有n个元素的多重集合s_2-1 问题描述:给定含有n个元素的多重集合S - 下载 - 搜珍网...
  7. python如何使用session和cookie_Python爬虫番外篇之Cookie和Session-阿里云开发者社区
  8. linux 引导程序修复工具,技术|Linux下修改引导器的工具:Boot-Repair
  9. html怎样使图片不占位子,复式客厅上阁楼楼梯安装什么位置不占地方 最节约空间的阁楼楼梯设计图片...
  10. 最优化方法外罚函数法Matlab,最优化方法 第三篇(罚函数法).pdf