创建张量

import tensorflow as tfprint("Tensorflow version:", tf.__version__)  # 检查版本号
print("Eager execution is:", tf.executing_eagerly())  # 检查是否在Eager模式下'''
Tensor表示张量,其实就是多维数组。
'''
'''
python中的列表list
Numpy中的数组对象ndarray
TensorFlow中的张量(Tensor)
'''
# 区别
'''
python列表(list):·元素可以使用不同的数据类型,可以嵌套·在内存中不连续存放,是一个动态的指针数组·读写效率低,占用内存空间大·不适合做数值计算Numpy数组(ndarray):·元素数据类型相同·每个元素在内存中占用的空间相同存储在一个连续的内存区域内·存储空间小,读取和写入速度快·在cpu中运算,不能够主动检测利用gpu进行运算
TensorFlow张量(Tensor):·可以高速运行于gpu和Tpu之上·支持cpu、嵌入式、单机多卡和多机多卡等多种计算环境·高速的实现神经网络和深度学习中的复杂算法
'''
# 创建Tensor对象# tf.constant()函数:创建张量# tf.constant(value,dtype,shape)# value:数字\python列表\numpy数组# dtype:元素的数据类型# shape:张量的形状# tf.convert_to_tensor()函数
'''判断是否是张量:is_tensor()函数isinstance()函数
'''
# 参数为PYthon列表
import tensorflow as tf
print(tf.constant([[1,2],[3,4]]))
# 张量的.numpy()方法
a = tf.constant([[1,2],[3,4]])
print(a.numpy())
print(type(a))
# <class 'tensorflow.python.framework.ops.EagerTensor'>表示其是eager模式下的张量
# 创建张量(tensor)
'''
tf.constant(张量内容,dtype=数据类型)
'''
import tensorflow as tfa = tf.constant([1, 5], dtype=tf.int64)
print(a)
print(a.dtype)  # 数据类型
print(a.shape)  #
# tf.Tensor([1 5], shape=(2,), dtype=int64) 打印出张量的所有内容
# <dtype: 'int64'>  数据类型
# (2,)  2表示有两个元素,一个逗号隔开表示一维数组# convert 转换'''
将numpy的数据类型转换为Tensor的数据类型
tf.convert_to_tensor(数据名,dtype=数据类型(可选))'''
import tensorflow as tf
import numpy as npa = np.arange(0, 5)
b = tf.convert_to_tensor(a, dtype=tf.int64)
print(a)
print(b)
# [0 1 2 3 4]
# tf.Tensor([0 1 2 3 4], shape=(5,), dtype=int64)'''
创建全为0的张量
tf.zeros(维度)创建全为1的张量
tf.ones(维度)创建全为指定值的张量
tf.fill(维度,指定值)维度:一维 直接写个数二维  用[行,列]多维 用[n,m,j,k.....]'''
print("******************")
a = tf.zeros([2, 3])  # 二维数组
b = tf.ones(4)  # 一维数组
c = tf.fill([2, 2], 9)  # 二维数组
print(a)
print(b)
print(c)'''
生成正态分布的随机数,默认均值为0,标准差为1
tf.random.normal(维度,mean=均值,stddev=标准差)生成截断式正态分布的随机数(truncated 截断)
tf.random.truncated_normal(维度,mean=均值,stddev=标准差)在tf.truncated_normal中如果随机生成数据的取值在()'''
d = tf.random.normal([2,2],mean=0.5,stddev=1)
print(d)e = tf.random.truncated_normal([2,2],mean=0.5,stddev=1)
print(e)
# tf.Tensor(
# [[ 0.8248359  0.9195403]
#  [-0.9171852  0.9591876]], shape=(2, 2), dtype=float32)
# tf.Tensor(
# [[-1.4231092   0.9822493 ]
#  [ 0.93558526  1.1987464 ]], shape=(2, 2), dtype=float32)'''
生成均匀分布随机数
tf.random.uniform(维度,minval=最小值,max=最大值)'''
f = tf.random.uniform([2,2],minval=0,maxval=1)
print(f)
# tf.Tensor(
# [[0.4069723  0.3565172 ]
#  [0.7605829  0.19685042]], shape=(2, 2), dtype=float32)'''
常用函数
强制tensor转换为该数据类型(用tf.cast强制类型转换)
tf.cast(张量名,dtype=数据类型)计算张量维度上的最小值
tf.reduce_min(张量名)计算张量维度上元素的最大值
tf.reduce_max(张量名)'''
x1 = tf.constant([1.,2.,3.],dtype = tf.float64)
print(x1)x2 = tf.cast(x1,tf.int32)
print(x2)print(tf.reduce_min(x2))
print(tf.reduce_max(x2))
# tf.Tensor([1. 2. 3.], shape=(3,), dtype=float64)
# tf.Tensor([1 2 3], shape=(3,), dtype=int32)
# tf.Tensor(1, shape=(), dtype=int32)
# tf.Tensor(3, shape=(), dtype=int32)'''
axis
在一个二维张量或数组中,可以通过调整axis等于0或1控制执行维度axsi=0代表跨行(经度,down),而axis=1代表跨列(维度,across)
如果不指定axis,则所有元素参与计算计算张量沿着指定维度的平均值
tf.reduce_mean(张量名,axis=操作轴)计算张量沿着指定维度的和
tf,reduce_sum(张量名,axis=操作轴)'''
x = tf.constant([[1,2,3],[2,3,4]])
print(x)
print(tf.reduce_mean(x))
print(tf.reduce_sum(x,axis=1))# tf.Tensor(
# [[1 2 3]
#  [2 3 4]], shape=(2, 3), dtype=int32)
# tf.Tensor(2, shape=(), dtype=int32)
# tf.Tensor([6 9], shape=(2,), dtype=int32)'''
tf.Variable
tf.Variable()将变量标记为“可训练”,被标记的变量会在反向传播中记录梯度信息。
神经网络训练中,常用该函数标记待训练的变量tf.Variable(初始值)
'''
#w = tf.Variable(tf.random.normal([2,2],mean=0,stddev=1))'''
tensorflow中的数学运算对应元素的四则运算:tf.add,tf.subtract,tf.multiply,tf.divide
平方、次方与开方:tf.square,tf.pow,tf.aqrt
矩阵乘:tf.matmul实现两个张量的对应元素相加
tf.add(张量1,张量2)
实现两个元素的对应元素相减
tf.subtract(张量1,张量2)
实现两个张量的对应元素相乘
tf.multiply(张量1,张量2)
实现两个张量的对应元素相除
tf.divide(张量1,张量2)!!!只有维度相同的张量才可以做四则运算'''
a = tf.ones([1,3])
b = tf.fill([1,3],3.)print(a)
print(b)print(tf.add(a,b))
print(tf.subtract(a,b))
print(tf.multiply(a,b))
print(tf.divide(b,a))
print("--------------------")# tf.Tensor([[1. 1. 1.]], shape=(1, 3), dtype=float32)
# tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32)
# tf.Tensor([[4. 4. 4.]], shape=(1, 3), dtype=float32)
# tf.Tensor([[-2. -2. -2.]], shape=(1, 3), dtype=float32)
# tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32)
# tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32)
'''
计算某个张量的平方
tf.square(张量名)计算某个张量的n次方
tf.pow(张量名,n次方数)计算某个张量的开方
tf.sqrt(张量名)
'''
a = tf.fill([1,2],3.)
print(a)
print(tf.pow(a,3))
print(tf.square(a))
print(tf.sqrt(a))
# tf.Tensor([[3. 3.]], shape=(1, 2), dtype=float32)
# tf.Tensor([[27. 27.]], shape=(1, 2), dtype=float32)
# tf.Tensor([[9. 9.]], shape=(1, 2), dtype=float32)
# tf.Tensor([[1.7320508 1.7320508]], shape=(1, 2), dtype=float32)
'''
矩阵乘tf.matmul实现两个矩阵的相乘
tf.matmul(矩阵1,矩阵2)
'''
a = tf.ones([3,2])
b = tf.fill([2,3],3.)
print(tf.matmul(a,b))
# tf.Tensor(
# [[6. 6. 6.]
#  [6. 6. 6.]
#  [6. 6. 6.]], shape=(3, 3), dtype=float32)
'''
常用函数 tf.Dataset.from_tensor_slices切分传入张量的第一维度,生成输入特征标签对,构建数据集
data = tf.Dataset.from_tensor_slices((输入特征,标签))(Numpy和Tensor格式都可用该语句读入数据)
'''
features = tf.constant([12,23,10,17])
labels = tf.constant([0,1,1,0])
dataset = tf.data.Dataset.from_tensor_slices((features,labels))
for element in dataset:print(element)
# (<tf.Tensor: shape=(), dtype=int32, numpy=12>, <tf.Tensor: shape=(), dtype=int32, numpy=0>)
# (<tf.Tensor: shape=(), dtype=int32, numpy=23>, <tf.Tensor: shape=(), dtype=int32, numpy=1>)
# (<tf.Tensor: shape=(), dtype=int32, numpy=10>, <tf.Tensor: shape=(), dtype=int32, numpy=1>)
# (<tf.Tensor: shape=(), dtype=int32, numpy=17>, <tf.Tensor: shape=(), dtype=i
'''
tf.GradientTape 实现对指定参数的求导运算
with结构记录计算过程,gradient求出张量的梯度with tf.GradientTape() as tape:若干个计算过程
grad = tape.gradient(函数,对谁求导)'''
with tf.GradientTape() as tape:w = tf.Variable(tf.constant(3.0))loss = tf.pow(w,2)
grad =tape.gradient(loss,w)
print(grad)
# tf.Tensor(6.0, shape=(), dtype=float32)'''
enumerate是python的内建函数,他可遍历每个元素(如:列表,元组,或字符串)
enumerate(列表名)'''
seq = ['one','two','three']
for i,element in enumerate(seq):print(i,element)
# 0 one
# 1 two
# 2 three
'''
tf.one_hot
tf.one_hot() 函数将待转换数据,转换为one_hot的形式输出。tf.one_hot(带转换数据,depth=分类)'''
classes = 3
labels = tf.constant([1,0,2])# 输入的元素值最小为0,最大为2
output = tf.one_hot(labels,depth=classes)
print(output)
# tf.Tensor(
# [[0. 1. 0.]
#  [1. 0. 0.]
#  [0. 0. 1.]], shape=(3, 3), dtype=float32)

创建数组 数组运算

# 生成ndarray(多维数组)的方法
# 1、将列表转换成ndarray
import numpy as np
list1 = [3.14,2.17,0,1,2]
nd1 = np.array(list1)
print(nd1)
print(type(nd1))
# 2、嵌套列表转成多维数组
import numpy as np
list2 = [[3.14,2.17,0,1,2],[1,2,3,4,5]]
nd2 = np.array(list2)
print(nd2)
print(type(nd2))
# 3、利用random模块生成多维数组
'''random 模块里的函数:random(生成0~1之间的随机数)uniform(生成均匀分布随机数)rando(生成标准正态的随机数)normal (生成正态分布)shuffle(随机打乱顺序)seed (设置随机数种子)'''
import numpy as np
nd3 = np.random.random([3,3])   # 生成三行三列的0~1之间的随机数
print(nd3)
print(type(nd3))print('**************************')
# 生成一个随机种子,对生成的随机数打乱
import numpy as np
np.random.seed(123)   # 设置随机数种子序号123 给数列管理器序号123得到哟个数列
nd5_1 = np.random.randn(2,3)        # 生成两行三列得的随机种子
print(nd5_1)
np.random.shuffle(nd5_1)
print("随机打乱后的数据:",nd5_1)
print(type(nd5_1))# 创建特定形状的多维数组
'''
np.zeros
np.ones
np.diag
np.eye
'''
import numpy as np
# 生成全是0的3x3的矩阵
nd6 = np.zeros([3,3])
# 生成全是1的3x3的矩阵
nd7 = np.ones([3,3])
# 生成3阶单位矩阵
nd8 = np.eye(3)
# 生成3阶对角矩阵
nd9 = np.diag([1,2,3])
print(nd9)# 利用arange函数生成ndarray
import numpy as np
print(np.arange(10))
print(np.arange(1,10))
print(np.arange(1,4,0.5))
print(np.arange(9,-1,-1))# 创建数组并且改变数组形状
'''
np.reshape(shape) 不改变当前数组形状,按照shape创建新的数组
np.resize(shape) 改变当前数组,按照shape创建数组
'''import numpy as npb = np.arange(12)
print(b.reshape(3, 4))
print(b)
# b = np.arange(12).reshape(3,4)t = np.arange(24).reshape(2, 3, 4)
print(t)
# [[[ 0  1  2  3]
#   [ 4  5  6  7]
#   [ 8  9 10 11]]
#
#  [[12 13 14 15]
#   [16 17 18 19]
#   [20 21 22 23]]]# np.reshape(shape) shape = -1 根据数组中的元素个数、以及其他维度的取值,来自动
# 出这个维度的取值
print(b.reshape(-1, 1))
# [[ 0]
#  [ 1]
#  [ 2]
#  [ 3]
#  [ 4]
#  [ 5]
#  [ 6]
#  [ 7]
#  [ 8]
#  [ 9]
#  [10]
#  [11]]# 一维数组跟多维数组相加,可以将一维数组扩展至多维数组
a = np.array([0, 1, 2, 3])
b = np.array([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]])
print(a + b)
# [[ 0  2  4  6]
#  [ 4  6  8 10]
#  [ 8 10 12 14]]
# 当两个数组中的数据类型不同时,精度低的数据类型会自动转换为精度高的数据类型,然后进行计算# 矩阵转置:np.transpose()
# 矩阵求逆:np.linalg.inv()
'''
总结:numpy对数组的常用操作对数组元素的切片改变数组的形状数组之间的常用运算'''
# 数组元素的运算
'''
numpy.sum() 计算所有元素的和
numpy.prod() 计算所有元素的乘积
numpy.diff() 计算数组的相邻元素之间的差
np.sqrt() 计算各元素的平方根
np.exp() 计算各元素的指数值
np.abs() 取各元素的绝对值
'''
# 求和函数sum():对数组中的所有元素求和a = np.arange(4)
print(a)
print(np.sum(a))b = np.arange(12).reshape(3, 4)
print(b)
print(np.sum(b))
# 6
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]
# 66'''
轴(axes):数组中的每个维度被称为一个轴
秩(rank):轴的格式
'''
print(np.sum(b, axis=0))
# [12 15 18 21]print(np.sum(b, axis=1))
# [ 6 22 38]# sqrt() 函数 求平方根
d = np.logspace(1, 4, 4, base=2)  # logspace函数生成等比数列
print(d)
print(np.sqrt(d))
# [ 2.  4.  8. 16.]
# [1.41421356 2.         2.82842712 4.        ]
'''
数组的堆叠运算
np.stack(数组1,数组2,....axis)
'''
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])print(np.stack((x, y), axis=0))
print(np.stack((x, y), axis=1))
# [[1 2 3]
#  [4 5 6]]
# [[1 4]
#  [2 5]
#  [3 6]]

创建矩阵 矩阵运算

'''
创建矩阵
矩阵---numpy.matrix
matrix(字符串/列表/元组/数组)
mat(字符串/列表/元组/数组)
'''
a = np.mat('1 2 3; 4 5 6')
print(a)
b = np.mat([[1,2,3],[4,5,6]])
print(b)# [[1 2 3]#  [4 5 6]]# [[1 2 3]#  [4 5 6]]a = np.array([[1,2,3],[4,5,6]])
print(a)
m = np.mat(a)
print(m)print(type(a))
print(type(m))# [[1 2 3]#  [4 5 6]]# [[1 2 3]#  [4 5 6]]# <class 'numpy.ndarray'># <class 'numpy.matrix'>'''
矩阵对象的属性:.ndim 矩阵的维数.shape 矩阵的形状.size 矩阵的元个数.dtype 元素的数据类型
'''
print(m.ndim)
print(m.shape)
print(m.size)
print(m.dtype)# 2# (2, 3)# 6# int32'''矩阵运算
矩阵的转置:.T
矩阵求逆:.I
'''
n = np.mat([[1,2],[-1,-3]])
print(n)
print(n.T)
print(n.I)# [[ 1  2]#  [-1 -3]]# [[ 1 -1]#  [ 2 -3]]# [[ 3.  2.]#  [-1. -1.]]# 随机数'''
随机数模块---numpy.random
np.random.rand()    元素在[0,1)之间均匀分布的数组
np.random.uniform(low,hige,size)    元素在[low,hige)区间均匀分布的数组
np.random.randn(d0,d1,d2,...,dn)    产生标准正态分布的数组(标准差时1,均值时0的正态分布)
np.random.normal(loc,scale,size)    产生正态分布的数组loc 均值;scale标准差伪随机数:由随机种子,根据一定的算法生成的
随机种子:指定随机数生成时所用算法开始的整数值如果使用相同的seed()值,则每次生成的随机数都是相同的如果不设置这个值,则系统根据时间来自己选择这个值,此时每次生成的随机数因时间差异而不同'''# 打乱顺序的函数 np.random.shuffle(序列)# 多维数组只打乱第一维b = np.arange(12).reshape(4,3)
print(b)
c = np.random.shuffle(b)
print(c)

数字图像基本概念

一个字节由8个二进制位组成
图像压缩:适当降低图像质量来减小它所占用的空间不同的图像压缩算法,对应不同的图像格式像素(Pixel):是图像中的一个最小单位图像的离散化:连续图像:人眼直接感受到的图像数字图像:把连续的图像数字化、离散化之后的图像。它是对连续图像的一种近似色彩深度/位深度:位图中每个像素点要用多少二进制位来表示位图(bitmap):通过记录每一个像素的颜色值,来存储和表达图像图像格式:BMP格式(是windows系统的标准位图格式):需要保存每个像素的颜色信息,占用存储空间大,不支持文件压缩,不适用网页JPEG:有损压缩压缩率高,所占空间小适合于色彩丰富、细节清晰细腻的大图像不适合所含颜色较少,具有大块颜色相近的区域,或亮度差异十分明显的简单图片每次编辑都会降低图像质量,不适合需要进行多次编辑的情况PNG(Portable Network Graphics ,PNG):无损压缩适合于有规律渐变色彩的图像,GIF,TIFF色彩模式:记录图像颜色的方式二值图像(Binary Image):每个像素只有2种可能的取值,使用1位二进制来表示,位深度为 0代表黑色,1代表白色灰度图像(Gray Image):每个像素使用1个字节表示,位深度位8,可以表示256种级别的灰度。0表示黑色,255表示白色RGB图像(彩色图像):每个像素都有红(R)、绿(G)、蓝(B)三个分量(称为通道)1个像素点使用3个字节(每个分量1个字节),位深度为24位(3*8)可以表示256*256*256种颜色称为24位真彩色RGBA图像:RGB图像+8位透明度信息Alpha(称为Alpha通道或者A通道)32位真彩色图像:1个像素点使用4个字节,位深度为32位256色彩色图像:每个像素用8位二进制表示,是调色板中的索引值CMYK、YCbCr、HSI

python图像处理库

import PIL.Image
from PIL import Image
import matplotlib.pyplot as pltimg = Image.open('lena.tiff')
img.save('test.tiff')
img.save('lena.jpg')
img.save('lena.bmp')img1 = Image.open('lena.tiff')
img2 = Image.open('lena.bmp')
img3 = Image.open('lena.jpg')print("image1:", img1.format)
print("image2:", img2.format)
print("image3:", img3.format)print("size:", img1.size)
print("size:", img2.size)
print("size:", img3.size)print("mode:", img1.mode)
print("mode2:", img2.mode)
print("mode3:", img3.mode)# imshow() 函数负责对图像进行处理 并显示其格式
plt.figure(figsize=(5, 5))
plt.imshow(img)
plt.show()# 分别显示不同格式的图像
# 设置画布尺寸img1 = Image.open('lena.tiff')
img2 = Image.open('lena.bmp')
img3 = Image.open('lena.jpg')plt.figure(figsize=(15, 5))# 将画布划分为1行3列
plt.subplot(131)
# 不显示坐标轴
plt.axis("off")
# 显示img图像(对图像进行处理并显示其格式)
plt.imshow(img1)
# 子图标题位置显示子图格式
plt.title(img1.format)plt.subplot(132)
plt.axis("off")
plt.imshow(img2)
plt.title(img2.format)plt.subplot(133)
plt.axis("off")
plt.imshow(img3)
plt.title(img3.format)plt.show()# 转换图像的色彩模式
# 图像对像.convert(色彩模式)
img_gray = img.convert("L")  # 将图像转换成灰度图像
print("mode=", img_gray.mode)  # 输出图像模式plt.figure(figsize=(5, 5))
plt.imshow(img_gray)
plt.show()# 将转换的灰度图像保存在工作目录
img_gray.save("lena_gray.bmp")# 颜色通道的分离与合并
'''
分离:图像对象.split()
合并:Image.merge(色彩模式,图像列表)
'''
# 打开RGB图像
img = Image.open("lena.tiff")
# 使用.split()分为三个颜色通道分别存储在不同的对象中
img_r, img_g, img_b = img.split()plt.figure(figsize=(10, 10))plt.subplot(221)
plt.axis('off')
# cmap=gray表示各个通道的图像是以灰度图像的形式显示的
plt.imshow(img_r, cmap="gray")
plt.title("R", fontsize=20)plt.subplot(222)
plt.axis("off")
plt.imshow(img_b, cmap="gray")
plt.title("G", fontsize=20)plt.subplot(223)
plt.axis("off")
plt.imshow(img_g, cmap="gray")
plt.title("B", fontsize=20)# 使用Image.merage(色彩模式,图像列表)合并各颜色通道,得到RGB彩色图像并显示在子图中
img_rgb = Image.merge("RGB", [img_r, img_g, img_b])
plt.subplot(224)
plt.axis("off")
plt.imshow(img_rgb)
plt.title("RGB", fontsize=20)plt.show()# 转化为数组
'''
np.array()'''
import numpy as nparr_img = np.array(img)
print("shape:", arr_img.shape, "\n")
print(arr_img)# 将灰度图像lena_gray.bmp转化为数组
img_gray = Image.open("lena.bmp")
arr_img_gray = np.array(img_gray)
print("\nshape:", arr_img_gray.shape)
print(arr_img_gray)# 255-arr_img_gray反向
arr_img_new = 255 - arr_img_gray
plt.figure(figsize=(10, 5))plt.subplot(121)
plt.axis("off")
plt.imshow(arr_img_gray, cmap="gray")plt.subplot(122)
plt.axis("off")
plt.imshow(arr_img_new, cmap="gray")plt.show()# 对图像的缩放、旋转和镜像
# 缩放图像
# 图像对像.resize((width,height))
# 图像对象.thumbnail((width,height))
plt.figure(figsize=(5, 5))
img_small = img.resize((64, 64))plt.imshow(img_small)
plt.show()
img_small.save("lena_s.jpg")# 旋转、镜像
# 图像对象.trandpose(旋转方式)
import matplotlib.pyplot as plt
from PIL import Imageplt.rcParams["font.sans-serif"] = "Simhei"
img = Image.open("lena.tiff")plt.figure(figsize=(10, 10))# 划分子图区域,并显示图像
plt.subplot(221)
plt.axis("off")
plt.imshow(img)
plt.title("原图", fontsize=20)plt.subplot(222)
plt.axis("off")
img_flr = img.transpose(Image.FLIP_LEFT_RIGHT)
plt.imshow(img_flr)
plt.title("左右翻转:", fontsize=20)plt.subplot(223)
plt.axis("off")
img_flr = img.transpose(Image.ROTATE_90)
plt.imshow(img_flr)
plt.title("逆时针旋转90度:", fontsize=20)plt.subplot(224)
plt.axis("off")
img_flr = img.transpose(Image.TRANSPOSE)
plt.imshow(img_flr)
plt.title("转置:", fontsize=20)plt.show()# 裁剪
# .crop()
import matplotlib.pyplot as plt
from PIL import Imageimg = Image.open("lena.tiff")plt.figure(figsize=(10, 5))plt.subplot(121)  # 绘制子图区域
plt.imshow(img)  # 显示原图plt.subplot(122)
img_region=img.crop((100,100,600,500))
plt.imshow(img_region)plt.show()

Matplotlib

# import matplotlib.pyplot as plt'''
Figure 对象figure(num,figsize,dpi,facecolor,edgecolor,frameon)num:图形编号或名称(数字/字符串)figsize:绘图对象的宽和高,单位为英寸dpi:绘图对象的分辨率,缺省值为80facecolor:背景颜色edgecolor:边框颜色frameon:是否显示边框 Figure 对象---划分子图  subplot(行数,列数,子图序号)
'''# import matplotlib.pyplot as plt## plt.figure(figsize=(3,2),facecolor='green')# plt.plot()  # plot() 绘制空白图形# plt.show()  # 显示出来## import matplotlib.pyplot as plt# fig = plt.figure()# plt.subplot(221)# plt.subplot(222)# plt.subplot(223)# plt.show()'''
设置中文字体
plt.rcParams["font.sans-serif"] = "SimHei"rcParams:run configuration Params即运行配置参数["font.sans-serif"] :字体"SimHei":中文黑体
添加标题添加全局标题suptitle(标题文字)添加子标题title(标题文字)tight_layout()函数 调整间隔检查坐标轴标签、刻度标签、子图标题,自动调整子图,使之自动填充整个绘图区域并消除子图之间的重叠tight_layout(rect=[left,bottom,right,top])'''
import matplotlib.pyplot as pltplt.rcParams["font.family"] = "SimHei"fig = plt.figure(facecolor="lightgrey")plt.subplot(221)
plt.title('子标题1')
plt.subplot(222)
plt.title('子标题2', loc='left', color='b')
plt.subplot(223)
myfontdict = {'fontsize': 12, 'color': 'g', 'rotation': 30}
plt.title('子标题3', fontdict=myfontdict)
plt.subplot(224)
plt.title('子标题4', color='white', backgroundcolor='black')plt.suptitle('全局标题', fontsize=20, color='red', backgroundcolor='yellow')
plt.tight_layout(rect=[0, 0, 1, 0.9])  # 自动调整间隔使子图充满整个画布
plt.show()# 散点图的绘制(scatter):数据点在直角坐标系中的分布图'''
scatter(x,y,scale,color,marker,label)
text(x,y,s,fontsize,color)增加均匀分布的点
增加图例 在scatter函数中的label属性中添加图例内容即可legend(loc,fontsize)显示图例 loc图例显示位置 fontsize字的大小
'''
import matplotlib.pyplot as plt  # 导入绘图库
import numpy as np  # 导入numpy库plt.rcParams['font.sans-serif'] = 'SimHei'  # 设置中文黑体为默认字体
plt.rcParams['axes.unicode_minus'] = False  # 正常显示负号n = 1024  # 随机点个数
x1 = np.random.normal(0, 1, n)  # 生成数据点x坐标
y1 = np.random.normal(0, 1, n)  # 生成数据点y坐标
x2 = np.random.uniform(-4, 4, (1, n))
y2 = np.random.uniform(-4, 4, (1, n))plt.scatter(x1, y1, color='blue', marker='*', label='正态分布')  # 绘制数据点
plt.scatter(x2, y2, color='yellow', marker='o', label='均匀分布')plt.legend()  # legend() 函数显示字体
plt.title('标准正态分布', fontsize=20)  # 设置标题# plt.text(2.5, 2.5, '均 值:0\n标准差:1')  # 显示文本plt.xlim(-4, 4)  # x轴范围
plt.ylim(-4, 4)  # y轴范围plt.xlabel('横坐标x', fontsize=14)  # 设置x轴标签文本
plt.ylabel('纵坐标y', fontsize=14)  # 设置y轴标签文本plt.show()  # 显示绘图# 绘制折线图(在散点图的基础上将相邻的点用线段连接起来'''
plot 绘制
plot(x,y,color,marker,label,linewidth,markersize)函数 绘制折线图
'''
import matplotlib.pyplot as plt
import numpy as npplt.rcParams['font.sans-serif'] = 'SimHei'  # 转成在中文字体n = 24  # 生成24个点
y1 = np.random.randint(27, 37, n)  # 生成随机数列
y2 = np.random.randint(40, 60, n)  # 生成随机数列plt.plot(y1, label='温度')  # 绘制折线图   将上面产生的随机数作为y坐标
plt.plot(y2, label='湿度')  # 绘制折线图   将上面产生的随机数作为y坐标plt.xlim(0, 23)  # 设置坐标轴范围
plt.ylim(20, 70)  # 设置坐标轴范围
plt.xlabel('小时', fontsize=12)
plt.ylabel('测量值', fontsize=12)plt.title('24小时温度湿度统计')  # 设置标题plt.legend()
plt.show()# 绘制柱形图'''
使用bar函数绘制柱形图
bar(left,height,width,facecolor,edgecolor,label)
facecolor 填充色
edgecolor 边缘颜色
'''
import numpy as np
import matplotlib.pyplot as plt  # 导入库plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False  # 设置rc参数y1 = [32, 25, 16, 30, 24, 45, 40, 33, 28, 17, 24, 20]
y2 = [-23, -35, -26, -35, -45, -43, -35, -32, -23, -17, -22, -28]plt.bar(range(len(y1)), y1, width=0.8, facecolor='green', edgecolor='white', label='统计量1')  # 绘制柱形条纹
plt.bar(range(len(y2)), y2, width=0.8, facecolor='red', edgecolor='white', label='统计量2')plt.title("柱状图", fontsize=20)  # 显示标题plt.legend()  # 显示图例
plt.show()  # 显示整个绘图'''
matplotlib官网有图和源程序
'''

鸢尾花数据集 手写图像minist数据集

鸢尾花数据集

# 鸢尾花数数据集
# 下载数据集(鸢尾花数据集不是tensorflow和keras中集成的内部数据集)
'''
get_file() 函数————下载数据集csv文件是一种字符分割的文件,以纯文本的形式存储表格数据可以使用记事本打开也可以在指定网络中下载数据集用:tf.keras.utils.get_file(fname,origin,cache_dir)fname :下载后的文件名origin :文件的URL地址cache_dir:下载后文件的存储位置
'''
# 下载鸢尾花数据集 iris
import tensorflow as tfTRAIN_URL = "http://download.tensorflow.org/data/iris_training.csv"
train_path = tf.keras.utils.get_file("iris_training.csv", TRAIN_URL)
fname_list = TRAIN_URL.split('/')
print(fname_list[-1])# Pandas 访问csv文件
'''
Pandas 库(Panel Data & Data Analysis)用于数据统计和分析可以高效、方便地操作大型数据集# 导入Pandas库import pandas as pd# 读取csv数据集文件pd.read_csv(filepath_or_buffle,header,names)names参数:自定义标题,代替header=0参数指定的列标题 names参数的值时一个列表# 访问数据head()函数:参数为空时,默认读取二维数据列表中的前五行数据tail(n)函数:读取后n行数据使用切片    df_iris[10:16] 表示读取10~15行数据# 显示统计信息describe()方法:显示二维数据的统计信息(总数、平均值、标准差、最大值、最小值、25%、50%、75%     numpydataframe中也有显示数据集属性的方法:  .ndim维数   .shape形状    .size元素个数        pandas'''
import pandas as pd
import numpy as npCOLUMN_NAMES = ['Sepallength', 'SepalWidth', 'PetaLength', 'PetalWidth', 'Spacies']
df_iris = pd.read_csv(train_path, header=0, names=COLUMN_NAMES)# print(train_path)
print(df_iris.head(8))  # 读取前8行数据
print(df_iris.tail(8))  # 读取后8行数据
print(df_iris[10:16])  # 读取10~15行数据
print(df_iris.describe())
print(type(df_iris))  # class 'pandas.core.frame.DataFrame'> dataframe是二维表格类型
print(df_iris.ndim)
print(df_iris.shape)
print(df_iris.size)
'''转化为Numpy数组'''
iris = np.array(df_iris)
print(type(iris))  # <class 'numpy.ndarray'> 转化为了numpy数组对象# 色彩映射
'''
plt.scatter(x,y,c,cmap)
将参数c指定为一个列表或数组,所绘制图形的颜色,可以随这个列表中的元素值而变换,变换所对应得颜色由参数cmap中指定得颜色所提供
'''
import matplotlib.pyplot as pltplt.scatter(iris[:, 2], iris[:, 3], c=iris[:, 4], cmap='brg')
plt.show()# 完整程序
import tensorflow as tf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt# 下载数据集文件
TRAIN_URL = "http://download.tensorflow.org/data/iris_training.csv"
train_path = tf.keras.utils.get_file("iris_training.csv", TRAIN_URL)# 定义类标题列表 读取数据集文件
COLUMN_NAMES = ['Sepallength', 'SepalWidth', 'PetaLength', 'PetalWidth', 'Spacies']
df_iris = pd.read_csv(train_path, header=0, names=COLUMN_NAMES)# 将pandas二维数据表转换成numpy二维数组
iris = np.array(df_iris)# 绘制散点图
plt.scatter(iris[:, 2], iris[:, 3], c=iris[:, 4], cmap='brg')
# 添加散点图的名称 颜色说明
plt.title("Anderson's Iris Data Set\n(Bule->Setosa | Red->Versicolor |Green->Virginica)")
# 设置坐标轴标签 标签直接从列标题列表中得到
plt.xlabel(COLUMN_NAMES[2])
plt.ylabel(COLUMN_NAMES[3])
plt.show()# 设置画布尺寸
fig = plt.figure('Iris Data', figsize=(15, 15))# 设置整个绘图的标题
fig.suptitle("Anderson's Iris Data Set\n(Blue->Setosa | Red->Versicolor | Green->virginica")# for循环绘制子图
for i in range(4):for j in range(4):#  所绘制子图的行数,列数及子图序号plt.subplot(4, 4, 4 * i + (j + 1))  # subplot(行数,列数,子图序号)if (i==j):plt.text(0.3,0.4,COLUMN_NAMES[i],fontsize=15)else:plt.scatter(iris[:, j], iris[:, i], c=iris[:, 4], cmap='brg')if (i==0):plt.title(COLUMN_NAMES[j])else:plt.ylabel(COLUMN_NAMES[i])# 调整子图间距
plt.tight_layout(rect=[0, 0, 1, 0.93])
# 显示绘图
plt.show()

