TF——线性回归
注释很清楚:
1 import tensorflow as tf 2 import os 3 import numpy as np 4 import matplotlib.pyplot as plt 5 os.environ["CUDA_VISIBLE_DEVICES"]="0" 6 learning_rate=0.01 7 training_epochs=1000 8 display_step=50 9 if __name__ =='__main__': 10 train_X = np.asarray( 11 [3.3, 4.4, 5.5, 6.71, 6.93, 4.168, 9.779,6.182,7.59,2.167,7.042,10.791,5.313,7.997,5.654,9.27,3.1]) 12 train_Y = np.asarray( 13 [1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,2.827,3.465,1.65,2.904,2.42,2.94,1.3]) 14 n_sample=train_X.shape[0]#维度——几行 15 print(n_sample) 16 '''变量''' 17 X=tf.placeholder("float") 18 Y=tf.placeholder("float") 19 '''模型''' 20 W=tf.Variable(np.random.randn(),name="weight")#标准正态分布 21 b = tf.Variable(np.random.randn(), name="bias") 22 '''线性回归模型 23 pred=x*k+b 24 ''' 25 mul=tf.multiply(X,W) 26 pred=tf.add(mul,b) 27 28 '''标准方差: 29 z=(Y-y)^2+...../n 30 ''' 31 print(2*n_sample) 32 cost=tf.reduce_sum(tf.pow(pred-Y,2))/(2*n_sample) 33 34 '''梯度下降法 去最小值,获得最有解''' 35 optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) 36 init = tf.global_variables_initializer() 37 with tf.Session() as sess: 38 sess.run(init) 39 '''训练模型''' 40 for epoch in range(training_epochs): 41 for(x,y) in zip(train_X,train_Y): 42 sess.run(optimizer,feed_dict={X:x,Y:y}) 43 44 if(epoch+1)%display_step==0: 45 c=sess.run(cost,feed_dict={X:train_X,Y:train_Y}) 46 print("训练次数:", '%04d' % (epoch + 1), 47 "标准差=", "{:.9f}".format(c), 48 "斜率=", sess.run(W), 49 "截距=",sess.run(b)) 50 print("PPPPPPPPPPPPPPPPPPPPPPPPP") 51 training_cost = sess.run(cost, feed_dict={X: train_X, Y: train_Y}) 52 print("标准差=", training_cost, "斜率=", sess.run(W), "截距=", sess.run(b)) 53 plt.plot(train_X,train_Y,'ro',label="DATA") 54 plt.plot(train_X, sess.run(W)*train_X+sess.run(b), label="Line",color="blue") 55 plt.legend() 56 plt.show()