深度学习相关整理

一.安装配置

'''
1.Anaconda 的清华源镜像
https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/?C=M&O=D
https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/?C=M&O=D

设置环境变量,让系统能够找到python, pip。如我的安装路径是E:\app\Anaconda\Anaconda3,则要添加路径
E:\app\Anaconda\Anaconda3
E:\app\Anaconda\Anaconda3\Scripts到系统环境变量

2.验证安装,Windows开始菜单中找到并打开 Anaconda Prompt,
在控制台分别输入以下两行来查看已安装的Conda版本和Python版本:
conda --version
python --version

创建虚拟环境:conda create -n 环境名称 python=版本号
conda create -n py388 python=3.8.8

conda activate py388
python --version  # 应显示 3.8.8

Anaconda Prompt 里,输入下面代码来生成.condarc配置文件:
conda config --set show_channel_urls yes

pip uninstall numpy
pip install numpy==1.22.4

3.Anaconda 常用命令
a.创建虚拟环境:conda create -n 环境名称 python=版本号
conda create -n py388 python=3.8.8

b.创建的虚拟环境在Anaconda的安装目录的envs文件夹下,
激活虚拟环境:conda activate 环境名称
conda activate py388

c.更新所有包:conda update --all

d.安装包:conda install ackage_name

e.更新包:conda update ackage_name

f.卸载包:conda install ackage_name

g.查看当前环境下安装的包:conda list

h.退出当前环境:conda deactivate

i.查询环境:conda env list

j.环境重命名:conda rename -n 旧名字 新名字

k.删除环境:conda env remove -n 环境名称

l.查看 conda 的详细信息,包括环境位置、活动环境等:conda info

m.导出环境,生成的yaml文件默认保存在当前路径
conda env export > your_env.yaml

n.根据导出的环境文件创建环境
conda env create -f your_env.yaml

o.上面的命令只会导出使用conda安装的,而pip安装的还需要下面的命令
pip freeze > requirements.txt

p.导入pip安装的包
pip install -r requirements.txt



打开cmd,输入conda info,有回显则安装成功

'''
import tensorflow as tf
print(tf.__version__)
# 输入数据:batch=2, seq_len=10, features=2
inputs = tf.ones((2, 10, 2))

# 卷积核:filter_height=5, in_channels=2, out_channels=2
w = tf.constant(1.0, shape=(5, 2, 2), dtype=tf.float32)

# 1D 卷积
output = tf.nn.conv1d(inputs, w, stride=1, padding='SAME')

# 直接打印,无需 Session
print("inputs =", inputs.numpy())
print("w =", w.numpy())
print("output =", output.numpy())


二.验证代码

# 导入TensorFlow库
import tensorflow as tf

# 打印TensorFlow版本
print("TensorFlow版本:", tf.__version__)

# 执行一个简单操作验证功能
# 创建常量张量并输出值
hello = tf.constant('Hello, TensorFlow!')
print(hello.numpy())

# 可选:测试一个数学操作,例如矩阵乘法(行内数学示例:$A \times B$)
a = tf.constant([[1, 2], [3, 4]])
b = tf.constant([[5, 6], [7, 8]])
c = tf.matmul(a, b)
print("矩阵乘法结果:\n", c.numpy())
import tensorflow as tf
print(tf.__version__)
# 输入数据:batch=2, seq_len=10, features=2
inputs = tf.ones((2, 10, 2))

# 卷积核:filter_height=5, in_channels=2, out_channels=2
w = tf.constant(1.0, shape=(5, 2, 2), dtype=tf.float32)

# 1D 卷积
output = tf.nn.conv1d(inputs, w, stride=1, padding='SAME')

# 直接打印,无需 Session
print("inputs =", inputs.numpy())
print("w =", w.numpy())
print("output =", output.numpy())

三.运行调试

'''
pip install tensorflow -i https://mirrors.tools.huawei.com/pypi/simple/  #华为源
pip install tensorflow -i https://pypi.tuna.tsinghua.edu.cn/simple  #清华源
'''
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

print("TensorFlow版本:", tf.__version__)
train_X = np.linspace(-1, 1, 100)
train_Y = 2 * train_X + np.random.randn(*train_X.shape) * 0.3 #y=2x 加入了噪音
plt.plot(train_X, train_Y, 'ro',label='Original data') #显示模拟数据点
plt.legend() #显示图例
plt.show()

3.1 版本1