手写数字图像数据集MINIST

# 下载MINIST数据集
import tensorflow as tfmnist = tf.keras.datasets.mnist
(train_x, train_y), (test_x, test_y) = mnist.load_data()# 分别输出训练集,和测试集的长度
print("Training set:", len(train_x))
print("Testing set:", len(test_x))
# Training set: 60000
# Testing set: 10000
# 输出数据的形状
print("Training set:", train_x.shape, train_x.dtype)
print("Training set:", train_y.shape, train_y.dtype)
# Training set: (60000, 28, 28) uint8
# Training set: (60000,) uint8
# uint8 表示8位无符号整数# 显示图片
import matplotlib.pyplot as plt
import numpy as npplt.axis("off")
plt.imshow(train_x[0], cmap="gray")
plt.show()
print(train_y[0])  # 输出标签 显示5# 随机显示4幅手写数字图片
# 导入需要的库
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np# 加载数据集
mnist = tf.keras.datasets.mnist
(train_x, train_y), (test_x, test_y) = mnist.load_data()# 绘图
for i in range(4):num = np.random.randint(1, 60000)plt.subplot(1, 4, i + 1)plt.axis("off")plt.imshow(train_x[num], cmap="gray")plt.title(train_y[num])plt.show()

numpy实现一元线性回归

