深度学习基础
01
目标
了解深度学习的基本概念。
02
学习内容
神经网络基础
Keras 基础
实践:使用 Keras 构建一个简单的神经网络模型
03
代码示例
1. 导入必要的库
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_iris
2. 加载示例数据集
# 加载示例数据集(鸢尾花数据集)
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['target'] = iris.target
print(f"示例数据集: \n{df.head()}")
3. 数据预处理
分割数据集
# 分割数据集为训练集和测试集
X = df.drop('target', axis=1)
y = df['target']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print(f"训练集特征: \n{X_train.head()}")
print(f"测试集特征: \n{X_test.head()}")
print(f"训练集标签: \n{y_train.head()}")
print(f"测试集标签: \n{y_test.head()}")
标准化特征
# 标准化特征
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
4. 构建神经网络模型
定义模型
# 定义一个简单的神经网络模型
model = Sequential()
model.add(Dense(10, input_dim=4, activation='relu')) # 输入层和第一个隐藏层
model.add(Dense(10, activation='relu')) # 第二个隐藏层
model.add(Dense(3, activation='softmax')) # 输出层
# 打印模型结构
model.summary()
编译模型
# 编译模型
model.compile(optimizer=Adam(learning_rate=0.01), loss='sparse_categorical_crossentropy', metrics=['accuracy'])
5. 训练模型
# 训练模型
history = model.fit(X_train_scaled, y_train, epochs=50, batch_size=10, validation_split=0.2)
6. 评估模型
在测试集上评估模型
# 在测试集上评估模型
loss, accuracy = model.evaluate(X_test_scaled, y_test)
print(f"测试集上的损失: {loss:.4f}")
print(f"测试集上的准确率: {accuracy:.4f}")
绘制训练过程中的损失和准确率
# 绘制训练过程中的损失和准确率
plt.figure(figsize=(12, 4))
# 绘制训练和验证损失
plt.subplot(1, 2, 1)
plt.plot(history.history['loss'], label='训练损失')
plt.plot(history.history['val_loss'], label='验证损失')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.title('训练和验证损失')
# 绘制训练和验证准确率
plt.subplot(1, 2, 2)
plt.plot(history.history['accuracy'], label='训练准确率')
plt.plot(history.history['val_accuracy'], label='验证准确率')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.title('训练和验证准确率')
plt.show()
7. 预测
使用模型进行预测
# 使用模型进行预测
y_pred = model.predict(X_test_scaled)
y_pred_classes = np.argmax(y_pred, axis=1)
# 打印前几个预测结果
print(f"前几个预测结果: \n{y_pred_classes[:10]}")
print(f"前几个真实标签: \n{y_test[:10].values}")
04
实践
# 导入必要的库
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
# 加载示例数据集(鸢尾花数据集)
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['target'] = iris.target
print(f"示例数据集: \n{df.head()}")
# 分割数据集为训练集和测试集
X = df.drop('target', axis=1)
y = df['target']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print(f"训练集特征: \n{X_train.head()}")
print(f"测试集特征: \n{X_test.head()}")
print(f"训练集标签: \n{y_train.head()}")
print(f"测试集标签: \n{y_test.head()}")
# 标准化特征
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# 定义一个简单的神经网络模型
model = Sequential()
model.add(Dense(10, input_dim=4, activation='relu')) # 输入层和第一个隐藏层
model.add(Dense(10, activation='relu')) # 第二个隐藏层
model.add(Dense(3, activation='softmax')) # 输出层
# 打印模型结构
model.summary()
# 编译模型
model.compile(optimizer=Adam(learning_rate=0.01), loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# 训练模型
history = model.fit(X_train_scaled, y_train, epochs=50, batch_size=10, validation_split=0.2)
# 在测试集上评估模型
loss, accuracy = model.evaluate(X_test_scaled, y_test)
print(f"测试集上的损失: {loss:.4f}")
print(f"测试集上的准确率: {accuracy:.4f}")
# 绘制训练过程中的损失和准确率
plt.figure(figsize=(12, 4))
# 绘制训练和验证损失
plt.subplot(1, 2, 1)
plt.plot(history.history['loss'], label='训练损失')
plt.plot(history.history['val_loss'], label='验证损失')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.title('训练和验证损失')
# 绘制训练和验证准确率
plt.subplot(1, 2, 2)
plt.plot(history.history['accuracy'], label='训练准确率')
plt.plot(history.history['val_accuracy'], label='验证准确率')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.title('训练和验证准确率')
plt.show()
# 使用模型进行预测
y_pred = model.predict(X_test_scaled)
y_pred_classes = np.argmax(y_pred, axis=1)
# 打印前几个预测结果
print(f"前几个预测结果: \n{y_pred_classes[:10]}")
print(f"前几个真实标签: \n{y_test[:10].values}")
05
总结
通过今天的练习,你应该已经了解了神经网络的基础知识,并学会了如何使用 Keras 构建和训练一个简单的神经网络模型
时间序列预测
学会使用深度学习进行时间序列预测。
LSTM 网络
实践:使用 LSTM 预测股票价格
目标
学会使用深度学习进行时间序列预测。
02
学习内容
LSTM 网络
实践:使用 LSTM 预测股票价格
03
代码示例
1. 导入必要的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM
from tensorflow.keras.optimizers import Adam
from tushare.pro_api import ProApi
2. 获取股票数据
# 设置 Tushare API Token
token = 'your_tushare_token' # 请替换为你的 Tushare Token
pro = ProApi(token)
# 获取股票数据
ts_code = '002594.SZ' # 比亚迪股票代码
start_date = '2018-01-01'
end_date = '2023-06-05'
df = pro.daily(ts_code=ts_code, start_date=start_date, end_date=end_date)
# 将数据按日期排序
df['trade_date'] = pd.to_datetime(df['trade_date'])
df.set_index('trade_date', inplace=True)
df.sort_index(inplace=True)
# 选择收盘价作为预测目标
df = df[['close']]
print(f"股票数据: \n{df.head()}")
3. 数据预处理
标准化数据
# 标准化数据
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(df)
# 将标准化后的数据转换为 DataFrame
df_scaled = pd.DataFrame(scaled_data, columns=['close'], index=df.index)
print(f"标准化后的数据: \n{df_scaled.head()}")
创建时间序列数据集
# 创建时间序列数据集
def create_dataset(data, time_step=60):
X, y = [], []
for i in range(len(data) - time_step - 1):
a = data[i:(i + time_step), 0]
X.append(a)
y.append(data[i + time_step, 0])
return np.array(X), np.array(y)
time_step = 60
X, y = create_dataset(scaled_data, time_step)
# 分割数据集为训练集和测试集
train_size = int(len(X) * 0.8)
test_size = len(X) - train_size
X_train, X_test = X[0:train_size], X[train_size:len(X)]
y_train, y_test = y[0:train_size], y[train_size:len(y)]
# 重塑输入数据为 [samples, time_steps, features]
X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], 1)
X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], 1)
4. 构建 LSTM 模型
定义模型
# 定义 LSTM 模型
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(time_step, 1)))
model.add(LSTM(50, return_sequences=False))
model.add(Dense(25))
model.add(Dense(1))
# 打印模型结构
model.summary()
编译模型
# 编译模型
model.compile(optimizer=Adam(learning_rate=0.001), loss='mean_squared_error')
5. 训练模型
# 训练模型
history = model.fit(X_train, y_train, epochs=50, batch_size=64, validation_data=(X_test, y_test))
6. 评估模型
在测试集上评估模型
# 在测试集上评估模型
loss = model.evaluate(X_test, y_test)
print(f"测试集上的损失: {loss:.4f}")
绘制训练过程中的损失
# 绘制训练过程中的损失
plt.figure(figsize=(12, 4))
plt.plot(history.history['loss'], label='训练损失')
plt.plot(history.history['val_loss'], label='验证损失')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.title('训练和验证损失')
plt.show()
7. 预测
使用模型进行预测
# 使用模型进行预测
y_pred = model.predict(X_test)
# 反标准化预测结果
y_pred_inv = scaler.inverse_transform(y_pred)
y_test_inv = scaler.inverse_transform(y_test.reshape(-1, 1))
# 打印前几个预测结果
print(f"前几个预测结果: \n{y_pred_inv[:10].flatten()}")
print(f"前几个真实标签: \n{y_test_inv[:10].flatten()}")
绘制预测结果
# 绘制预测结果
plt.figure(figsize=(12, 6))
plt.plot(df.index[-len(y_test):], y_test_inv, label='真实值')
plt.plot(df.index[-len(y_test):], y_pred_inv, label='预测值')
plt.xlabel('日期')
plt.ylabel('收盘价')
plt.legend()
plt.title('股票价格预测')
plt.show()
04
实践
# 导入必要的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM
from tensorflow.keras.optimizers import Adam
from tushare.pro_api import ProApi
# 设置 Tushare API Token
token = 'your_tushare_token' # 请替换为你的 Tushare Token
pro = ProApi(token)
# 获取股票数据
ts_code = '002594.SZ' # 比亚迪股票代码
start_date = '2018-01-01'
end_date = '2023-06-05'
df = pro.daily(ts_code=ts_code, start_date=start_date, end_date=end_date)
# 将数据按日期排序
df['trade_date'] = pd.to_datetime(df['trade_date'])
df.set_index('trade_date', inplace=True)
df.sort_index(inplace=True)
# 选择收盘价作为预测目标
df = df[['close']]
print(f"股票数据: \n{df.head()}")
# 标准化数据
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(df)
# 将标准化后的数据转换为 DataFrame
df_scaled = pd.DataFrame(scaled_data, columns=['close'], index=df.index)
print(f"标准化后的数据: \n{df_scaled.head()}")
# 创建时间序列数据集
def create_dataset(data, time_step=60):
X, y = [], []
for i in range(len(data) - time_step - 1):
a = data[i:(i + time_step), 0]
X.append(a)
y.append(data[i + time_step, 0])
return np.array(X), np.array(y)
time_step = 60
X, y = create_dataset(scaled_data, time_step)
# 分割数据集为训练集和测试集
train_size = int(len(X) * 0.8)
test_size = len(X) - train_size
X_train, X_test = X[0:train_size], X[train_size:len(X)]
y_train, y_test = y[0:train_size], y[train_size:len(y)]
# 重塑输入数据为 [samples, time_steps, features]
X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], 1)
X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], 1)
# 定义 LSTM 模型
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(time_step, 1)))
model.add(LSTM(50, return_sequences=False))
model.add(Dense(25))
model.add(Dense(1))
# 打印模型结构
model.summary()
# 编译模型
model.compile(optimizer=Adam(learning_rate=0.001), loss='mean_squared_error')
# 训练模型
history = model.fit(X_train, y_train, epochs=50, batch_size=64, validation_data=(X_test, y_test))
# 在测试集上评估模型
loss = model.evaluate(X_test, y_test)
print(f"测试集上的损失: {loss:.4f}")
# 绘制训练过程中的损失
plt.figure(figsize=(12, 4))
plt.plot(history.history['loss'], label='训练损失')
plt.plot(history.history['val_loss'], label='验证损失')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.title('训练和验证损失')
plt.show()
# 使用模型进行预测
y_pred = model.predict(X_test)
# 反标准化预测结果
y_pred_inv = scaler.inverse_transform(y_pred)
y_test_inv = scaler.inverse_transform(y_test.reshape(-1, 1))
# 打印前几个预测结果
print(f"前几个预测结果: \n{y_pred_inv[:10].flatten()}")
print(f"前几个真实标签: \n{y_test_inv[:10].flatten()}")
# 绘制预测结果
plt.figure(figsize=(12, 6))
plt.plot(df.index[-len(y_test):], y_test_inv, label='真实值')
plt.plot(df.index[-len(y_test):], y_pred_inv, label='预测值')
plt.xlabel('日期')
plt.ylabel('收盘价')
plt.legend()
plt.title('股票价格预测')
plt.show()
05
总结
通过今天的练习,你应该已经学会了如何使用 LSTM 网络进行时间序列预测,并能够使用 Keras 构建和训练一个简单的 LSTM 模型来预测股票价格