tensorflow学习
ref: 周莫烦 https://www.youtube.com/watch?v=JKR1Dxinwwc&list=PLXO45tsB95cKI5AIlf5TxxFPzb-0zeVZ8&index=8
1.训练y=0.1x+0.3表达式的中的w和b
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import tensorflow as tf import numpy as np #create data x_data=np.random.rand(100).astype(np.float32) y_data=x_data*0.1+0.3 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() with tf.Session() as sess: sess.run(init) for step in range(201): sess.run(train); if(step%20==0): print(step,sess.run(Weights),sess.run(biases))
2.placeholder的使用
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import tensorflow as tf input1=tf.placeholder(tf.float32) input2=tf.placeholder(tf.float32) output=tf.multiply(input1,input2) with tf.Session() as sess: print(sess.run(output,feed_dict={input1:[7.0],input2:[2.0]}))
3.简单的神经网络(包含画图)
用于y=x^2-0.5
一些随机数生成函数的区别:链接
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt def add_layer(inputs,in_size,out_size,activation_function=None): Weights=tf.Variable(tf.random_normal([in_size,out_size])) biases=tf.Variable(tf.zeros([1,out_size])+0.1) Wx_plus_b=tf.matmul(inputs,Weights)+biases if activation_function==None: outputs=Wx_plus_b else: outputs=activation_function(Wx_plus_b) return outputs x_data=np.linspace(-1,1,300)[:,np.newaxis] noise=np.random.normal(0,0.05,x_data.shape) y_data=np.square(x_data)-0.5+noise xs=tf.placeholder(tf.float32,[None,1]) ys=tf.placeholder(tf.float32,[None,1]) l1=add_layer(xs,1,10,activation_function=tf.nn.relu) prediction=add_layer(l1,10,1,activation_function=None) loss=tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),reduction_indices=[1])) train_step=tf.train.GradientDescentOptimizer(0.1).minimize(loss) init=tf.initialize_all_variables() sess=tf.Session() sess.run(init) fig=plt.figure() ax=fig.add_subplot(1,1,1) ax.scatter(x_data,y_data) plt.ion() plt.show() for i in range(1001): sess.run(train_step,feed_dict={xs:x_data,ys:y_data}) if i%50==0: #print(sess.run(loss,feed_dict={xs:x_data,ys:y_data})) try: ax.lines.remove(lines[0]) except Exception: pass prediction_value=sess.run(prediction,feed_dict={xs:x_data}) lines=ax.plot(x_data,prediction_value,'r-',lw=5) if i==1000: plt.ioff() plt.show() else: plt.pause(0.1)
4.神经网络训练MNIST
reduce_sum函数:链接
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data',one_hot=True) import matplotlib.pyplot as plt def add_layer(inputs,in_size,out_size,activation_function=None): Weights=tf.Variable(tf.random_normal([in_size,out_size]),name='W') biases=tf.Variable(tf.zeros([1,out_size])+0.1) Wx_plus_b=tf.matmul(inputs,Weights)+biases if activation_function==None: outputs=Wx_plus_b else: outputs=activation_function(Wx_plus_b) return outputs def compute_accuracy(v_xs,v_ys): global prediction y_pre=sess.run(prediction,feed_dict={xs:v_xs}) correct_prediction=tf.equal(tf.argmax(y_pre,1),tf.argmax(v_ys,1)) accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) result=sess.run(accuracy,feed_dict={xs:v_xs,ys:v_ys}) return result xs=tf.placeholder(tf.float32,[None,784]) ys=tf.placeholder(tf.float32,[None,10]) prediction=add_layer(xs,784,10,activation_function=tf.nn.softmax) cross_entropy=tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),reduction_indices=[1])) train_step=tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) sess=tf.Session() sess.run(tf.initialize_all_variables()) for i in range(1001): batch_xs,batch_ys=mnist.train.next_batch(100) sess.run(train_step,feed_dict={xs:batch_xs,ys:batch_ys}) if i%50 ==0: print(compute_accuracy(mnist.test.images,mnist.test.labels))
5.图片读取的一些方法 链接
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import tensorflow as tf import matplotlib.pyplot as plt image_contents=tf.read_file('acoustic-guitar-player.jpg') #image_contents = tf.gfile.FastGFile('acoustic-guitar-player.jpg', 'rb').read() image = tf.image.decode_jpeg(image_contents) image = tf.image.resize_image_with_crop_or_pad(image, 227, 227) with tf.Session() as sess: sess.run(image) plt.imshow(image.eval()) plt.show()