通过实验来一步一步的学习
线性回归:
//导入库
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os
learning_rate=0.01//学习率
training_epochs=1000//学习次数
display_step=50//每次的次数
train_X=np.asarray([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])//实验数据
train_Y=np.asarray([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])
n_samples=train_X.shape[0]
X=tf.placeholder("float")
Y=tf.placeholder("float")//占位符
W=tf.Variable(np.random.randn(),name="weight")
b=tf.Variable(np.random.randn(),name="bias")//定义变量
pred=tf.add(tf.multiply(X,W),b)//回归函数
cost=tf.reduce_sum(tf.pow(pred-Y,2))/(2*n_samples)//损失函数
optimizer=tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)//训练
init=tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)//初始化操作
for epoch in range(training_epochs):
for (x, y) in zip(train_X, train_Y):
sess.run(optimizer,feed_dict={X:x,Y:y})
if (epoch+1)%display_step == 0:
c=sess.run(cost,feed_dict={X:train_X,Y:train_Y})
print("Epoch:", '%04d' % (epoch + 1), "cost=", "{:.9f}".format(c), "W=", sess.run(W), "b=", sess.run(b))
plt.plot(train_X, train_Y, 'ro', label='Original data')
plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitting line')
plt.legend()
plt.show()
逻辑回归
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#导入实验所需的数据
mnist = input_data.read_data_sets("C:\Users\Administrator\Desktop\大三寒假作业\大三寒假作业\深度学习算法部分",one_hot = True)
#设置训练参数
learning_rate=0.01
training_epochs=25
batch_size=100
display_step=1
#构造计算图,使用占位符placeholder函数构造变量x,y,
x=tf.placeholder(tf.float32,[None,784])
y=tf.placeholder(tf.float32,[None,10])
#使用Variable函数,设置模型的初始权重
W=tf.Variable(tf.zeros([784,10]))
b=tf.Variable(tf.zeros([10]))
#构造逻辑回归模型
pred=tf.nn.softmax(tf.matmul(x,W)+b)
#构造代价函数cost
cost=tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred),reduction_indices=1))
#使用梯度下降法求最小值,即最优解
optimizer=tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
#初始化全部变量
init=tf.global_variables_initializer()
#.使用tf.Session()创建Session会话对象,会话封装了Tensorflow运行时的状态和控制
with tf.Session() as sess:
sess.run(init)
#调用会话对象sess的run方法,运行计算图,即开始训练模型
for epoch in range(training_epochs):
avg_cost = 0
total_batch = int(mnist.train.num_examples / batch_size)
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
_, c = sess.run([optimizer, cost], feed_dict={x: batch_xs, y: batch_ys})
avg_cost += c / total_batch
if (epoch+1) % display_step == 0:
print("Epoch:", '%04d' % (epoch + 1), "Cost:","{:.09f}".format(avg_cost))
print("Optimization Finished!")
#测试模型
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
#评估模型的准确度
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print("Accuracy:", accuracy.eval({x: mnist.test.images[:3000], y: mnist.test.labels[:3000]}))