'''
numpy实现一元线性回归步骤:1.加载数据2.设置超参数3.设置模型参数初值4.训练模型'''import numpy as np
import matplotlib.pyplot as plt# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']# 1.加载数据
x = np.array([137.97, 104.50, 100.00, 124.32, 79.20, 99.00, 124.00, 114.00,106.69, 138.05, 53.75, 46.91, 68.00, 63.02, 81.26, 86.21])
y = np.array([145.00, 110.00, 93.00, 116.00, 65.32, 104.00, 118.00, 91.00,62.00, 133.00, 51.00, 45.00, 78.50, 69.65, 75.69, 95.31])# 2.设置超参数
learn_rate = 0.0001  # 设置学习率
iter = 10 # 设置迭代次数 循环次数设置为100次disply_step = 1  # 显示间隔    每隔10次显示一次# 3.设置模型初值
np.random.seed(612)
w = np.random.randn()  # 作为W的初值
b = np.random.randn()# 4.训练模型
mse = []for i in range(0, iter + 1):# 计算梯度dL_dw = np.mean(x * (w * x + b - y))  # 偏导数求梯度dL_db = np.mean(w * x + b - y)# 使用梯度的结果更新模型的参数w = w - learn_rate * dL_dw  # 更新权值b = b - learn_rate * dL_db# 使用更新后的模型参数计算房价的估计值和均方误差pred = w * x + b  # 计算房价的估计值Loss = np.mean(np.square(y - pred)) / 2  # 计算均方误差作为损失值mse.append(Loss)  # 追加到列表中# plt.plot(x,pred)if i % disply_step == 0:print("i:%i,Loss:%f,w:%f,b:%f" % (i, mse[i],w,b))  # 每隔50次迭代显示一次当前的迭代次数和损失值# 结果可视化
plt.figure(figsize=(12, 4))plt.subplot(1, 2, 1)
plt.plot(mse)  # 子图一中绘制损失的变化曲线
plt.xlabel("Iteration", fontsize=14)
plt.ylabel("Loss", fontsize=14)plt.subplot(1, 2, 2)
pred = pred.reshape(-1)
plt.plot(y, color="red", marker="o", label="销售记录")  # 子图二中绘制样本数据
plt.plot(pred, color="blue", marker=".", label="预测房价")  # 绘制模型的预测数据
plt.xlabel("Sample", fontsize=14)
plt.ylabel("Price", fontsize=14)plt.legend()
plt.show()import numpy as np
import matplotlib.pyplot as plt# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']# 加载数据
x = np.array([137.97, 104.50, 100.00, 124.32, 79.20, 99.00, 124.00, 114.00,106.69, 138.05, 53.75, 46.91, 68.00, 63.02, 81.26, 86.21])
y = np.array([145.00, 110.00, 93.00, 116.00, 65.32, 104.00, 118.00, 91.00,62.00, 133.00, 51.00, 45.00, 78.50, 69.65, 75.69, 95.31])# 设置超参数
learn_rate = 0.0001  # 设置学习率
iter = 10  # 设置迭代次数 循环次数设置为100次disply_step = 1  # 显示间隔    每隔10次显示一次# 设置模型初值
np.random.seed(612)
w = np.random.randn()  # 作为W的初值
b = np.random.randn()# 训练模型
mse = []
for i in range(0, iter + 1):# 放在前面可以看到使用初始值时的损失值pred = w * x + b  # 计算房价的估计值Loss = np.mean(np.square(y - pred)) / 2  # 计算均方误差作为损失值mse.append(Loss)  # 追加到列表中# 计算梯度dL_dw = np.mean(x * (w * x + b - y))  # 计算偏导数dL_db = np.mean(w * x + b - y)# 使用梯度的结果更新模型的参数w = w - learn_rate * dL_dw  # 更新权值b = b - learn_rate * dL_db# plt.plot(x,pred)if i % disply_step == 0:print("i:%i,Loss:%f,w:%f,b:%f" % (i, mse[i], w, b))  # 每隔50次迭代显示一次当前的迭代次数和损失值# 结果可视化
plt.figure(figsize=(12, 4))plt.subplot(1, 2, 1)
plt.plot(mse)  # 子图一中绘制损失的变化曲线
plt.xlabel("Iteration", fontsize=14)
plt.ylabel("Loss", fontsize=14)plt.subplot(1, 2, 2)
pred = pred.reshape(-1)
plt.plot(y, color="red", marker="o", label="销售记录")  # 子图二中绘制样本数据
plt.plot(pred, color="blue", marker=".", label="预测房价")  # 绘制模型的预测数据
plt.xlabel("Sample", fontsize=14)
plt.ylabel("Price", fontsize=14)plt.legend()
plt.show()

