本文共 1472 字,大约阅读时间需要 4 分钟。
主要是得注意输入的数据格式和placeholder的用法,当然了,还有weights和bias的初始化
import tensorflow as tfimport numpy as npimport matplotlib.pyplot as pltimport osos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'x = np.linspace(-10, 10, 50)[:, np.newaxis]noise = np.random.normal(0, 0.5, x.shape)y=x*0.5+noise #加上一个0~1内的随机数。用来模拟噪声w=tf.Variable(tf.random_normal([1,1]))b=tf.Variable(tf.zeros([1,1]))#定义权重x_input=tf.placeholder(tf.float32, [None, 1])y_output=tf.placeholder(tf.float32, [None, 1])# y_predict=w*x+b### plt.figure()# plt.scatter(x,y,c='green',s=50,marker='o')#散点图# plt.plot(x, y, color="red") #画一条直线# plt.show()#5个样本作为一个batchdef get_next_batch(): train_indices=np.random.choice(range(len(x)),50) train_x=x[train_indices] train_y=y[train_indices] return train_x,train_ydef output(): y_predict=tf.add(tf.matmul(x_input,w),b) return y_predictsess=tf.Session()y_predict=output()loss=(tf.reduce_mean(tf.reduce_sum(tf.square(y_output-y_predict))))/50train=tf.train.GradientDescentOptimizer(0.005).minimize(loss)init=tf.global_variables_initializer()sess.run(init)print(sess.run(w))print('_______')for i in range(100): #500次迭代 train_x,train_y=get_next_batch() sess.run(train,feed_dict={x_input:train_x,y_output:train_y}) if i%30==0: result_w=sess.run(w) result_b=sess.run(b) y_predict=result_w[0][0]*x+result_b plt.figure() plt.scatter(x,y,c='green',s=50,marker='o')#散点图 plt.plot(x, y_predict, color="red") #画一条直线 plt.show()
转载地址:http://yukmi.baihongyu.com/