Tensorflow入门(3)——小练习(单词统计、1+...+n、矩阵运算)
一、罗密欧与朱丽叶
统计 THE TRAGEDY OF ROMEO AND JULIET (罗密欧与朱丽叶)英文小说中各单词出现的次数
import re
import collections
import pandas as pd
# 读取文件
filename = '罗密欧与朱丽叶(英文版)莎士比亚.txt'
content=open(filename).read()
word=re.compile(r'\W+')
# 转换为小写字母
words=word.split(content.upper())
# 计数各单词次数
words_count=collections.Counter(words)
# 输出要求的各单词次数
words_list=['THE','TRAGEDY','OF','ROMEO','AND','JULIET']
times=[]
for i in range(len(words_list)):
temp=words_list[i]
print('文中出现',temp,'(不区分大小写):',words_count[temp],"次")
times.append(words_count[temp])
# 表格显示并降序
data = pd.DataFrame({'word':words_list,'times':times})
data = data.sort_values('times', ascending=[False])
print(data)
二、1+...+10
要求:
1)通过TensorFlow来进行计算,必须要用到tf.Variable、tf.constant,正确定义了相关常量、变量和操作;
2)进行了变量初始化,能通过计算正常输出结果;
import tensorflow as tf
import os
# 定义常量1,被加数:value与总和:result
value=tf.Variable(0,name="value")
result=tf.Variable(0,name="value")
one=tf.constant(1)
# 更新
new_value=tf.add(value,one)
update_value=tf.assign(value,new_value)
new_result=tf.add(result,value)
update_result=tf.assign(result,new_result)
# 初始化
sess=tf.Session()
sess.run(tf.global_variables_initializer())
# 循环相加
for i in range(10):
sess.run(update_value)
sess.run(update_result)
print('round',i+1,':sum ',sess.run(result))
print('\n从 1 +...+10的和为:',sess.run(result))
# 关闭对话
sess.close()
三、输入n,求1+...+n的和
要求:
1)通过TensorFlow来进行计算,必须要用到tf.Variable、tf.constant,tf.placeholder,正确定义了相关常
量、变量、占位符和操作;
2)正整数n由用户在运行时输入;
3)能正确计算1+2+...+n的值;
import tensorflow as tf
import os
# 占位符
n=tf.placeholder(tf.int32, name='n')
# 被加数value,结果result,常数one
value=tf.Variable(0,name="value")
result=tf.Variable(0,name="value")
one=tf.constant(1,name="one")
# 更新
new_value=tf.add(value,one)
update_value=tf.assign(value,new_value)
new_result=tf.add(result,n)
update_result=tf.assign(result,new_result)
# 初始化
sess=tf.Session()
sess.run(tf.global_variables_initializer())
# 输入n
temp = int(input("请输入一个正整数n:"))
# 循环相加
for i in range(temp):
r=sess.run(update_result,feed_dict={n:sess.run(update_value)})
print('\n从 1 +...+',temp,'的和为:',sess.run(result))
# 关闭对话
sess.close()
四、模拟矩阵运算
要求:
1)请用Tensorflow框架,模拟一下[[1.0, 2.0], [3.0, 4.0]] + [[5, 6], [7, 8]] * 9 – 10E的运算,并输出结果。(E为单位矩阵,乘法为矩阵乘)
import tensorflow as tf
a = tf.Variable([[1.0, 2.0], [3.0, 4.0]], dtype=tf.float32)
b = tf.Variable([[5.0, 6.0], [7.0, 8.0]], dtype=tf.float32)
e = tf.eye(2)
res1=a+b
res2=res1*9
res3=res2-10*e
# res1=tf.add(a, b, name=None)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print("矩阵相加结果:\n",sess.run(res1))
print("结果矩阵*9:\n",sess.run(res2))
print("最终结果:\n",sess.run(res3))

浙公网安备 33010602011771号