numpy实现多元线性回归

'''
# Numpy实现多元线性回归步骤:1.加载数据2.数据处理(对样本属性进行归一化,并转换为模型需要的二维数组)3.设置超参数4,设置模型参数的初始值5.训练模型
'''import numpy as np
import matplotlib.pyplot as plt# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']# 1.加载数据
area = np.array([137.97, 104.50, 100.00, 124.32, 79.20, 99.00, 124.00, 114.00,106.69, 138.05, 53.75, 46.91, 68.00, 63.02, 81.26, 86.21])
room = np.array([3, 2, 3, 1, 2, 3, 2, 2, 3, 1, 1, 1, 1, 2, 2, 2])
price = np.array([145.00, 110.00, 93.00, 116.00, 65.32, 104.00, 118.00, 91.00,62.00, 133.00, 51.00, 45.00, 78.50, 69.65, 75.69, 95.31])
# 样本数量
num = len(area)# 2.数据处理(对样本属性进行归一化,并转换为模型需要的二维数组)
# 创建值全为1的一维数组
x0 = np.ones(num)# 对商品房面积和房间数进行归一化处理
x1 = (area - area.min()) / (area.max() - area.min())
x2 = (room - room.min()) / (room.max() - room.min())# 将x0,x1,x2堆叠为形状为(16,3)的二维数组
X = np.stack((x0, x1, x2), axis=1)
# 将房价转化为(16,1)的二维数组
Y = price.reshape(-1, 1)# 3.设置超参数
learn_rate = 0.01  # 设置学习率
iter = 50  # 设置迭代次数 循环次数设置为500次disply_step = 10  # 显示间隔    每隔50次显示一次# 4.设置模型参数的初始值
np.random.seed(612)
W = np.random.randn(3, 1)  # 随机生成形状为(3,1)的数组作为W的初值# 5.训练模型
mse = []for i in range(0, iter + 1):PRED = np.matmul(X, W)  # 线性模型表达式   计算房价的估计值Loss = np.mean(np.square(Y - PRED)) / 2  # 损失函数的表达式     计算均方误差作为损失值mse.append(Loss)  # 追加到列表中dL_dW = np.matmul(np.transpose(X), np.matmul(X, W) - Y)  # 计算梯度     计算偏导数W = W - learn_rate * dL_dW  # 更新模型     更新权值if i % disply_step == 0:print("i:%i,Loss:%f" % (i, mse[i]))  # 每隔50次迭代显示一次当前的迭代次数和损失值# 结果可视化
plt.figure(figsize=(12, 4))plt.subplot(1, 2, 1)
plt.plot(mse)  # 子图一中绘制损失的变化曲线
plt.xlabel("Iteration", fontsize=14)
plt.ylabel("Loss", fontsize=14)plt.subplot(1, 2, 2)
PRED = PRED.reshape(-1)
plt.plot(price, color="red", marker="o", label="销售记录")  # 子图二中绘制样本数据
plt.plot(PRED, color="blue", marker=".", label="预测房价")  # 绘制模型的预测数据
plt.xlabel("Sample", fontsize=14)
plt.ylabel("Price", fontsize=14)plt.legend()
plt.show()

