Compare commits

...

6 Commits

12 changed files with 567 additions and 0 deletions

69
ANN_TF2.py Normal file
View File

@ -0,0 +1,69 @@
# 导入必要的库
import tensorflow as tf
from keras import datasets, layers, models
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('TkAgg') # 使用 TkAgg 后端
import matplotlib.pyplot as plt
# 主函数入口
if __name__ == '__main__':
# 加载 MNIST 数据集。分为训练集和测试集
(train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data()
# 对图像数据进行标准化处理,将像素值缩放到 0-1 之间
train_images, test_images = train_images / 255.0, test_images / 255.0
# 打印数据维度信息
print("data_shpe:",train_images.shape,test_images.shape,train_labels.shape,test_labels.shape)
"""
输出((60000, 28, 28), (10000, 28, 28), (60000,), (10000,))
"""
# 绘制训练图像的示例
plt.figure(figsize=(20, 10))
for i in range(20):
plt.subplot(2, 10, i + 1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i], cmap=plt.cm.binary)
plt.xlabel(train_labels[i])
plt.show()
# 调整图像数据的维度,以符合模型的输入要求
train_images = train_images.reshape((60000, 28, 28, 1))
test_images = test_images.reshape((10000, 28, 28, 1))
# 再次打印调整后的数据维度信息
print("data_shpe:",train_images.shape, test_images.shape, train_labels.shape, test_labels.shape)
"""
输出((60000, 28, 28, 1), (10000, 28, 28, 1), (60000,), (10000,))
"""
# 构建卷积神经网络模型
model = models.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(10)
])
model.summary() # 打印模型结构
# 编译模型,设置优化器、损失函数和评价指标
model.compile(
optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
# 训练模型
history = model.fit(
train_images,
train_labels,
epochs=10,
)

109
ANN_mnist.py Normal file
View File

@ -0,0 +1,109 @@
#===============================================
# 训练简单的神经网络,并显示运行时间
# 数据集mnnist
#===============================================
"""from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import datetime
starttime = datetime.datetime.now()
import tensorflow as tf
import numpy as np
# Import data
from tensorflow.examples.tutorials.mnist import input_data
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('data_dir', '/learn/tensorflow/python/data/', 'Directory for storing data') # 把数据放在/data文件夹中
mnist_data = input_data.read_data_sets(FLAGS.data_dir, one_hot=True) # 读取数据集
# 建立抽象模型
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]))
a = tf.nn.softmax(tf.matmul(x, W) + b)
# 定义损失函数和训练方法
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(a), reduction_indices=[1])) # 损失函数为交叉熵学习速率要设为0.3量级
#cross_entropy = -tf.reduce_sum(y * tf.log(a)) # 损失函数为交叉熵
optimizer = tf.train.GradientDescentOptimizer(0.3) # 梯度下降法学习速率要设为0.001量级
train_next = optimizer.minimize(cross_entropy) # 训练目标:最小化损失函数
# Train
sess = tf.InteractiveSession() # 建立交互式会话
# tf.global_variables_initializer().run()
sess.run(tf.global_variables_initializer())
for i in range(1000):
batch_xs, batch_ys = mnist_data.train.next_batch(100) # 随机抓取100个数据
# train_next.run({x: batch_xs, y: batch_ys})
sess.run(train_next, feed_dict={x: batch_xs, y: batch_ys})
#测试
correct_prediction = tf.equal(tf.argmax(a, 1), tf.argmax(y, 1))
# tf.cast先将数据转换成float防止求平均不准确:比如 tf.float32就是正确写成tf.float16导致不准确超出范围。
accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))
print(sess.run(accuracy,feed_dict={x:mnist_data.test.images,y:mnist_data.test.labels}))
endtime=datetime.datetime.now()
print('total time endtime-starttime:', endtime-starttime)"""
"""由于tensorflow更新至了2.0,1.0的方法许多已经被合并调整后弃用了,所以使用chatgpt更新了2.0版本的代码如下"""
# 导入 TensorFlow 和相关的 Keras 类和函数
import tensorflow as tf
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import SGD
import datetime
# 加载 MNIST 数据集,这是一个手写数字的图像数据集,用于训练和测试机器学习模型。
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 对数据进行归一化处理,将像素值从 [0, 255] 缩放到 [0, 1] 区间,这有助于模型的训练。
x_train, x_test = x_train / 255.0, x_test / 255.0
# 将图像数据从 28x28 的矩阵形式转换成 784 维的向量形式。
x_train = x_train.reshape(-1, 784)
x_test = x_test.reshape(-1, 784)
# 将标签转换为 one-hot 编码,这是将分类标签转换为仅在对应类的位置为 1其余为 0 的向量。
y_train = tf.keras.utils.to_categorical(y_train, 10)
y_test = tf.keras.utils.to_categorical(y_test, 10)
# 创建一个 Sequential 模型。这是一种线性堆叠的模型,您可以通过在列表中添加层来构建模型。
model = Sequential([
Dense(10, activation='softmax', input_shape=(784,))
])
# 编译模型。这一步设置了模型的优化器、损失函数和评估指标。
# - 使用 SGD随机梯度下降优化器。
# - 损失函数使用 categorical_crossentropy适用于多分类问题。
# - 评估指标使用准确率accuracy
model.compile(optimizer=SGD(lr=0.3),
loss='categorical_crossentropy',
metrics=['accuracy'])
# 记录训练开始时间。
starttime = datetime.datetime.now()
# 训练模型。这里使用 fit 方法对模型进行训练。
# - x_train 和 y_train 是训练数据和标签。
# - epochs=10 表示总共训练 10 个周期。
# - batch_size=100 指定每次梯度更新时使用的样本数量。
model.fit(x_train, y_train, epochs=10, batch_size=100)
# 记录训练结束时间。
endtime = datetime.datetime.now()
# 在测试集上评估模型性能。
# - x_test 和 y_test 是测试数据和标签。
# 这里返回的是模型在测试数据上的损失值和准确率。
loss, accuracy = model.evaluate(x_test, y_test)
print(f"Test Accuracy: {accuracy}")
# 打印总的训练时间。
print('Total time (endtime - starttime):', endtime - starttime)

98
IO.py Normal file
View File

@ -0,0 +1,98 @@
# ====================================================================
# 保存和输入matlat格式数据并画图显示
#
# ====================================================================
import scipy.io as sio
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import os
# 通过以下三段代码来保证scipy.io.savemat 函数的正常运行
# 指定要保存的文件路径
file_path = 'data/testpython.mat'
# 获取文件夹路径
folder_path = os.path.dirname(file_path)
# 如果文件夹不存在,则创建它
if not os.path.exists(folder_path):
os.makedirs(folder_path)
# 创建4个变量并赋值
sio.savemat('data/testpython.mat', {'a': 1, 'b': 5, 'c': 3, 'd': 4})
"""
这行代码调用savemat函数来保存数据
'data/testpython.mat':
这是你想要保存文件的路径和文件名这里的例子中,文件会被保存在名为data的文件夹下,文件名为testpython.mat
{'a': 1, 'b': 5, 'c': 3, 'd': 4}:
这是一个Python字典,其中包含了你想要保存到.mat文件中的数据在这个例子中,你有四个键值对,键是'a', 'b', 'c', 'd',相应的值是1, 5, 3, 和4
注意:scipy.io.savemat 函数在保存 MATLAB 格式的 .mat 文件时默认情况下不会自动创建不存在的文件路径如果指定的文件路径不存在函数会引发一个错误
因此需要在使用scipy.io.savemat前确保文件存在
"""
# 创建了一个变量x并赋予一个矩阵
sio.savemat('data/testpython2.mat', {'x': [[1, 3, 5, 4], [5, 3, 2, 8]]})
# 读取“testpython.mat”文件内容并赋值给data变量
data = sio.loadmat('data/testpython.mat')
# 同上
data2 = sio.loadmat('data/testpython2.mat')
# 创建一个内值全为零的数组变量x
x = np.zeros([1, 4])
"""
np.zeros()是NumPy提供的一个函数,用于创建一个包含零值的数组
[1, 4]是传递给np.zeros()函数的参数,它指定了要创建的数组的形状在这个例子中,它是一个包含1行和4列的数组
"""
# 分别对x变量数组内的各值进行赋值
x[0][0] = data['a']
x[0][1] = data['b']
x[0][2] = data['c']
x[0][3] = data['d']
y = data2['x']
# 打印x及其数据类型以及y矩阵中第一行的内容及其数据类型
print(x, f"x的数据类型为{x.dtype}", y[0], f"y中第一列的数据类型为{y[0].dtype}")
# 初始化一个图形对象,然后可以在该图形上绘制不同的图表或子图。
fig = plt.figure()
# 在fig上创建一个带有三维坐标系的子图
ax = fig.add_subplot(111, projection='3d')
"""
.add_subplot(111, projection='3d')这是在图形对象 fig 中添加一个三维坐标系的子图的操作
111:这个参数表示将图形分割成一个 1x1 的网格并选择网格中的第一个位置这意味着整个图形窗口只包含一个子图占据整个窗口
projection='3d':这个参数指定了子图的投影类型为三维坐标系(3D)这意味着你可以在这个子图中绘制三维图表,例如三维散点图曲面图等
"""
# 设定散点的xyz数据
xs = x
ys = y[0]
zs = y[1]
# 画出对应位置的点
ax.scatter(xs, ys, zs, c='b', marker='o')
# 给xyz轴加上标签
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
# 显示图像
plt.show()
# 释放资源并清除图形
plt.close()

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
data/testpython.mat Normal file

Binary file not shown.

BIN
data/testpython2.mat Normal file

Binary file not shown.

87
ne_PM.py Normal file
View File

@ -0,0 +1,87 @@
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# TensorFlow 2.x 使用 Keras API
from keras.optimizers import SGD
# 确保我们正在使用 TensorFlow 2.x
print("TensorFlow version:", tf.__version__)
# 生成训练数据
x_train = np.float32(np.random.rand(2, 100))
y_train = np.dot([5.000, 7.000], x_train) + 2.000
# 构建线性模型
class LinearModel(tf.keras.Model):
def __init__(self):
super(LinearModel, self).__init__()
self.W = tf.Variable(tf.zeros([1, 2]), name='weight')
self.b = tf.Variable(tf.zeros([1]), name='bias')
def call(self, inputs):
return tf.matmul(self.W, inputs) + self.b
model = LinearModel()
# 定义损失函数和优化器
loss_object = tf.keras.losses.MeanSquaredError()
optimizer = SGD(learning_rate=0.5)
# 训练步骤封装
@tf.function
def train_step(inputs, outputs):
with tf.GradientTape() as tape:
predictions = model(inputs)
loss = loss_object(outputs, predictions)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
return loss
# 训练模型
m = 101
W_temp, b_temp = [], []
for step in range(m):
loss = train_step(x_train, y_train)
if step % 20 == 0:
print("Step {:02d}: Loss {:.3f}, W {}, b {}".format(
step, loss, model.W.numpy(), model.b.numpy()))
W_temp.append(model.W.numpy()[0])
b_temp.append(model.b.numpy()[0])
# 参数可视化
fig, ax = plt.subplots()
step = np.arange(0, m, 20)
ax.plot(step, [w[0] for w in W_temp], marker='o', label='W1')
ax.plot(step, [w[1] for w in W_temp], marker='*', label='W2')
ax.plot(step, b_temp, marker='^', label='b')
ax.legend()
ax.set_xlabel('step')
ax.set_ylabel('value')
ax.set_title('Parameter')
# 生成测试数据
x_test = np.float32(np.random.rand(2, 100))
y_test = np.dot([5.000, 7.000], x_test) + 2.000
# 测试模型
y_pred = model(x_test)
y_diff = abs(y_pred - y_test)
y_diff = np.where(y_diff > 0.01, y_diff, 1)
accuracy = np.sum(y_diff == 1) / len(y_diff[0])
print('accuracy:', accuracy)
# 测试结果可视化
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
xs, ys = x_test[0], x_test[1]
zs1, zs2 = y_test, y_pred.numpy()[0]
ax.scatter(xs, ys, zs1, c='r', marker='v') # 真实值
ax.scatter(xs, ys, zs2, c='b', marker='^') # 预测值
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# 显示图表
plt.show()

41
ne_ZL_TF2.py Normal file
View File

@ -0,0 +1,41 @@
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# 准备初始数据
x_data = np.float32(np.random.rand(100)) # 生成 100 个随机数,作为输入数据
y_data = x_data * 2 + 1.6 # 根据线性方程 y = 2x + 1.6 生成输出数据
# 初始化权重W和偏置b变量
weights = tf.Variable(tf.zeros([1]), name='weights') # 初始化权重为 0
biases = tf.Variable(tf.zeros([1]), name='biases') # 初始化偏置为 0
# 定义模型
def linear_model(x):
return weights * x + biases
# 定义损失函数
def loss_fn(y_true, y_pred):
return tf.reduce_mean(tf.square(y_true - y_pred))
# 定义优化器
optimizer = tf.optimizers.SGD(0.5) # 梯度下降优化器,学习率为 0.5
# 训练过程
def train_step(x, y):
with tf.GradientTape() as tape:
y_pred = linear_model(x)
loss = loss_fn(y, y_pred)
gradients = tape.gradient(loss, [weights, biases])
optimizer.apply_gradients(zip(gradients, [weights, biases]))
# 训练模型
for step in range(201):
train_step(x_data, y_data)
if step % 20 == 0:
print(f"Step {step}: weights = {weights.numpy()}, biases = {biases.numpy()}")
# 绘图(可选)
plt.scatter(x_data, y_data, c='r')
plt.plot(x_data, linear_model(x_data), c='g')
plt.show()

163
picture.py Normal file
View File

@ -0,0 +1,163 @@
# ===============================================================
# 画图柱状图散点图拆线图3D图概率分布图累计概率分布图
# ===============================================================
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
# ===============================================================
# 柱状图
plt.subplot(221) # 创建一个两行两列的子图列表,并选取左上角第一个子图作为当前子图
size = 5
x = np.arange(size) # 返回等差数列从0开始到5默认步长为1
a = np.random.random(size) # 返回五个随机数范围0-1
b = np.random.random(size)
width = 0.3
plt.bar(x+width/2, a, label='a', width=width)
plt.bar(x+width*3/2, b, label='b', width=width)
'''
plt.bar Matplotlib 库中的一个函数用于创建柱状图它的语法如下
plt.bar(x, height, width=0.8, align='center', **kwargs)
参数说明
x:柱状图的 x 坐标位置,可以是一个数值序列或类别名称序列
height:柱状图的高度,可以是一个数值序列表示每个柱的高度
width:柱状图的宽度,默认为 0.8
align:柱状图的对齐方式,默认为 'center'表示柱状图的中心与 x 坐标对齐
**kwargs:可选的关键字参数,用于设置柱状图的其他属性,如颜色标签等
plt.bar 函数会根据给定的 x 坐标位置和高度创建柱状图可以通过设置不同的参数来调整柱状图的样式和属性,如宽度对齐方式颜色等
'''
plt.legend()
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('plot')
plt.show()
# ===============================================================
# 散点图
plt.subplot(222) # 创建一个两行两列的子图列表,并选取右上角第一个子图作为当前子图
x = np.random.random(10)
y = np.random.random(10)
plt.scatter(x, y, s=15, c='b', marker=(6, 1), alpha=0.7, lw=2)
# 设置xy轴的范围
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.show()
# ===============================================================
# 拆线图
plt.subplot(223) # 创建一个两行两列的子图列表,并选取左下角第一个子图作为当前子图
size = 5
x = np.arange(size)
a = np.random.random(size)
b = np.random.random(size)
plt.plot(x, a, marker='o', mec='b', mfc='b', label=u'y=a')
"""
使用 Matplotlib 库中的 plot 函数绘制折线图它的语法如下
plt.plot(x, y, **kwargs)
参数说明
x:x 轴上的数据点可以是一个数值序列
y:y 轴上的数据点可以是一个数值序列
**kwargs:可选的关键字参数用于设置折线图的其他属性如标记样式线条颜色标签等
在代码中,x x 轴上的数据点,a y 轴上的数据点marker='o' 设置折线图上的标记样式为圆圈,mec='b' mfc='b' 设置标记的边框颜色和填充颜色都为蓝色label=u'y=a' 设置折线图的标签为 "y=a"
通过调用 plt.plot 函数可以将数据点连接起来生成一条折线图可以通过设置不同的参数来调整折线图的样式和属性如标记样式线条颜色标签等
"""
plt.plot(x, b, marker='*', ms=10, label=u'y=b')
plt.legend()
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('plot')
plt.show()
# ===============================================================
# 3D图
# ===============================================================
# plt.subplot(224)
# 定义函数
def rand_range(n, vmin, vmax):
'''
make an array of random numbers having shape (n, )
with each number distributed Uniform(vmin, vmax).
'''
return (vmax - vmin) * np.random.rand(n) + vmin
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') # 在fig对象中添加一个三维子图
# plot n random points in the box
# defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh].
n = 5
# 添加不同格式的点第一种为红色圆点z取值范围为-50~-25第二种为蓝色三角形点z取值范围在-30~-5
for c, m, zlow, zhigh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:
xs = rand_range(n, 20, 30)
ys = rand_range(n, 30, 100)
zs = rand_range(n, zlow, zhigh)
ax.scatter(xs, ys, zs, c=c, marker=m)
# 单独一个散点(绿色星型)
ax.scatter(25, 50, -25, c='g', marker="*")
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()
# ===============================================================
# 概率分布图,累计概率分布图
# ===============================================================
# 概率分布直方图
# 高斯分布
mean = 0 # 均值为0
sigma = 1 # 标准差为1反应数据集中还是分散的值
x = mean+sigma*np.random.randn(10000)
# 第二个参数是柱子宽一些还是窄一些,越大越窄越密
fig, (ax0, ax1) = plt.subplots(nrows=2, figsize=(6, 6))
"""
参数说明
nrows=2:指定子图的行数为 2
figsize=(6, 6)指定图像窗口的大小为 6x6 英寸
plt.subplots 函数返回一个包含子图对象的元组,其中的每个子图对象可以通过元组解包的方式分别赋值给不同的变量在这个例子中,ax0 ax1 分别表示第一个子图和第二个子图
通过创建包含多个子图的图像窗口可以在不同的子图上绘制不同的图形或数据并且可以通过调整子图的位置大小等属性来自定义图像的布局
"""
# pdf概率分布图一万个数落在某个区间内的数有多少个
ax0.hist(x, bins=40, density=True, histtype='bar',
facecolor='green', alpha=0.8, rwidth=0.8) # bins参数表示将数据分成几组
ax0.set_title('pdf')
# cdf累计概率函数cumulative累计。比如需要统计小于5的数的概率
# bins参数表示将数据分成几组
# normed 是否对y轴数据进行标准化:True表是在本区间的点在所有的点中所占的概率如果 normed 为False 则是显示点的数量
ax1.hist(x, bins=20, density=False, histtype='step',
facecolor='blue', alpha=0.8, cumulative=True, rwidth=0.8)
ax1.set_title("cdf")
fig.subplots_adjust(hspace=0.4) # 调整子图间的垂直间距
plt.show()
# plt.draw()
# 可用 help(function) 查看函数帮助help(ax.plot_surface)
# ===============================================================