Python:TensorFlow深度学习框架学习笔记

官方文档
1.基本操作知识
创建图与启动图
import tensorflowas tf

#创建一个常量op,为一个一行两列的矩阵

m1=tf.constant([[3,3]])

#创建两行一列的矩阵

m2= tf.constant([[2], [3]])

#创建矩阵乘法

product = tf.matmul(m1, m2)

print(product)

#定义一个会话,启动默认图

sess = tf.Session()

#调用run方法来执行矩形乘法op

result = sess.run(product)

print(result)

sess.close()

with tf.Session()as sess:

#调用矩阵乘法op

result = sess.run(product)

print(result)

变量操作
x = tf.Variable([1, 2])#定义一个变量

a = tf.constant([3, 3])

sub = tf.subtract(x, a)#减法

add = tf.add(x, sub)#加法

init = tf.global_variables_initializer()#变量初始化

with tf.Session()as sess:

sess.run(init)

print(sess.run(sub))

print(sess.run(add))

state = tf.Variable(0,name=‘counter’)#创建一个变量初始化为0

new_value = tf.add(state,1)#将state+1

update = tf.assign(state, new_value)#将new_value的值赋值给state

init = tf.global_variables_initializer()

with tf.Session()as sess:

sess.run(init)

print(sess.run(state))

for _in range(5):

sess.run(update)

print(sess.run(state))

Fetch与Feed
#Fetch

input1 = tf.constant(3.0)

input2 = tf.constant(2.0)

input3 = tf.constant(5.0)

add = tf.add(input1, input2)

mil = tf.multiply(input1, add)

with tf.Session()as sess:

result = sess.run([mil, add])

print(result)

#Feed

#创建占位符

input1 = tf.placeholder(tf.float32)

input2 = tf.placeholder(tf.float32)

output = tf.multiply(input1, input2)

with tf.Session()as sess:

#feed的数据以字典形式输入

print(sess.run(output,feed_dict={input1:[7.],input2:[2.]}))

案例:直线拟合测试
#使用numpy生成100个随机点

x_data = np.random.rand(100)

y_data = x_data*0.1+0.2

#构建一个线性模型

b = tf.Variable(0.)

k = tf.Variable(0.)

y = k*x_data+b

#二次代价函数

loss = tf.reduce_mean(tf.square(y_data-y))

#定义一个梯度下降法来进行训练优化器

optimizer = tf.train.GradientDescentOptimizer(0.2)

#最小代价函数

train = optimizer.minimize(loss)

#初始化变量

init = tf.global_variables_initializer()

with tf.Session()as sess:

sess.run(init)

for stepin range(201):

sess.run(train)

if step%20==0:

print(step, sess.run([k, b]))

线性回归
import tensorflowas tf

import numpyas np

import matplotlib.pyplotas plt

#使用numpy生成200个随机点

x_data = np.linspace(-0.5, 0.5, 200)[:,np.newaxis]#-0.5到0.5之间生成200个数据组成200行一列

noise = np.random.normal(0,0.02,x_data.shape)

y_data = np.square(x_data) + noise

#定义两个placeholder

x = tf.placeholder(tf.float32,[None,1])

y = tf.placeholder(tf.float32,[None,1])

#构建神经网络中间层

Weights_L1 = tf.Variable(tf.random_normal([1, 10]))

biases_L1 = tf.Variable(tf.zeros([1, 10]))

Wx_plus_b_L1 = tf.matmul(x, Weights_L1)+biases_L1

L1 = tf.nn.tanh(Wx_plus_b_L1)

#定义输出层

Weights_L2 = tf.Variable(tf.random_normal([10, 1]))

biases_L2 = tf.Variable(tf.zeros([1, 1]))

Wx_plus_b_L2 = tf.matmul(L1, Weights_L2)+biases_L2

prediction = tf.nn.tanh(Wx_plus_b_L2)

#二次代价函数

loss = tf.reduce_mean(tf.square(y-prediction))

#定义一个梯度下降法来进行训练优化器

train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

with tf.Session()as sess:

#变量初始化

sess.run(tf.global_variables_initializer())

for _in range(2000):

sess.run(train_step,feed_dict={x:x_data,y:y_data})

#获得预测值

prediction_value = sess.run(prediction, feed_dict={x:x_data})

#画图

plt.figure()

plt.scatter(x_data,y_data)

plt.plot(x_data,prediction_value,“r_”,lw=5)#用红实线 粗为5的先绘图

plt.show()

2.数据分析分类
MNIST数据集(手写数字数据集)
MNIST数据集的标签监狱0~9的数字,我们把标签转化为“one-hot vectors” 一个one-hot向量除了某一位数字一外,其余纬度都是0,如标签0为([1,0,0,0,0,0,0,0,0,0])

因此,minist.train.label是一个[60000,10]的数字矩阵

      minist.train.images是一个形状为[60000,784]的张量,每张图片像素28*28=784,第一个维度数字用来索引图片,第二个维度数字用来索引每张图片的像素点。图片的每个像素的强度都介于0-1之间

神经网络的构建

784——10的映射

Softmax函数

代码:

import tensorflowas tf

from tensorflow.examples.tutorials.mnistimport input_data

#载入数据集

mnist = input_data.read_data_sets(“MNIST_data”,one_hot=True)

#每个批次大小

batch_size =100

#计算一共多少个批次

n_batch = mnist.train.num_examples // batch_size

#定义两个placeholder

x = tf.placeholder(tf.float32, [None, 784])

y = tf.placeholder(tf.float32, [None, 10])

#创建一个简单的神经网络

W = tf.Variable(tf.zeros([784, 10]))

b = tf.Variable(tf.zeros([10]))

prediction = tf.nn.softmax(tf.matmul(x, W)+b)

#二次代价函数

loss = tf.reduce_mean(tf.square(y-prediction))

#梯度下降法

train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)

#初始化变量

init = tf.global_variables_initializer()

#结果存放在一个boolean列表

correct_prediction = tf.equal(tf.arg_max(y, 1), tf.arg_max(prediction, 1))#arg_max求最大数字的位置

#求准确率

accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

with tf.Session()as sess:

#变量初始化

sess.run(init)

for epochin range(21):#所有图片训练21次

    for batchin range(n_batch):

batch_xs, batch_ys = mnist.train.next_batch(batch_size)

sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys})

acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})

print(“Iter”+str(epoch)+",Test Accuracy"+str(acc))

二次代价函数
交叉熵代价函数
#交叉熵函数

loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction))

拟合
欠拟合,,争取拟合,过拟合

防止过拟合:

1.增加数据集 2.正则化方法 3.Dropout

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JackHCC

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值