TensorFlow实现多元线性回归

# TensorFlow实现多元线性回归import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']# 1.加载数据
area = np.array([137.97, 104.50, 100.00, 124.32, 79.20, 99.00, 124.00, 114.00,106.69, 138.05, 53.75, 46.91, 68.00, 63.02, 81.26, 86.21])
room = np.array([3, 2, 3, 1, 2, 3, 2, 2, 3, 1, 1, 1, 1, 2, 2, 2])
price = np.array([145.00, 110.00, 93.00, 116.00, 65.32, 104.00, 118.00, 91.00,62.00, 133.00, 51.00, 45.00, 78.50, 69.65, 75.69, 95.31])num = len(area)
# 2.数据处理(对样本属性进行归一化,并转换为模型需要的二维数组)
# 创建值全为1的一维数组
x0 = np.ones(num)# 对商品房面积和房间数进行归一化处理
x1 = (area - area.min()) / (area.max() - area.min())
x2 = (room - room.min()) / (room.max() - room.min())# 将x0,x1,x2堆叠为形状为(16,3)的二维数组
X = np.stack((x0, x1, x2), axis=1)
# 将房价转化为(16,1)的二维数组
Y = price.reshape(-1, 1)# 3.设置超参数
learn_rate = 0.3  # 设置学习率
iter = 50  # 设置迭代次数 循环次数设置为100次disply_step = 50  # 显示间隔    每隔10次显示一次# 4.设置模型参数初始值
np.random.seed(621)
W = tf.Variable(np.random.randn(3, 1))  # 为了能被梯度带自动监视,将w,b封装为Variable对象
b = tf.Variable(np.random.randn())# 5.训练模型
mse = []for i in range(0, iter + 1):with tf.GradientTape() as tape:PRED = tf.matmul(X, W)  # 线性模型表达式   计算房价的估计值Loss = tf.reduce_mean(tf.square(Y - PRED)) / 2  # 损失函数的表达式     计算均方误差作为损失值mse.append(Loss)  # 追加到列表中dL_dW = tape.gradient(Loss,W)  # 计算梯度     计算偏导数W.assign_sub(learn_rate*dL_dW)  # 更新模型     更新权值if i % disply_step == 0:print("i:%i,Loss:%f" % (i, Loss))

