机器学习之_TensorFlow

TensorFlow 是一个用于数值计算的Python 库, 可以描述一幅数据计算的数据流图(data flow graph)。
TensorFlow 最初由Google大脑小组(隶属于Google机器智能研究机构)的研究员和工程师们开发出来,用于机器学习和深度神经网络方面的研究,但这个系统的通用性使其也可广泛用于其他计算领域。
详情可参考TensorFlow中文社区

会话 (Session):TensorFlow描述的计算流程图需要在Session中启动;Session将其与C++后端连接,为其分配计算设备(CPU 或 GPU)和提供计算方法,反复训练模型。

节点(Nodes):在图中表示数学操作,例如,数据输入(feed in)的起点或输出(push out)的终点;

线(edges):线输送节点间相互联系和不断变化的多维数据数组(即张量, tensor)。

#导包
import numpy as np
import tensorflow as tf
#手写数字集mnist
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('./')
mnist.train.images.shape
#就是训练样本集
mnist.train.images[0]
mnist.train.labels[:100]

mnist = input_data.read_data_sets("./", one_hot=True)
#独热编码
#0-1概率

#数据没变
mnist.train.images.shape
mnist.train.labels[0]
#[0.1,0.1,0,0,0,0,0,0,0,0.8]
#真实分布

a = tf.constant([3,1,-3.0])
#将数据转变为概率来看了
#交叉熵就是将数据------通过它的概率去比较大小(加和是1)
with tf.Session() as sess:
    print(sess.run(tf.nn.softmax(a)))

mnist.train.images.shape
mnist.train.labels.shape

X = tf.placeholder(dtype=tf.float64, shape = [None, 784])
Y = tf.placeholder(dtype = tf.float64, shape = [None, 10])

#占位
W = tf.Variable(initial_value=np.zeros(shape = [784,10]), dtype = tf.float64)
b = tf.Variable(initial_value=np.zeros(shape = [10]), dtype=tf.float64)

#w *x + b
#pred是什么样的额数据10列
pred = tf.matmul(X, W)+ b

y_ = tf.nn.softmax(pred)
#这一步就是使用了【】
#[0.1,0,0,0,0,0,0,0,0.2,0.7]

#Y:真实的概率  [0., 0., 0., 0., 0., 0., 0.,  0., 0.,1]
#y_:[0.1,0,0,0,0,0,0,0,0.2,0.7] 预测的非真实分布
#这只是简单的公式而已
cost = tf.reduce_mean(tf.reduce_sum(tf.multiply(Y, tf.log(1/y_)), axis = 1))

optimizer = tf.train.GradientDescentOptimizer(0.01).minimize(cost)

使用TensorFlow实现线性回归.

#导包
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
%matplotlib inline
rng = np.random

#定义训练次数learning_epochs,卷曲神经的学习率learning_rate
#显示打印数据的步幅display_step
learning_epochs = 1000
learning_rate = 0.01
display_step = 50

#生成训练数据
train_X = np.linspace(0,10,num = 20)+rng.randn(20)
train_X
train_Y = np.linspace(1,4,num =  20)+np.random.randn(20)
train_Y
n_samples = train_Y.shape[0]
n_samples

# 绘图
plt.scatter(train_X,train_Y)

#定义TensorFlow参数:X,Y,W,b
X = tf.placeholder("float")
Y = tf.placeholder("float")
#Variable变量定义了斜率和截距
#weight 权重
#bias偏差, 就叫截距
W = tf.Variable(rng.randn(), name = "weight")
b = tf.Variable(rng.randn(), name = "bias")

#创建线性模型
y_pred = tf.add(tf.multiply(W, X), b)
#y = w*x + b

#创建TensorFlow均方误差cost,以及梯度下降优化器optimizer
a = tf.constant([1,2,3])
sess = tf.Session()
sess.run(tf.reduce_sum(a))

#损失,误差
#均方误差, 严格按照最小二乘法
cost = tf.reduce_sum(tf.pow((y_pred - Y), 2))/n_samples

#如何把cost变为最小? 梯度下降法
#就是一个操作
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

#TensorFlow初始化
e = [1,2,3]
f = [4,5,6]
for (g,h) in zip(e,f):
    print(g, h)
#对tensorflow 进行初始化的
init = tf.global_variables_initializer()

#训练开始
with tf.Session() as sess:
    #开始初始化
    sess.run(init)
    #训练所有的数据, 1000次循环
    for epoch in range(5000):
        #执行20次
        for (x,y) in zip(train_X,train_Y):
            #每次都要执行梯度下降算法
            sess.run(optimizer, feed_dict = {X:x, Y:y})
        #每执行50次然后打印一下损失值
        if (epoch+1)%display_step == 0:
            #cost叫均方误差
            c = sess.run(cost, feed_dict={X:train_X, Y:train_Y})
            print("cost:", "{:.9f}".format(c), "W:",sess.run(W),'b:',sess.run(b))
            
    #数据可视化
    plt.plot(train_X, train_Y,"ro")
    plt.plot(train_X, sess.run(W)*train_X+sess.run(b))
发布了388 篇原创文章 · 获赞 71 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/ZZQHELLO2018/article/details/104002098