tensorflow学习笔记一——模拟一条直线方程
来源:互联网 发布:上海知贤装饰 编辑:程序博客网 时间:2024/05/16 07:04
Session
Session在tensorflow中就像指针一样,指向需要运行的代码。Session运行结束后,需要关闭,可以利用with来自动完成。
from __future__ import print_functionimport tensorflow as tfmatrix1 = tf.constant([[3, 3]])matrix2 = tf.constant([[2], [2]])product = tf.matmul(matrix1, matrix2) # matrix multiply np.dot(m1, m2)# method 1sess = tf.Session()result = sess.run(product)print(result)sess.close()# method 2with tf.Session() as sess: result2 = sess.run(product) print(result2)
变量
在tensorflow中,变量通过Variable函数来定义。并且一定要运行initialize_all_variables()来初始化所有变量。
from __future__ import print_functionimport tensorflow as tfstate = tf.Variable(0, name='counter')#print(state.name)one = tf.constant(1)new_value = tf.add(state, one)update = tf.assign(state, new_value)#该操作是将new_value的值赋给state.不可以用state = new_value代替init = tf.initialize_all_variables() # must have if define variablewith tf.Session() as sess: sess.run(init) for _ in range(3): sess.run(update) print(sess.run(state))
占位符
在tensorflow中,有一部分的变量是在输入的时候才能确定的,所以可以使用占位符来先定义对这类数据的操作。
from __future__ import print_functionimport tensorflow as tfinput1 = tf.placeholder(tf.float32)input2 = tf.placeholder(tf.float32)ouput = tf.mul(input1, input2)with tf.Session() as sess: print(sess.run(ouput, feed_dict={input1: [7.], input2: [2.]}))
模拟直线
本次利用神经网络学习来趋近一条直线方程y = 0.1x + 0.3.代码如下:
from __future__ import print_functionimport tensorflow as tfimport numpy as np# create datax_data = np.random.rand(100).astype(np.float32)y_data = x_data*0.1 + 0.3### create tensorflow structure start ###Weights = tf.Variable(tf.random_uniform([1], -1.0, 1.0))biases = tf.Variable(tf.zeros([1]))y = Weights*x_data + biases loss = tf.reduce_mean(tf.square(y-y_data))optimizer = tf.train.GradientDescentOptimizer(0.5)train = optimizer.minimize(loss)init = tf.initialize_all_variables()### create tensorflow structure end ###sess = tf.Session()sess.run(init) # Very importantfor step in range(201): sess.run(train) if step % 20 == 0: print(step, sess.run(Weights), sess.run(biases))
tf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32, seed=None, name=None)用这个函数初始化W,得到一个一维的,取值范围在-1到1的数组,本例中就是一个数字。初始化biase为0。
y为预测的值,y_data是正确的值,通过计算两者的差值的平方作为误差,然后用梯度下降使得误差最小。
0 0
- tensorflow学习笔记一——模拟一条直线方程
- TensorFlow拟合一条直线
- tensorflow学习笔记(一)——tensorflow基本使用
- TensorFlow学习笔记(一)
- TensorFlow学习笔记(一)
- tensorflow学习笔记一
- TensorFlow官方教程学习笔记(一)——起步
- TensorFlow学习笔记(一)——快速上手
- Tensorflow学习笔记(一):初识TensorFlow——实现线性回归
- TensorFlow学习笔记(一):TensorFlow安装
- tensorflow学习笔记(一):tensorflow安装
- TensorFlow学习笔记(一)
- tensorflow学习笔记(一)
- TensorFlow学习笔记(一)
- TensorFlow学习笔记(一)
- Tensorflow学习笔记(一)
- tensorflow学习笔记(一)
- 人工智能学习笔记-TensorFlow(一)
- 见证微信小程序之火热
- Spring 定时器Quartz的用法
- github上的一些js及jq插件分享
- PHP基础教程三之运算符
- hive优化:基于map数和reduce数
- tensorflow学习笔记一——模拟一条直线方程
- 第4周实践项目2--建设“单链表”算法库
- 第四周 项目4-猴子选大王
- centos6.6下nginx配置远程服务器上图片访问
- SQLSERVER SQLServer通过端口1433 连接到主机的TCP/IP方法
- Sublime常用插件
- Linux安装jdk1.7和tomcat9版本不匹配引起的错误
- 第四周 猴子选大王
- SDK代理服务器解决国内不能更新下载问题