TensorFlow实现梯度下降法

# TensorFlow实现梯度下降法import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']# 1.加载数据
x = np.array([137.97, 104.50, 100.00, 124.32, 79.20, 99.00, 124.00, 114.00,106.69, 138.05, 53.75, 46.91, 68.00, 63.02, 81.26, 86.21])
y = np.array([145.00, 110.00, 93.00, 116.00, 65.32, 104.00, 118.00, 91.00,62.00, 133.00, 51.00, 45.00, 78.50, 69.65, 75.69, 95.31])# 2.设置超参数
learn_rate = 0.0001  # 设置学习率
iter = 10  # 设置迭代次数 循环次数设置为100次disply_step = 1  # 显示间隔    每隔10次显示一次# 3.设置模型参数初始值
np.random.seed(621)
w = tf.Variable(np.random.randn())  # 为了能被梯度带自动监视,将w,b封装为Variable对象
b = tf.Variable(np.random.randn())# 4.训练模型
mse = []for i in range(0, iter + 1):with tf.GradientTape() as tape:pred = w * x + b  # 线性模型表达式Loss = 0.5 * tf.reduce_mean(tf.square(y - pred))  # 损失函数的表达式mse.append(Loss)dL_dw, dL_db = tape.gradient(Loss, [w, b])  # 手动计算梯度带的代码换成使用梯度带对象的gradient方法来自动获取梯度w.assign_sub(learn_rate * dL_dw)  # 使用迭代公式更新模型参数 给Variable对象赋值需要使用他的assign方法  使用assign_sub方法实现减法运算b.assign_sub(learn_rate * dL_db)  # 使用迭代公式更新模型参数 给Variable对象赋值需要使用他的assign方法  使用assign_sub方法实现减法运算if i % disply_step == 0:print("i:%i,Loss:%f,w:%f,b:%f" % (i,Loss,w.numpy(),b.numpy()))

实现一元逻辑回归

# 逻辑回归
# 分类器:能够自动对输入的数据进行分类
#        输入:特征,输出:离散值
'''
手写数字图片————》手写数字识别
向量的形式送入分类器
28x28=784
minist手写数字数据集中每一张图片都是28x28的灰度图片 会以一个包含784各像素的一维向量的形式送入分类器中
经过分类器计算之后输出0~9十个离散的值实现分类器:准备训练样本训练分类器对样本分类单位阶跃函数(unit-step function)'''
# sigmoid()函数
import tensorflow as tfprint("TensorFlow version:", tf.__version__)import numpy as npx = np.array([1., 2., 3., 4.])w = tf.Variable(1.)
b = tf.Variable(1.)print(1 / (1 + tf.exp(w * x + b)))  # exp是求e得多少次方
# tf.Tensor([0.11920292 0.04742587 0.01798621 0.00669285], shape=(4,), dtype=float32)
# 结果也是一个形状位4的一维张量# 交叉熵损失函数
y = np.array([0, 0, 1, 1])
pred = np.array([0.1, 0.2, 0.8, 0.49])
print(1 - y)  # 1-y做广播运算 结果是一维数组
print(1 - pred)f = -tf.reduce_sum(y * tf.math.log(pred) + (1 - y) * tf.math.log(1 - pred))  # math.log()函数实现以e为底得对数运算
'''每一个样本得交叉熵损失  求和 得到所有得样本得交叉熵损失
.reduce_sum()求和
。reduce_mean() 平均交叉熵损失
'''
print(f)  # tf.Tensor(1.2649975061637104, shape=(), dtype=float64)# 实现一元线性回归
# 1.加载数据
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as pltx = np.array([137.97, 104.50, 100.00, 126.32, 79.20, 99.00, 124.00, 114.000,106.69, 140.05, 53.75, 46.91, 68.00, 63.02, 81.26, 86.21])
y = np.array([1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0])plt.scatter(x, y)
# 2.数据处理
x_train = x - np.mean(x)  # 对数据进行中心化
y_train = yplt.scatter(x_train, y_train)
# 3.设置超参数和显示间隔
learn_rate = 0.005
iter = 5disply_step = 1
# 4.设置模型变量得初始值
np.random.seed((612))
w = tf.Variable(np.random.randn())
b = tf.Variable(np.random.randn())# 5.训练模型
cross_train = []  # 存放训练集得交叉熵损失
acc_train = []  # 存放分类集的分类准确率for i in range(0, iter + 1):with tf.GradientTape() as tape:# 计算sigmoid函数pred_train = 1 / (1 + tf.exp(-(w * x_train + b)))# 交叉熵损失函数Loss_train = -tf.reduce_mean(y_train * tf.math.log(pred_train) + (1 + y_train) * tf.math.log(1 - pred_train))# 计算准确率 不需要进行求导运算 可以移到with语句外面Accuracy_train = tf.reduce_mean(tf.cast(tf.equal(tf.where(pred_train < 0.5, 0, 1), y_train), tf.float32))# 记录每一次迭代的交叉熵损失 和 准确率cross_train.append(Loss_train)acc_train.append(Accuracy_train)# 获得损失函数对w和b的偏导数dL_dw, dL_db = tape.gradient(Loss_train, [w, b])# 更新模型参数w.assign_sub(learn_rate * dL_dw)b.assign_sub((learn_rate * dL_db))# 输出训练过程和结果if i % disply_step == 0:print("i:%i,Train Loss:%f,Accuracy:%f" % (i, Loss_train, Accuracy_train))

波士顿房价预测01

