|
使用tensorflow进行简单的线性回归 标签(空格分隔): tensorflow 数据准备- 使用np.random.uniform()生成x方向的数据
- 使用np.random.uniform()生成bias数据
- 直线方程为y=0.1x + 0.2
- 使用梯度下降算法
代码- <font size="5">import numpy as np
- import tensorflow as tf
- path = 'D:\tensorflow_quant\ailib\log_tmp'
- # 生成x数据
- points = 100
- vectors = []
- for i in range(points): # y=0.1*x + 0.2
- x = np.random.uniform(0, 0.66)
- y = x * 0.1 + 0.2 + np.random.uniform(0, 0.04)
- vectors.append([x, y])
- x_data = [v[0] for v in vectors]
- y_data = [v[1] for v in vectors]
- #形成计算图
- w = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
- b = tf.Variable(tf.zeros([1]))
- y = w * x_data + b
- #定义损失函数
- loss = tf.reduce_mean(tf.square(y-y_data))
- #定义优化器
- optimizer = tf.train.GradientDescentOptimizer(0.5)
- train = optimizer.minimize(loss)
- #对计算图开始计算
- with tf.Session() as sess:
- init = tf.global_variables_initializer()
- sess.run(init)
- for step in range(1000):
- sess.run(train)
- if step%5==0:
- print(step,sess.run(loss),sess.run(w),sess.run(b))
- #生成计算日志
- writer = tf.Summary.FileWriter(path,sess.graph)</font>
复制代码
|
|