# '''
# pip install tensorflow -i https://mirrors.tools.huawei.com/pypi/simple/  #华为源
# pip install tensorflow -i https://pypi.tuna.tsinghua.edu.cn/simple  #清华源
# '''
# #TF 1.x
# import tensorflow as tf
# import numpy as np
# import matplotlib.pyplot as plt

# print("TensorFlow版本:", tf.__version__)
# #1.准备数据
# train_X = np.linspace(-1, 1, 100)
# train_Y = 2 * train_X + np.random.randn(*train_X.shape) * 0.3 #y=2x 加入了噪音
# plt.plot(train_X, train_Y, 'ro',label='Original data') #显示模拟数据点
# plt.legend() #显示图例
# plt.show()

# #2.搭建模型
# #2.1.创建模型
# #占位符
# X = tf.placeholder("float")
# Y = tf.placeholder("float")
# #模型参数
# W = tf.Variable(tf.random_normal([1]),name="weight")
# b = tf.Variable(tf.zeros([1]),name="bias")
# #前向结构
# z = tf.multiply(X, W) + b

# #2.2.反向搭建模型
# #反向优化
# cost = tf.reduce_mean(tf.square(Y-z))
# learning_rate = 0.01 #学习率
# optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) #梯度下降

# #3.迭代训练模型
# #3.1.训练模型
# init = tf.global_variables_initializer() #初始化所有变量
# #定义函数
# training_epochs = 20 #迭代次数取20
# display_step = 2
# #启动session
# with tf.Session() as sess:
#     sess.run(init) #初始化
#     plotdata={"batchsize":[],'loss':[]} #存放批次值和损失值
#     #向模型输入数据
#     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 % display_step == 0:#若余数为0
#                 loss = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
#                 print("Epoch:",epoch,"Cost:",loss,"W:",W,"Bias:",b)
#                 if not (loss == "NA"):
#                     plotdata["batchsize"].append(epoch)
#                     plotdata["loss"].append(loss)
#     print("Finished Training!")#训练完成
#     print("cost=",sess.run(cost, feed_dict={X: train_X, Y: train_Y}),"W=",sess.run(W),"Bias=",sess.run(b))
# #3.2.训练模型可视化
# #图形显示
#     plt.plot(train_X, train_Y, 'ro',label='Original data')#圆形 ,标签:原始数据
#     plt.plot(train_X, sess.run(W) * train_X + sess.run(b),label='Fittedline')
#     plt.legend()
#     plt.show()

#     plotdata["avgloss"] = moving_average(plotdata["loss"])
#     plt.figure(1)
#     plt.subplot(211)
#     plt.plot(plotdata["batchsize"],plotdata["avgloss"],"b--")
#     plt.xlabel("Minibatch number")
#     plt.ylabel("Loss")
#     plt.title("Minibatch Loss vs . Training Loss")
#     plt.show()

# #4.使用模型
#     print("x = 0.2,z = ",sess.run(z,feed_dict={X: 0.2}))
# '''
# 5 个 TF 2.x 习惯:
# 不要用 placeholder → 直接传数据
# 不要用 Session → 直接运行函数
# 用 @tf.function 提升性能
# 用 tf.GradientTape() 实现自动微分
# 用 tf.keras 构建模型(推荐)
# '''
# 升级到TensorFlow 2.x API:

# 使用tf.keras API替代原始的placeholder和Variable
# 使用model.compile()配置优化器和损失函数
# 使用train_on_batch()方法实现逐样本训练
# 保留原始功能:

# 保持了原始代码结构和训练流程
# 每2个epoch输出一次训练信息
# 保留了损失计算和权重更新的可视化
# 添加了移动平均损失曲线
# 增强可视化:

# 使用子图同时显示模型拟合和训练损失
# 添加了更清晰的标签和标题
# 优化了图形布局
# 改进训练过程:

# 使用更简洁的Keras API
# 自动处理张量形状转换
# 简化了模型评估过程
# 保持结果一致性:

# 保留原始线性回归任务(y=2x+噪声)
# 使用相同的随机种子保证结果可复现
# 输出格式与原始代码相似

3.2 版本2

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

print("TensorFlow版本:", tf.__version__)

# 1.准备数据
train_X = np.linspace(-1, 1, 100)
train_Y = 2 * train_X + np.random.randn(*train_X.shape) * 0.3  # y=2x 加入噪音

plt.plot(train_X, train_Y, 'ro', label='Original data')
plt.legend()
plt.show()

# 2.搭建模型
# 2.1.创建模型(使用Keras Sequential API)
model = tf.keras.Sequential([
    tf.keras.layers.Dense(units=1, input_shape=[1])
])