import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf# 1.加载数据集
boston_housing = tf.keras.datasets.boston_housing
(train_x, train_y), (test_x, test_y) = boston_housing.load_data()print(train_x.shape, train_y.shape)  # (404, 13) (404,) 表示:404条样本,13条属性print(test_x.shape, test_y.shape)  # (102, 13) (102,)# 2.数据处理
x_train = train_x[:, 5]  # 取出所有训练样本中的房间数
y_train = train_y  # 房价
print(x_train.shape, y_train.shape)  # (404,) (404,) 房间数,和房价都是一维数组x_test = test_x[:, 5]  # 测试集的房间数
y_test = test_y  # 测试集上的房价
print(x_test.shape, y_test.shape)# 3.设置超参数
learn_rate = 0.04  # 学习率设为0。04
iter = 2000  # 迭代次数设为2000
disply_step = 200  # 显示间隔设为200# 4.设置模型参数初始值
np.random.seed(612)
w = tf.Variable(np.random.randn())
b = tf.Variable(np.random.randn())
print(w.numpy().dtype, b.numpy().dtype)  # float32 float32# 5.训练模型
mse_train = []  # 用来记录训练集上的损失   mse:mean square error
mse_test = []  # 用来记录测试集上的损失for i in range(0, iter + 1):with tf.GradientTape() as tape:# 把他们放在GradientTape的with语句中实现对wb的监视pred_train = w * x_train + b # 计算训练集上的预测值loss_train = 0.5 * tf.reduce_mean(tf.square(y_train - pred_train)) # 计算训练集上的均方误差pred_test = w * x_test + bloss_test = 0.5 * tf.reduce_mean(tf.square(y_test - pred_test))mse_train.append(loss_train) # 把训练误差记录在列表中mse_test.append(loss_test)dL_dw, dL_db = tape.gradient(loss_train, [w, b]) # 使用训练集中的数据计算损失函数对w b的梯度w.assign_sub(learn_rate * dL_dw) # 使用算出的梯度更新w bb.assign_sub(learn_rate * dL_db)if i % disply_step == 0:print("i:%i, Train Loss:%f, Test Loss:%f" %(i,loss_train,loss_test))'''使用训练集上的数据更新模型参数,测试集没有参与
但在每一步迭代中都使用当前的模型参数w b 计算测试集上的误差,并将其记录在mse_test列表中'''# 6.可视化输出
plt.figure(figsize=(15,10))plt.subplot(221)
plt.scatter(x_train,y_train,color="blue",label="data") # 绘制散点图
plt.plot(x_train,pred_train,color="red",label="model")  # 绘制模型直线
plt.legend(loc="upper left")plt.subplot(222)
plt.plot(mse_train,color="blue",linewidth=3,label="train loss")
plt.plot(mse_test,color="red",linewidth=1.5,label="test lost")
plt.legend(loc="upper right")plt.subplot(223)
plt.plot(y_train,color="blue",marker="o",label="true_price")
plt.plot(pred_train,color="red",marker=".",label="predict")
plt.legend()plt.subplot(224)
plt.plot(y_test,color="blue",marker="o",label="true_price")
plt.plot(pred_test,color="red",marker=".",label="predict")
plt.legend()plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gjxaYeqF-1605190599122)(TensorFlow.assets/波士顿房价预测01.png)]

波士顿房价预测02

# 二维数组归一化---循环语句实现
import numpy as npx = np.array([[3., 10., 500],[2., 20., 200],[1., 30., 300],[5., 50., 100]])print(x.shape)
print(len(x))
print(x.shape[0], x.shape[1])for i in range(x.shape[1]):# 对第i列归一化x[:, i] = (x[:, i] - x[:, i].min()) / (x[:, i].max() - x[:, i].min())print(x)  # 循环完成之后所有的列都被归一化# 二维数组归一化————广播运算
x = np.array([[3., 10., 500],[2., 20., 200],[1., 30., 300],[5., 50., 100]])print(x.min(axis=0))  # 每一列的最小值
print(x.max(axis=0))  # 每一列的最大值
print(x.max(axis=0) - x.min(axis=0))  # 最大值减去最小值print(x - x.min(axis=0))  # x-x.min(axis=0) 进行广播运算print((x - x.min(axis=0)) / (x.max(axis=0) - x.min(axis=0)))  # 广播运算 实现对数组的归一化处理
'''
不用进行循环运算,代码简洁,效率更高
'''# 波士顿房价归一化处理
# 1.导入需要的库 加载数据集
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as npboston_housing = tf.keras.datasets.boston_housing
(train_x, train_y), (test_x, test_y) = boston_housing.load_data()print(train_x.shape, train_y.shape)
print(test_x.shape, test_y.shape)
# 训练集和测试集中样本的数量(创建全一数组时需要使用)
num_train = len(train_x)
num_test = len(test_x)# 2.数据处理
# 对训练样本的所有属性进行归一化
x_train = (train_x - train_x.min(axis=0)) / (train_x.max(axis=0) - train_x.min(axis=0))
y_train = train_y  # 标签y不需要归一化,但是也进行重新赋值# 对测试样本的所有属性进行归一化
x_test = (test_x - test_x.min(axis=0)) / (test_x.max(axis=0) - test_x.min(axis=0))
y_test = test_y  # 标签y不需要归一化,但是也进行重新赋值# 生成多元回归需要的二元数组的形式
x0_train = np.ones(num_train).reshape(-1, 1)
x0_test = np.ones(num_test).reshape(-1, 1)X_train = tf.cast(tf.concat([x0_train, x_train], axis=1), tf.float32)  # .concat() 是tensorflow的数组堆叠函数
X_test = tf.cast(tf.concat([x0_test, x_test], axis=1), tf.float32)  # .cast() 是tensorflow的类型转换函数 指定为32位浮点数print(X_train.shape, X_test.shape)  # (404, 14) (102, 14) 404个元素  13个属性归一化+堆叠的全为1的属性Y_train = tf.constant(y_train.reshape(-1, 1), tf.float32)  # 把房价转换成列向量
Y_test = tf.constant(y_test.reshape(-1, 1), tf.float32)print(Y_train.shape, Y_test.shape)# 3.设置超参数
learn_rate = 0.01
iter = 3000
display_step = 100# 4.设置模型变量的初始值
np.random.seed(612)
W = tf.Variable(np.random.randn(14, 1), dtype=tf.float32)# 5.训练模型
mse_train = []
mse_test = []for i in range(0, iter + 1):with tf.GradientTape() as tape:# 计算训练集的预测房价和损失PRED_train = tf.matmul(X_train, W)Loss_train = 0.5 * tf.reduce_mean(tf.square(Y_train - PRED_train))# 计算测试集的预测房价和损失PRED_test = tf.matmul(X_test, W)Loss_test = 0.5 * tf.reduce_mean(tf.square(Y_test - PRED_test))# 记录每一次迭代之后使用更新后的参数(模型在训练集上的损失,和在测试集上的损失值)mse_train.append(Loss_train)mse_test.append(Loss_test)# 使用训练集中的样本更新模型参数dL_dW = tape.gradient(Loss_train, W)W.assign_sub(learn_rate * dL_dW)if i % display_step == 0:# 输出训练集和测试集上的损失print("i:%i, Train Loss:%f, Test Loss:%f" % (i, Loss_train, Loss_test))# 可视化输出
plt.figure(figsize=(20,4))plt.subplot(131)
plt.ylabel("MSE")
plt.plot(mse_train,color="blue",linewidth=3)# mse:mean square error 均方误差
plt.plot(mse_test,color="red",linewidth=1.5)plt.subplot(132)
plt.plot(y_train,color="blue",marker="o",label="true_price") # .polt() 绘制线图
plt.plot(PRED_train,color="red",marker=".",label="predict")
plt.legend(loc="upper right")  # .legend() 显示图中标签
plt.ylabel("Price")plt.subplot(133)
plt.plot(y_test,color="blue",marker="o",label="true_price")
plt.plot(PRED_test,color="red",marker=".",label="predict")
plt.legend()
plt.ylabel("Price")plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TEurexsc-1605190599128)(TensorFlow.assets/波士顿房价预测02.png)]

波士顿房价可视化

'''
keras:是一个高层的神经网络和深度学习库可以快速搭建神经网络模型,非常易于调试和扩展Tensorflow的官方API内置了一些常用的公共数据库,可以通过Keras.datasets模块加载和访问在机器学习中通常将数据集划分为:训练数据集和测验数据集
'''
# 加载和使用kears中的内置数据集
# 加载数据集
'''
tensorflow.keras.datasets.boston_housing
tensorflow.keras 意思:是keras API 在tensorflow中的实现
'''
import tensorflow as tfboston_housing = tf.keras.datasets.boston_housing(train_x, train_y), (test_x, test_y) = boston_housing.load_data(test_split=0)  # 使用这个数据集中的load_data方法加载数据集
'''train_x和train_y接受训练数据集的数据
可以使用test_split=0.2 改变测试数据集在数据集中所占的比例'''
print('Training set:', len(train_x))
print('Testing set:', len(test_x))print(type(train_x))
print(type(train_y))print('Dim of train_x:', train_x.ndim)
print('Shape of train_x:', train_x.shape)
# Training set: 506
# Testing set: 0
# <class 'numpy.ndarray'>
# <class 'numpy.ndarray'>
# Dim of train_x: 2
# Shape of train_x: (506, 13)print(train_x[:5])  # train_x中的前五行数据# 绘制散点图(平均房间数与房价之间的关系)
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tfboston_housing = tf.keras.datasets.boston_housing
(train_x, train_y), (_, _) = boston_housing.load_data(test_split=0)plt.figure(figsize=(5, 5))  # 设置绘图尺寸
plt.scatter(train_x[0:,5], train_y)  # 绘制散点图
plt.xlabel('RM')  # 设置x轴标签文本
plt.ylabel("Price($1000's)")  # 设置y轴标签文本
plt.title("5.RM-Price")  # 设置标题
plt.show()  # 显示绘图# 波士顿房价数据集可视化
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf# 加载数据集
boston_housing = tf.keras.datasets.boston_housing
(train_x,train_y),(_,_) = boston_housing.load_data(test_split=0)# 设置运行时参数
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False# 定义属性标题列表
titles = ["CRIM","ZN","INDUS","CHAS","NOX","RM","AGE","DIS","RAD","TAX","PTRATIO","B-1000","LSTAT","MEDV"]# 设置画布尺寸
plt.figure(figsize=(12,12)) # 设置画布尺寸# 执行循环体 分别绘制13个子图
for i in range(13):plt.subplot(4,4,(i+1))plt.scatter(train_x[:,i],train_y)plt.xlabel(titles[i])   # 子图x轴标签plt.ylabel("Price($1000's)")    # 子图y轴标签plt.title(str(i+1)+'.'+titles[i]+" - Price")    # 子图标题plt.tight_layout(rect=[0, 0, 1, 0.9])  # 调整子图间隔
plt.suptitle("各个属性与房价的关系",x=0.5,y=1.02,fontsize=20) # 设置全局标题
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-H4fHodMv-1605190599130)(TensorFlow.assets/波士顿房价可视化01.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YJ2UMwpu-1605190599133)(TensorFlow.assets/波士顿房价可视化02.png)]

梯度下降法求多元线性回归

import numpy as np
import matplotlib.pyplot as plt# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']# 1.加载数据
area = np.array([137.97, 104.50, 100.00, 124.32, 79.20, 99.00, 124.00, 114.00,106.69, 138.05, 53.75, 46.91, 68.00, 63.02, 81.26, 86.21])
room = np.array([3, 2, 3, 1, 2, 3, 2, 2, 3, 1, 1, 1, 1, 2, 2, 2])
price = np.array([145.00, 110.00, 93.00, 116.00, 65.32, 104.00, 118.00, 91.00,62.00, 133.00, 51.00, 45.00, 78.50, 69.65, 75.69, 95.31])
# 样本数量
num = len(area)# 2.数据处理
# 创建值全为1的一维数组
x0 = np.ones(num)# 对商品房面积和房间数进行归一化处理
x1 = (area - area.min()) / (area.max() - area.min())
x2 = (room - room.min()) / (room.max() - room.min())# 将x0,x1,x2堆叠为形状为(16,3)的二维数组
X = np.stack((x0, x1, x2), axis=1)
# 将房价转化为(16,1)的二维数组
Y = price.reshape(-1, 1)# 3.设置超参数
learn_rate = 0.001  # 设置学习率
iter = 6000  # 设置迭代次数 循环次数设置为500次disply_step = 30  # 显示间隔    每隔50次显示一次# 设置模型参数的初始值
np.random.seed(612)
W = np.random.randn(3, 1)  # 随机生成形状为(3,1)的数组作为W的初值# 4.训练模型
mse = []
for i in range(0, iter + 1):dL_dW = np.matmul(np.transpose(X), np.matmul(X, W) - Y)  # 计算偏导数W = W - learn_rate * dL_dW  # 更新权值PRED = np.matmul(X, W)  # 计算房价的估计值Loss = np.mean(np.square(Y - PRED)) / 2  # 计算均方误差作为损失值mse.append(Loss)  # 追加到列表中if i % disply_step == 0:print("i:%i,Loss:%f" % (i, mse[i]))  # 每隔50次迭代显示一次当前的迭代次数和损失值# 5.结果可视化
plt.figure(figsize=(12, 4))plt.subplot(1, 2, 1)
plt.plot(mse)  # 子图一中绘制损失的变化曲线
plt.xlabel("Iteration", fontsize=14)
plt.ylabel("Loss", fontsize=14)plt.subplot(1, 2, 2)
PRED = PRED.reshape(-1)
plt.plot(price, color="red", marker="o", label="销售记录")  # 子图二中绘制样本数据
plt.plot(PRED, color="blue", marker=".", label="预测房价")  # 绘制模型的预测数据
plt.xlabel("Sample", fontsize=14)
plt.ylabel("Price", fontsize=14)plt.legend()
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-itTKgmVS-1605190599141)(TensorFlow.assets/梯度下降法.png)]

TensorFlow2.0基础学习笔记相关推荐

  1. 日语课程0基础学习笔记——第一课

    学习目标: 编程0基础学习笔记--前言 这是一个个人使用的日语学习记录博客!根据B站的up日语教程一直跟下来,从第一天开始记录.后续会把我学习的内容和知识点尽量多的记录在这个博客中,不仅是方便自己复习 ...

  2. guido正式发布python年份_Python 基础学习笔记.docx

    Python 基础学习笔记 基于<Python语言程序设计基础(第2版)> 第一部分 初识Python语言 第1章 程序设计基本方法 1.1 计算机的概念 计算机是根据指令操作数据的设备, ...

  3. ASP.Net MVC开发基础学习笔记(5):区域、模板页与WebAPI初步

    http://blog.jobbole.com/85008/ ASP.Net MVC开发基础学习笔记(5):区域.模板页与WebAPI初步 2015/03/17 · IT技术 · .Net, Asp. ...

  4. Python3 基础学习笔记 C09【文件和异常】

    CSDN 课程推荐:<8小时Python零基础轻松入门>,讲师齐伟,苏州研途教育科技有限公司CTO,苏州大学应用统计专业硕士生指导委员会委员:已出版<跟老齐学Python:轻松入门& ...

  5. Python3 基础学习笔记 C08 【类】

    CSDN 课程推荐:<8小时Python零基础轻松入门>,讲师齐伟,苏州研途教育科技有限公司CTO,苏州大学应用统计专业硕士生指导委员会委员:已出版<跟老齐学Python:轻松入门& ...

  6. Python3 基础学习笔记 C06【用户输入和 while 循环】

    CSDN 课程推荐:<8小时Python零基础轻松入门>,讲师齐伟,苏州研途教育科技有限公司CTO,苏州大学应用统计专业硕士生指导委员会委员:已出版<跟老齐学Python:轻松入门& ...

  7. Python3 基础学习笔记 C05【字典】

    CSDN 课程推荐:<8小时Python零基础轻松入门>,讲师齐伟,苏州研途教育科技有限公司CTO,苏州大学应用统计专业硕士生指导委员会委员:已出版<跟老齐学Python:轻松入门& ...

  8. Python3 基础学习笔记 C04【if 语句】

    CSDN 课程推荐:<8小时Python零基础轻松入门>,讲师齐伟,苏州研途教育科技有限公司CTO,苏州大学应用统计专业硕士生指导委员会委员:已出版<跟老齐学Python:轻松入门& ...

  9. Python3 基础学习笔记 C03【操作列表】

    CSDN 课程推荐:<8小时Python零基础轻松入门>,讲师齐伟,苏州研途教育科技有限公司CTO,苏州大学应用统计专业硕士生指导委员会委员:已出版<跟老齐学Python:轻松入门& ...

最新文章

  1. build怎么调试 react_webpack打包调试react并使用babel编译jsx配置方法
  2. MySQL系列: undo和redo工作原理
  3. 页面性能优化参考建议
  4. Android中的AutoCompleteTextView组件
  5. linux修改栈指针x86,x86-堆栈指针未填充16时libc的system()导致分段...
  6. CAFFE(FAQ.2):Ubuntu 配置caffe 框架之数据库读取,错误解决:ImportError: No module named leveldb解决办法...
  7. 一周内被程序员疯转 2.4 W次,最终被大厂封杀!
  8. validate参数校验和数据回显
  9. snprintf的返回值代表字节数 != 实际写入字节数
  10. WebService与RestAPI 、SoapAPI
  11. matlab nastran,nastran op2 matlab
  12. C++实现均值滤波器和中值滤波器
  13. dosbox运行C语言,[转载]dosbox的使用方法
  14. iphone自适应屏幕亮度_如何降低iPhone的亮度低于iOS允许的亮度
  15. Firefox OS开发指南
  16. uni-app 从本地相册选择图片或使用相机拍照
  17. Git 远程篇之查看远程仓库信息
  18. R语言 coalesce 函数
  19. TensorFlow入门教程(16)分离歌曲中的人声和背景音乐
  20. Linux的一些简单命令操作,好懂易学(1)

热门文章

  1. 崩坏三服务器维护,崩坏3登录过程所遇问题解决方法汇总
  2. 期刊评价标准JCR,IF,SJR以及如何查询期刊等级
  3. Linux下如何拷贝隐藏文件
  4. 仁微电子-医院智慧病房物联网系统
  5. 3年已过,你知道这些目标网站,过去是如何被爬的吗?爬虫100例复盘5
  6. android 相机 app,android – Emulator的相机内置app buggy在Froyo / 2.2?
  7. python应用程序无法正常启动0xc00007b_详细教您解决应用程序无法正常启动(0xc000007b)...
  8. ch340串口驱动_如何使用串口来给STM32下载程序
  9. Kaggle: Jigsaw Multilingual Toxic Comment Classification Top Solutions 金牌思路总结
  10. 处理echarts地图省份坐标重叠的方法