赞
踩
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
num_points = 1000
vectors_set = []
for i in range(num_points):
x1 = np.random.normal(0.0, 0.55)
y1 = x1 * 0.1 + 0.3 + np.random.normal(0.0, 0.03)#给这些点加一些抖动
vectors_set.append([x1, y1])
x_data = [v[0] for v in vectors_set]
y_data = [v[1] for v in vectors_set]
plt.scatter(x_data,y_data,c=‘r’)
plt.show()
W = tf.Variable(tf.random_uniform([1], -1.0, 1.0), name=‘W’)#随机初始化权重参数-1到1之间
b = tf.Variable(tf.zeros([1]), name=‘b’)#以0为初始化,[1]表示维度
y = W * x_data + b#目标函数
loss = tf.reduce_mean(tf.square(y - y_data), name=‘loss’)#reduce_mean平均值
optimizer = tf.train.GradientDescentOptimizer(0.5)#学习率大了
train = optimizer.minimize(loss, name=‘train’)
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
print (“W =”, sess.run(W), “b =”, sess.run(b), “loss =”, sess.run(loss))
for step in range(20):
sess.run(train)
# 输出训练好的W和b
print (“W =”, sess.run(W), “b =”, sess.run(b), “loss =”, sess.run(loss))
#writer = tf.train.SummaryWriter("./tmp", sess.graph)
plt.scatter(x_data,y_data,c=‘r’)
plt.plot(x_data,sess.run(W)*x_data+sess.run(b))
plt.show()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。