# 2.2.编译模型(配置优化器和损失函数)
model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=0.01), 
              loss='mean_squared_error')

# 2.3.训练模型
print("开始训练...")
history = model.fit(
    x=train_X,
    y=train_Y,
    epochs=20,
    verbose=0  # 不输出训练过程
)

# 按原逻辑每2个epoch输出一次损失
print("\n训练过程监控:")
for epoch in range(20):
    if epoch % 2 == 0:
        loss = model.evaluate(train_X, train_Y, verbose=0)
        weights, bias = model.layers[0].get_weights()
        print(f"Epoch {epoch}: loss={loss:.4f}, W={weights[0][0]:.4f}, bias={bias[0]:.4f}")

# 2.4.输出最终结果
weights, bias = model.layers[0].get_weights()
final_loss = model.evaluate(train_X, train_Y, verbose=0)
print("\n训练完成!")
print(f"Final cost={final_loss:.4f}, W={weights[0][0]:.4f}, bias={bias[0]:.4f}")

# 可视化训练结果
plt.plot(train_X, train_Y, 'ro', label='Original data')
plt.plot(train_X, model.predict(train_X), 'b-', label='Fitted line')
plt.legend()
plt.show()

3.3 完善版本2

#TF 2.x 

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

print("TensorFlow版本:", tf.__version__)

# 1.准备数据
train_X = np.linspace(-1, 1, 100)
train_Y = 2 * train_X + np.random.randn(*train_X.shape) * 0.3  # y=2x 加入噪音

plt.plot(train_X, train_Y, 'ro', label='Original data')
plt.legend()
plt.show()

# 2.搭建模型
# 2.1 创建模型
# 使用Keras API代替placeholder和Variable
model = tf.keras.Sequential([
    tf.keras.layers.Dense(units=1, input_shape=[1])
])

# 2.2 反向优化
# 使用Keras的优化器和损失函数
model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=0.01), 
              loss='mean_squared_error')

# 3.迭代训练模型
# 3.1 训练模型
training_epochs = 20
display_step = 2

# 存储训练信息
plotdata = {"batchsize": [], "loss": []}

# 训练循环
for epoch in range(training_epochs):
    # 逐样本训练
    for x, y in zip(train_X, train_Y):
        # 使用单个样本进行训练
        model.train_on_batch(x.reshape(1, 1), y.reshape(1, 1))
    
    # 计算整个训练集上的损失
    loss = model.evaluate(train_X.reshape(-1, 1), train_Y, verbose=0)
    
    # 每display_step个epoch记录一次
    if epoch % display_step == 0:
        # 获取当前权重和偏置
        weights, bias = model.layers[0].get_weights()
        plotdata["batchsize"].append(epoch)
        plotdata["loss"].append(loss)
        print(f"Epoch {epoch}: loss={loss:.4f}, W={weights[0][0]:.4f}, bias={bias[0]:.4f}")

# 训练完成
print("\nFinished Training!")
weights, bias = model.layers[0].get_weights()
final_loss = model.evaluate(train_X.reshape(-1, 1), train_Y, verbose=0)
print(f"Final cost={final_loss:.4f}, W={weights[0][0]:.4f}, bias={bias[0]:.4f}")

# 3.2 训练模型可视化
# 图形显示
plt.figure(figsize=(12, 8))

# 原始数据和拟合直线
plt.subplot(2, 1, 1)
plt.plot(train_X, train_Y, 'ro', label='Original data')
plt.plot(train_X, model.predict(train_X.reshape(-1, 1)), 'b-', label='Fitted line')
plt.legend()
plt.title('Model Fit')

# 损失曲线
plt.subplot(2, 1, 2)
# 计算移动平均
window_size = 5
moving_avg = np.convolve(plotdata["loss"], np.ones(window_size)/window_size, mode='valid')
plt.plot(plotdata["batchsize"][window_size-1:], moving_avg, "b--", label='Moving Average')
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.title('Training Loss')
plt.legend()

plt.tight_layout()
plt.show()

# 4.使用模型
# 预测新值
x_test = 0.2
z_pred = model.predict(np.array([[x_test]]))[0][0]
print(f"x = 0.2, z = {z_pred:.4f}")

整理不易,诚望各位看官点赞 收藏 评论 予以支持,这将成为我持续更新的动力源泉。若您在阅览时存有异议或建议,敬请留言指正批评,让我们携手共同学习,共同进取,吾辈自当相互勉励!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值