活动介绍

修改代码,使得输出结果是可重复的:# 定义模型参数 input_dim = X_train.shape[1] epochs = 100 batch_size = 32 learning_rate = 0.01 dropout_rate = 0.7 # 定义模型结构 def create_model(): model = Sequential() model.add(Dense(64, input_dim=input_dim, activation='relu')) model.add(Dropout(dropout_rate)) model.add(Dense(32, activation='relu')) model.add(Dropout(dropout_rate)) model.add(Dense(1, activation='sigmoid')) optimizer = Adam(learning_rate=learning_rate) model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy']) return model # 5折交叉验证 kf = KFold(n_splits=5, shuffle=True, random_state=42) cv_scores = [] for train_index, test_index in kf.split(X_train): # 划分训练集和验证集 X_train_fold, X_val_fold = X_train.iloc[train_index], X_train.iloc[test_index] y_train_fold, y_val_fold = y_train_forced_turnover_nolimited.iloc[train_index], y_train_forced_turnover_nolimited.iloc[test_index] # 创建模型 model = create_model() # 定义早停策略 #early_stopping = EarlyStopping(monitor='val_loss', patience=10, verbose=1) # 训练模型 model.fit(X_train_fold, y_train_fold, validation_data=(X_val_fold, y_val_fold), epochs=epochs, batch_size=batch_size,verbose=1) # 预测验证集 y_pred = model.predict(X_val_fold) # 计算AUC指标 auc = roc_auc_score(y_val_fold, y_pred) cv_scores.append(auc) # 输出交叉验证结果 print('CV AUC:', np.mean(cv_scores)) # 在全量数据上重新训练模型 model = create_model() model.fit(X_train, y_train_forced_turnover_nolimited, epochs=epochs, batch_size=batch_size, verbose=1) #测试集结果 test_pred = model.predict(X_test) test_auc = roc_auc_score(y_test_forced_turnover_nolimited, test_pred) test_f1_score = f1_score(y_test_forced_turnover_nolimited, np.round(test_pred)) test_accuracy = accuracy_score(y_test_forced_turnover_nolimited, np.round(test_pred)) print('Test AUC:', test_auc) print('Test F1 Score:', test_f1_score) print('Test Accuracy:', test_accuracy) #训练集结果 train_pred = model.predict(X_train) train_auc = roc_auc_score(y_train_forced_turnover_nolimited, train_pred) train_f1_score = f1_score(y_train_forced_turnover_nolimited, np.round(train_pred)) train_accuracy = accuracy_score(y_train_forced_turnover_nolimited, np.round(train_pred)) print('Train AUC:', train_auc) print('Train F1 Score:', train_f1_score) print('Train Accuracy:', train_accuracy)

时间: 2023-12-24 13:13:14 浏览: 302
为了使输出结果可重复,可以在代码开头设置随机种子。修改后的代码如下: ```python import numpy as np import pandas as pd from sklearn.metrics import roc_auc_score, f1_score, accuracy_score from sklearn.model_selection import KFold from keras.models import Sequential from keras.layers import Dense, Dropout from keras.optimizers import Adam from keras.callbacks import EarlyStopping # 设置随机种子 np.random.seed(42) # 定义模型参数 input_dim = X_train.shape[1] epochs = 100 batch_size = 32 learning_rate = 0.01 dropout_rate = 0.7 # 定义模型结构 def create_model(): model = Sequential() model.add(Dense(64, input_dim=input_dim, activation='relu')) model.add(Dropout(dropout_rate)) model.add(Dense(32, activation='relu')) model.add(Dropout(dropout_rate)) model.add(Dense(1, activation='sigmoid')) optimizer = Adam(learning_rate=learning_rate) model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy']) return model # 5折交叉验证 kf = KFold(n_splits=5, shuffle=True, random_state=42) cv_scores = [] for train_index, test_index in kf.split(X_train): # 划分训练集和验证集 X_train_fold, X_val_fold = X_train.iloc[train_index], X_train.iloc[test_index] y_train_fold, y_val_fold = y_train_forced_turnover_nolimited.iloc[train_index], y_train_forced_turnover_nolimited.iloc[test_index] # 创建模型 model = create_model() # 定义早停策略 #early_stopping = EarlyStopping(monitor='val_loss', patience=10, verbose=1) # 训练模型 model.fit(X_train_fold, y_train_fold, validation_data=(X_val_fold, y_val_fold), epochs=epochs, batch_size=batch_size,verbose=1) # 预测验证集 y_pred = model.predict(X_val_fold) # 计算AUC指标 auc = roc_auc_score(y_val_fold, y_pred) cv_scores.append(auc) # 输出交叉验证结果 print('CV AUC:', np.mean(cv_scores)) # 在全量数据上重新训练模型 model = create_model() model.fit(X_train, y_train_forced_turnover_nolimited, epochs=epochs, batch_size=batch_size, verbose=1) #测试集结果 test_pred = model.predict(X_test) test_auc = roc_auc_score(y_test_forced_turnover_nolimited, test_pred) test_f1_score = f1_score(y_test_forced_turnover_nolimited, np.round(test_pred)) test_accuracy = accuracy_score(y_test_forced_turnover_nolimited, np.round(test_pred)) print('Test AUC:', test_auc) print('Test F1 Score:', test_f1_score) print('Test Accuracy:', test_accuracy) #训练集结果 train_pred = model.predict(X_train) train_auc = roc_auc_score(y_train_forced_turnover_nolimited, train_pred) train_f1_score = f1_score(y_train_forced_turnover_nolimited, np.round(train_pred)) train_accuracy = accuracy_score(y_train_forced_turnover_nolimited, np.round(train_pred)) print('Train AUC:', train_auc) print('Train F1 Score:', train_f1_score) print('Train Accuracy:', train_accuracy) ```
阅读全文

相关推荐

在以下这段代码后面继续添加输出测试集、训练集AUC、f1_score、准确率的代码:# 定义模型参数 input_dim = X_train.shape[1] epochs = 100 batch_size = 32 learning_rate = 0.1 dropout_rate = 0.5 # 定义模型结构 def create_model(): model = Sequential() model.add(Dense(128, input_dim=input_dim, activation='relu')) model.add(Dropout(dropout_rate)) model.add(Dense(32, activation='relu')) model.add(Dropout(dropout_rate)) model.add(Dense(1, activation='sigmoid')) optimizer = Adam(learning_rate=learning_rate) model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy']) return model # 5折交叉验证 kf = KFold(n_splits=5, shuffle=True, random_state=42) cv_scores = [] for train_index, test_index in kf.split(X_train): # 划分训练集和验证集 X_train_fold, X_val_fold = X_train.iloc[train_index], X_train.iloc[test_index] y_train_fold, y_val_fold = y_train_forced_turnover_nolimited.iloc[train_index], y_train_forced_turnover_nolimited.iloc[test_index] # 创建模型 model = create_model() # 定义早停策略 early_stopping = EarlyStopping(monitor='val_loss', patience=10, verbose=1) # 训练模型 model.fit(X_train_fold, y_train_fold, validation_data=(X_val_fold, y_val_fold), epochs=epochs, batch_size=batch_size, callbacks=[early_stopping], verbose=1) # 预测验证集 y_pred = model.predict(X_val_fold) # 计算AUC指标 auc = roc_auc_score(y_val_fold, y_pred) cv_scores.append(auc) # 输出交叉验证结果 print('CV AUC:', np.mean(cv_scores)) # 在全量数据上重新训练模型 model = create_model() model.fit(X_train, y_train_forced_turnover_nolimited, epochs=epochs, batch_size=batch_size, verbose=1)

修改这段代码,使得输出训练集结果是可重复的:# 定义模型参数 input_dim = X_train.shape[1] epochs = 100 batch_size = 32 learning_rate = 0.001 dropout_rate = 0.1 # 定义模型结构 def create_model(): model = Sequential() model.add(Dense(64, input_dim=input_dim, activation='relu')) model.add(Dropout(dropout_rate)) model.add(Dense(32, activation='relu')) model.add(Dropout(dropout_rate)) model.add(Dense(1, activation='sigmoid')) optimizer = Adam(learning_rate=learning_rate) model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy']) return model # 5折交叉验证 kf = KFold(n_splits=5, shuffle=True, random_state=42) cv_scores = [] for train_index, test_index in kf.split(X_train): # 划分训练集和验证集 X_train_fold, X_val_fold = X_train.iloc[train_index], X_train.iloc[test_index] y_train_fold, y_val_fold = y_train_forced_turnover_nolimited.iloc[train_index], y_train_forced_turnover_nolimited.iloc[test_index] # 创建模型 model = create_model() # 定义早停策略 #early_stopping = EarlyStopping(monitor='val_loss', patience=10, verbose=1) # 训练模型 model.fit(X_train_fold, y_train_fold, validation_data=(X_val_fold, y_val_fold), epochs=epochs, batch_size=batch_size,verbose=1) # 预测验证集 y_pred = model.predict(X_val_fold) # 计算AUC指标 auc = roc_auc_score(y_val_fold, y_pred) cv_scores.append(auc) # 输出交叉验证结果 print('CV AUC:', np.mean(cv_scores)) # 在全量数据上重新训练模型 model = create_model() model.fit(X_train, y_train_forced_turnover_nolimited, epochs=epochs, batch_size=batch_size, verbose=1) #测试集结果 test_pred = model.predict(X_test) test_auc = roc_auc_score(y_test_forced_turnover_nolimited, test_pred) test_f1_score = f1_score(y_test_forced_turnover_nolimited, np.round(test_pred)) test_accuracy = accuracy_score(y_test_forced_turnover_nolimited, np.round(test_pred)) print('Test AUC:', test_auc) print('Test F1 Score:', test_f1_score) print('Test Accuracy:', test_accuracy) #训练集结果 train_pred = model.predict(X_train) train_auc = roc_auc_score(y_train_forced_turnover_nolimited, train_pred) train_f1_score = f1_score(y_train_forced_turnover_nolimited, np.round(train_pred)) train_accuracy = accuracy_score(y_train_forced_turnover_nolimited, np.round(train_pred)) print('Train AUC:', train_auc) print('Train F1 Score:', train_f1_score) print('Train Accuracy:', train_accuracy)

将这段代码改为输出的AUC、f1_score、Accuracy是可重复的:# 定义模型参数 input_dim = X_train.shape[1] epochs = 100 batch_size = 32 learning_rate = 0.001 dropout_rate = 0.1 # 定义模型结构 def create_model(): model = Sequential() model.add(Dense(64, input_dim=input_dim, activation='relu')) model.add(Dropout(dropout_rate)) model.add(Dense(32, activation='relu')) model.add(Dropout(dropout_rate)) model.add(Dense(1, activation='sigmoid')) optimizer = Adam(learning_rate=learning_rate) model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy']) return model # 5折交叉验证 kf = KFold(n_splits=5, shuffle=True, random_state=42) cv_scores = [] for train_index, test_index in kf.split(X_train): # 划分训练集和验证集 X_train_fold, X_val_fold = X_train.iloc[train_index], X_train.iloc[test_index] y_train_fold, y_val_fold = y_train_forced_turnover_nolimited.iloc[train_index], y_train_forced_turnover_nolimited.iloc[test_index] # 创建模型 model = create_model() # 定义早停策略 #early_stopping = EarlyStopping(monitor='val_loss', patience=10, verbose=1) # 训练模型 model.fit(X_train_fold, y_train_fold, validation_data=(X_val_fold, y_val_fold), epochs=epochs, batch_size=batch_size,verbose=1) # 预测验证集 y_pred = model.predict(X_val_fold) # 计算AUC指标 auc = roc_auc_score(y_val_fold, y_pred) cv_scores.append(auc) # 输出交叉验证结果 print('CV AUC:', np.mean(cv_scores)) # 在全量数据上重新训练模型 model = create_model() model.fit(X_train, y_train_forced_turnover_nolimited, epochs=epochs, batch_size=batch_size, verbose=1) #测试集结果 test_pred = model.predict(X_test) test_auc = roc_auc_score(y_test_forced_turnover_nolimited, test_pred) test_f1_score = f1_score(y_test_forced_turnover_nolimited, np.round(test_pred)) test_accuracy = accuracy_score(y_test_forced_turnover_nolimited, np.round(test_pred)) print('Test AUC:', test_auc) print('Test F1 Score:', test_f1_score) print('Test Accuracy:', test_accuracy) #训练集结果 train_pred = model.predict(X_train) train_auc = roc_auc_score(y_train_forced_turnover_nolimited, train_pred) train_f1_score = f1_score(y_train_forced_turnover_nolimited, np.round(train_pred)) train_accuracy = accuracy_score(y_train_forced_turnover_nolimited, np.round(train_pred)) print('Train AUC:', train_auc) print('Train F1 Score:', train_f1_score) print('Train Accuracy:', train_accuracy)

帮我纠正这段代码# 定义模型参数 input_dim = X_train.shape[1] epochs = 100 batch_size = 32 lr = 0.001 dropout_rate = 0.5 # 定义模型结构 def create_model(): model = Sequential() model.add(Dense(64, input_dim=input_dim, activation='relu')) model.add(Dropout(dropout_rate)) model.add(Dense(32, activation='relu')) model.add(Dropout(dropout_rate)) model.add(Dense(1, activation='sigmoid')) optimizer = Adam(lr=lr) model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy']) return model # 5折交叉验证 kf = KFold(n_splits=5, shuffle=True, random_state=42) cv_scores = [] for train_index, test_index in kf.split(X_train): # 划分训练集和验证集 X_train_fold, X_val_fold = X_train.iloc[train_index], X_train.iloc[test_index] y_train_fold, y_val_fold = y_train_forced_turnover_nolimited.iloc[train_index], y_train_forced_turnover_nolimited.iloc[test_index] # 创建模型 model = create_model() # 定义早停策略 early_stopping = EarlyStopping(monitor='val_loss', patience=10, verbose=1) # 训练模型 model.fit(X_train_fold, y_train_fold, validation_data=(X_val_fold, y_val_fold), epochs=epochs, batch_size=batch_size, callbacks=[early_stopping], verbose=1) # 预测验证集 y_pred = model.predict(X_val_fold) # 计算AUC指标 auc = roc_auc_score(y_val_fold, y_pred) cv_scores.append(auc) # 输出交叉验证结果 print('CV AUC:', np.mean(cv_scores)) # 在全量数据上重新训练模型 model = create_model() model.fit(X_train, y_train_forced_turnover_nolimited, epochs=epochs, batch_size=batch_size, verbose=1)

import tensorflow as tf from keras import datasets, layers, models import matplotlib.pyplot as plt # 导入mnist数据,依次分别为训练集图片、训练集标签、测试集图片、测试集标签 (train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data() # 将像素的值标准化至0到1的区间内。(对于灰度图片来说,每个像素最大值是255,每个像素最小值是0,也就是直接除以255就可以完成归一化。) train_images, test_images = train_images / 255.0, test_images / 255.0 # 查看数据维数信息 print(train_images.shape,test_images.shape,train_labels.shape,test_labels.shape) #调整数据到我们需要的格式 train_images = train_images.reshape((60000, 28, 28, 1)) test_images = test_images.reshape((10000, 28, 28, 1)) print(train_images.shape,test_images.shape,train_labels.shape,test_labels.shape) train_images = train_images.astype("float32") / 255.0 def image_to_patches(images, patch_size=4): batch_size = tf.shape(images)[0] patches = tf.image.extract_patches( images=images[:, :, :, tf.newaxis], sizes=[1, patch_size, patch_size, 1], strides=[1, patch_size, patch_size, 1], rates=[1, 1, 1, 1], padding="VALID" ) return tf.reshape(patches, [batch_size, -1, patch_size*patch_size*1]) class TransformerBlock(tf.keras.layers.Layer): def __init__(self, embed_dim, num_heads): super().__init__() self.att = tf.keras.layers.MultiHeadAttention(num_heads=num_heads, key_dim=embed_dim) self.ffn = tf.keras.Sequential([ tf.keras.layers.Dense(embed_dim*4, activation="relu"), tf.keras.layers.Dense(embed_dim) ]) self.layernorm1 = tf.keras.layers.LayerNormalization() self.layernorm2 = tf.keras.layers.LayerNormalization() def call(self, inputs): attn_output = self.att(inputs, inputs) out1 = self.layernorm1(inputs + attn_output) ffn_output = self.ffn(out1) return self.layernorm2(out1 + ffn_output) class PositionEmbedding(tf.keras.layers.Layer): def __init__(self, max_len, embed_dim): super().__init__() self.pos_emb = tf.keras.layers.Embedding(input_dim=max_len, output_dim=embed_dim) def call(self, x): positions = tf.range(start=0, limit=tf.shape(x)[1], delta=1) return x + self.pos_emb(positions) def build_transformer_model(): inputs = tf.keras.Input(shape=(49, 16)) # 4x4 patches x = tf.keras.layers.Dense(64)(inputs) # 嵌入维度64 # 添加位置编码 x = PositionEmbedding(max_len=49, embed_dim=64)(x) # 堆叠Transformer模块 x = TransformerBlock(embed_dim=64, num_heads=4)(x) x = TransformerBlock(embed_dim=64, num_heads=4)(x) # 分类头 x = tf.keras.layers.GlobalAveragePooling1D()(x) outputs = tf.keras.layers.Dense(10, activation="softmax")(x) return tf.keras.Model(inputs=inputs, outputs=outputs) model = build_transformer_model() model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"]) # 数据预处理 train_images_pt = image_to_patches(train_images[..., tf.newaxis]) test_images_pt = image_to_patches(test_images[..., tf.newaxis]) history = model.fit( train_images_pt, train_labels, validation_data=(test_images_pt, test_labels), epochs=10, batch_size=128 )代码检查并添加注释

X_train = np.load('X_train.npy') y_train = np.load('y_train.npy') X_val = np.load('X_val.npy') y_val = np.load('y_val.npy') X_test = np.load('X_test.npy') y_test = np.load('y_test.npy') class DDCTrainer: def __init__(self, input_dim): self.input_dim = input_dim self.domain_loss_weight = 0.1 # 领域损失权重 # 构建特征提取网络 self.feature_extractor = self.build_feature_extractor() # 完整模型构建(包括分类头) self.classifier_model = self.build_classifier(self.feature_extractor) @staticmethod def build_feature_extractor(): model = Sequential([ Dense(64, activation='relu', input_shape=(None,)), Dropout(0.5), Dense(32, activation='relu'), ]) return model @staticmethod def build_domain_discriminator(feature_extractor_output_dim): model = Sequential([ Dense(16, activation='relu', input_shape=(feature_extractor_output_dim,)), Dense(1, activation='sigmoid'), # 判断是否属于源领域或目标领域 ]) return model def build_classifier(self, feature_extractor): classifier_head = Sequential([ feature_extractor, Dense(2, activation='softmax') # 分类任务为两类 ]) classifier_head.compile(optimizer=Adam(), loss='sparse_categorical_crossentropy', metrics=['accuracy']) return classifier_head def compute_domain_confusion(self, features_source, features_target): """ 计算领域间混淆度 """ mean_features_source = np.mean(features_source, axis=0) mean_features_target = np.mean(features_target, axis=0) confusion_distance = euclidean(mean_features_source, mean_features_target) return confusion_distance def simulate_ddc_training(ddc_trainer, source_data, target_data, epochs=10, batch_size=32): for epoch in range(epochs): # 提取特征 features_source = ddc_trainer.feature_extractor.predict(source_data[0]) features_target = ddc_trainer.feature_extractor.predict(target_data[0]) # 更新特征提取器以最小化领域差异 domain_confusion = ddc_trainer.compute_domain_confusion(features_source, features_target) print(f"Epoch {epoch + 1}/{epochs} - Domain Confusion Distance: {domain_confusion:.4f}") # 对齐分布的同时训练分类器 history = ddc_trainer.classifier_model.fit( *source_data, validation_data=target_data, epochs=1, batch_size=batch_size, verbose=0 ) val_accuracy = history.history['val_accuracy'][0] print(f"\tValidation Accuracy on Target Data: {val_accuracy * 100:.2f}%\n") if __name__ == "__main__": # 初始化 DDC Trainer 并设置输入维度 input_dim = X_train.shape[1] trainer = DDCTrainer(input_dim=input_dim) # 模拟源域和目标域划分(假设一部分是源域,另一部分为目标域) source_data = (X_train[:len(X_train) // 2], y_train[:len(y_train) // 2]) # 源域 target_data = (X_val, y_val) # 目标域 # 开始模拟 DDC 过程 simulate_ddc_training(trainer, source_data, target_data, epochs=10, batch_size=32)TypeError: build_feature_extractor() missing 1 required positional argument: 'input_dim'

import scipy.io import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader, TensorDataset from sklearn.model_selection import train_test_split # 1. 加载MAT文件 def load_matlab_data(file_path): data = scipy.io.loadmat(file_path) csi = np.squeeze(data['csi']) # [num_samples, num_subcarriers, num_users] allocations = np.squeeze(data['allocations']) # [num_samples, num_subcarriers] symbols = np.squeeze(data['symbols_with_channel']) snr = np.squeeze(data['snr']) return csi, allocations, symbols, snr # 2. 数据预处理 def preprocess_data(csi, allocations, snr): X = np.concatenate([ np.abs(csi).reshape(csi.shape[0], -1), snr.reshape(-1, 1) ], axis=1) y = allocations return X, y # 3. 定义LSTM模型 class LSTMModel(nn.Module): def __init__(self, input_dim, hidden_dim, output_dim, num_layers=2): super().__init__() self.lstm = nn.LSTM(input_dim, hidden_dim, num_layers, batch_first=True) self.fc = nn.Linear(hidden_dim, output_dim) def forward(self, x): out, _ = self.lstm(x) # [batch_size, seq_length=1, hidden_dim] out = self.fc(out) # [batch_size, seq_length=1, output_dim] return out.squeeze(1) # [batch_size, output_dim] # 4. 训练与验证 def train_model(model, X_train, y_train, num_epochs=50, batch_size=32, lr=1e-3): dataset = TensorDataset( torch.tensor(X_train, dtype=torch.float32), torch.tensor(y_train, dtype=torch.long) ) dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True) criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=lr) for epoch in range(num_epochs): model.train() total_loss = 0 for batch_X, batch_y in dataloader: optimizer.zero_grad() outputs = model(batch_X.unsqueeze(1)) # [batch_size, output_dim] outputs_flat = outputs.view(-1, outputs.shape[-1]) targets_flat = batch_y.view(-1) loss = criterion(outputs_flat, targets_flat) loss.backward() optimizer.step() total_loss += loss.item() if (epoch + 1) % 10 == 0: print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {total_loss/len(dataloader):.4f}') def evaluate_model(model, X_test, y_test): model.eval() with torch.no_grad(): outputs = model(torch.tensor(X_test, dtype=torch.float32).unsqueeze(1)) outputs_flat = outputs.view(-1, outputs.shape[-1]) targets_flat = torch.tensor(y_test, dtype=torch.long).view(-1) accuracy = (outputs_flat.argmax(1) == targets_flat).float().mean() print(f'Test Accuracy: {accuracy.item():.4f}') # 主函数 def main(): csi, allocations, _, snr = load_matlab_data('ofdm_dataset_with_channel.mat') X, y = preprocess_data(csi, allocations, snr) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) model = LSTMModel( input_dim=X_train.shape[1], hidden_dim=128, output_dim=np.max(allocations) + 1 ) train_model(model, X_train, y_train) evaluate_model(model, X_test, y_test) if __name__ == '__main__': main()有Expected input batch_size (32) to match target batch_size (2048).修改一下

import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.models import Model from tensorflow.keras.layers import Input, LSTM, Dense, Dropout, Layer from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau from tensorflow.keras.optimizers import Adam from sklearn.model_selection import TimeSeriesSplit import joblib import tensorflow as tf from tensorflow.keras.models import Model from tensorflow.keras.layers import Input, LSTM, Dense, Dropout, Layer from tensorflow.keras.optimizers import Adam import warnings import tensorflow as tf warnings.filterwarnings('ignore') # ===== 自定义注意力层 ===== class AttentionLayer(Layer): def __init__(self, **kwargs): super(AttentionLayer, self).__init__(**kwargs) def build(self, input_shape): self.time_steps = input_shape[1] self.feature_dim = input_shape[2] # 创建可训练权重 self.W = self.add_weight( name='att_weight', shape=(self.feature_dim, self.feature_dim), initializer='glorot_uniform', trainable=True ) self.b = self.add_weight( name='att_bias', shape=(self.feature_dim,), initializer='zeros', trainable=True ) self.V = self.add_weight( name='att_v', shape=(self.feature_dim, 1), initializer='glorot_uniform', trainable=True ) super(AttentionLayer, self).build(input_shape) def call(self, inputs): # 计算注意力分数 score = tf.tanh(tf.matmul(inputs, self.W) + self.b) # (batch, time_steps, feature_dim) score = tf.matmul(score, self.V) # (batch, time_steps, 1) score = tf.squeeze(score, axis=-1) # (batch, time_steps) # 应用softmax获取注意力权重 alpha = tf.nn.softmax(score, axis=-1) # (batch, time_steps) alpha = tf.expand_dims(alpha, axis=-1) # (batch, time_steps, 1) # 加权求和 context = tf.reduce_sum(alpha * inputs, axis=1) # (batch, feature_dim) return context def compute_output_shape(self, input_shape): return (input_shape[0], input_shape[2]) # (batch_size, feature_dim) # ===== 模型构建函数 ===== def build_attention_lstm_model(input_shape): time_steps, num_features = input_shape inputs = Input(shape=input_shape) # LSTM层 lstm_out = LSTM(128, return_sequences=True)(inputs) lstm_out = Dropout(0.3)(lstm_out) # 使用自定义注意力层 attention_out = AttentionLayer()(lstm_out) # 红球分支 red_branch = Dense(64, activation='relu')(attention_out) red_branch = Dropout(0.2)(red_branch) red_output = Dense(33, activation='sigmoid', name='red_output')(red_branch) # 蓝球分支 blue_branch = Dense(32, activation='relu')(attention_out) blue_branch = Dropout(0.2)(blue_branch) blue_output = Dense(16, activation='sigmoid', name='blue_output')(blue_branch) model = Model(inputs=inputs, outputs=[red_output, blue_output]) optimizer = Adam(learning_rate=0.001) model.compile( optimizer=optimizer, loss={'red_output': 'binary_crossentropy', 'blue_output': 'binary_crossentropy'}, metrics={'red_output': 'binary_accuracy', 'blue_output': 'binary_accuracy'}, # 关键修改:使用字典形式指定损失权重 loss_weights={'red_output': 0.7, 'blue_output': 0.3} ) model.summary() return model # ===== 数据预处理函数 ===== def step1_format_data(): """格式化原始数据""" print("===== 步骤1: 格式化原始数据 =====") df = pd.read_excel('01hand.xlsx', sheet_name='Sheet1', header=None) # 提取A列和C列数据 new_df = pd.DataFrame({ 'A': pd.to_numeric(df.iloc[:, 0], errors='coerce'), 'B': pd.to_numeric(df.iloc[:, 2], errors='coerce') }).dropna() # 保存新文件 new_df.to_excel('01hand2.xlsx', index=False, header=False) print(f"新表格 '01hand2.xlsx' 创建成功! 包含 {len(new_df)} 行数据") def step2_process_data(): """数据去重和排序""" print("\n===== 步骤2: 数据去重和排序 =====") input_file = "01hand2.xlsx" output_file1 = "02resultA.xlsx" # 降序输出 output_file2 = "02resultB.xlsx" # 升序输出 # 读取数据并转换为长格式 df = pd.read_excel(input_file, header=None) all_values = df.stack().dropna().astype(str).tolist() # 确保数据长度是8的倍数 valid_length = len(all_values) - (len(all_values) % 8) if len(all_values) != valid_length: print(f"警告: 数据总量 {len(all_values)} 不符合8的倍数, 截断至 {valid_length} 个元素") all_values = all_values[:valid_length] # 转换数据格式 new_data = [] for i in range(0, len(all_values), 8): group = all_values[i:i+8] try: # 转换日期和数字 date = int(group[0]) numbers = [int(float(num)) if '.' in num else int(num) for num in group[1:]] new_data.append([date] + numbers) except: continue # 创建DataFrame并去重 columns = ['日期', '数字1', '数字2', '数字3', '数字4', '数字5', '数字6', '数字7'] df = pd.DataFrame(new_data, columns=columns) df = df.drop_duplicates(subset='日期').dropna() # 保存降序文件 df.sort_values('日期', ascending=False).to_excel(output_file1, index=False) print(f"降序文件保存至: {output_file1}") # 保存升序文件 df.sort_values('日期', ascending=True).to_excel(output_file2, index=False) print(f"升序文件保存至: {output_file2}") print(f"最终数据维度: {df.shape}") return df # ===== 特征工程函数 ===== def create_features(df, save_features=True): """创建模型特征并保存特征处理器""" print("\n===== 步骤3: 特征工程 =====") features = df[['日期']].copy() red_cols = ['数字1', '数字2', '数字3', '数字4', '数字5', '数字6'] # 基础特征 features['红球和值'] = df[red_cols].sum(axis=1) features['蓝球值'] = df['数字7'] features['奇偶比'] = df[red_cols].applymap(lambda x: x % 2).sum(axis=1) features['大小比'] = df[red_cols].applymap(lambda x: 1 if x > 16 else 0).sum(axis=1) # 窗口特征 (窗口大小10) window_size = 10 for col in ['红球和值', '奇偶比', '大小比']: features[f'{col}_MA{window_size}'] = features[col].rolling(window=window_size).mean() features[f'{col}_STD{window_size}'] = features[col].rolling(window=window_size).std() # 滞后特征 (滞后1-9期) for lag in range(1, 10): for col in red_cols + ['数字7']: features[f'{col}_lag{lag}'] = df[col].shift(lag) # 目标变量 (下一期开奖结果) red_targets = [] blue_targets = [] for i in range(len(df) - 1): next_row = df.iloc[i + 1] # 红球目标 (33选6) red_target = [1 if num in next_row[red_cols].values else 0 for num in range(1, 34)] # 蓝球目标 (16选1) blue_target = [1 if i == next_row['数字7'] else 0 for i in range(1, 17)] red_targets.append(red_target) blue_targets.append(blue_target) # 转换为numpy数组 red_targets = np.array(red_targets) blue_targets = np.array(blue_targets) # 移除无效数据 (前window_size行和最后一行) features = features.iloc[window_size:-1].reset_index(drop=True) red_targets = red_targets[window_size-1:-1] # 对齐索引 blue_targets = blue_targets[window_size-1:-1] # 保存特征处理器 feature_columns = features.drop(columns=['日期']).columns.tolist() joblib.dump(feature_columns, 'feature_columns.pkl') print(f"特征列名已保存: {len(feature_columns)}个特征") if save_features: features.to_excel('04_features.xlsx', index=False) print(f"特征工程完成, 维度: {features.shape}") return features, red_targets, blue_targets # ===== 模型构建函数 ===== def prepare_data(features, red_targets, blue_targets): """准备训练数据并保存数据处理器""" print("\n===== 步骤4: 数据准备 =====") scaler_X = MinMaxScaler() X_scaled = scaler_X.fit_transform(features.drop(columns=['日期'])) # 保存特征处理器 joblib.dump(scaler_X, 'scaler_X.save') print("特征缩放器已保存") # 创建时间序列数据 time_steps = 10 X_seq, y_red_seq, y_blue_seq = [], [], [] for i in range(time_steps, len(X_scaled)): X_seq.append(X_scaled[i-time_steps:i, :]) y_red_seq.append(red_targets[i-1]) # 使用当前时间步的目标 y_blue_seq.append(blue_targets[i-1]) X_seq = np.array(X_seq) y_red_seq = np.array(y_red_seq) y_blue_seq = np.array(y_blue_seq) print(f"时间序列数据形状: X={X_seq.shape}, y_red={y_red_seq.shape}, y_blue={y_blue_seq.shape}") # 保存历史数据用于预测 joblib.dump(X_scaled[-10:], 'historical_data.pkl') print("历史数据已保存用于预测") return X_seq, y_red_seq, y_blue_seq, scaler_X # ===== 模型训练函数 ===== def train_model(X, y_red, y_blue): """训练模型""" print("\n===== 步骤5: 模型训练 =====") best_models = [] tscv = TimeSeriesSplit(n_splits=3) for fold, (train_index, val_index) in enumerate(tscv.split(X)): print(f"\n===== 训练 Fold {fold+1}/3 =====") X_train, X_val = X[train_index], X[val_index] y_red_train, y_red_val = y_red[train_index], y_red[val_index] y_blue_train, y_blue_val = y_blue[train_index], y_blue[val_index] model = build_attention_lstm_model((X_train.shape[1], X_train.shape[2])) callbacks = [ EarlyStopping(monitor='val_loss', patience=15, restore_best_weights=True, verbose=1), ReduceLROnPlateau(monitor='val_loss', factor=0.3, patience=7, min_lr=1e-6, verbose=1) ] history = model.fit( X_train, {'red_output': y_red_train, 'blue_output': y_blue_train}, epochs=100, batch_size=32, validation_data=(X_val, {'red_output': y_red_val, 'blue_output': y_blue_val}), callbacks=callbacks, verbose=1 ) model.save(f'best_model_fold{fold+1}.h5') best_models.append(model) # 保存训练历史图 plot_training_history(history, fold+1) return best_models def plot_training_history(history, fold): """绘制训练历史图表""" plt.figure(figsize=(15, 10)) # 损失曲线 plt.subplot(2, 2, 1) plt.plot(history.history['loss'], label='训练损失') plt.plot(history.history['val_loss'], label='验证损失') plt.title(f'Fold {fold} - 总损失曲线') plt.ylabel('损失') plt.xlabel('Epoch') plt.legend() # 红球准确率 plt.subplot(2, 2, 2) plt.plot(history.history['red_output_binary_accuracy'], label='红球训练准确率') plt.plot(history.history['val_red_output_binary_accuracy'], label='红球验证准确率') plt.title(f'Fold {fold} - 红球准确率') plt.ylabel('准确率') plt.xlabel('Epoch') plt.legend() # 蓝球准确率 plt.subplot(2, 2, 3) plt.plot(history.history['blue_output_binary_accuracy'], label='蓝球训练准确率') plt.plot(history.history['val_blue_output_binary_accuracy'], label='蓝球验证准确率') plt.title(f'Fold {fold} - 蓝球准确率') plt.ylabel('准确率') plt.xlabel('Epoch') plt.legend() # 学习率 plt.subplot(2, 2, 4) if 'lr' in history.history: plt.plot(history.history['lr'], label='学习率') plt.title(f'Fold {fold} - 学习率变化') plt.ylabel('学习率') plt.xlabel('Epoch') plt.legend() plt.tight_layout() plt.savefig(f'training_history_fold{fold}.png') plt.close() # ===== 预测准备函数 ===== def prepare_prediction_input(df, features, scaler_X): """准备预测输入,确保特征一致性""" print("\n===== 准备预测输入 =====") # 加载特征列名 feature_columns = joblib.load('feature_columns.pkl') print(f"预期特征数量: {len(feature_columns)}") # 创建空DataFrame prediction_features = pd.DataFrame(columns=feature_columns) # 获取最后10行有效数据 last_10 = features.iloc[-10:] # 填充基础特征 red_cols = ['数字1', '数字2', '数字3', '数字4', '数字5', '数字6'] current_row = df.iloc[-1] prediction_features.loc[0, '红球和值'] = current_row[red_cols].sum() prediction_features.loc[0, '蓝球值'] = current_row['数字7'] prediction_features.loc[0, '奇偶比'] = current_row[red_cols].apply(lambda x: x % 2).sum() prediction_features.loc[0, '大小比'] = current_row[red_cols].apply(lambda x: 1 if x > 16 else 0).sum() # 填充窗口特征 window_size = 10 for col in ['红球和值', '奇偶比', '大小比']: col_values = features[col].iloc[-window_size:] prediction_features.loc[0, f'{col}_MA{window_size}'] = col_values.mean() prediction_features.loc[0, f'{col}_STD{window_size}'] = col_values.std() # 填充滞后特征 - 修正逻辑 for lag in range(1, 10): # 确保滞后索引有效 lag_index = -lag - 1 # 从当前行向前追溯 for col in red_cols + ['数字7']: feature_name = f'{col}_lag{lag}' if feature_name in feature_columns: if len(df) > lag: prediction_features.loc[0, feature_name] = df[col].iloc[lag_index] else: # 数据不足时使用平均值 prediction_features.loc[0, feature_name] = df[col].mean() # 处理缺失特征 missing_cols = set(feature_columns) - set(prediction_features.columns) for col in missing_cols: prediction_features[col] = 0 # 默认填充0 # 确保顺序一致 prediction_features = prediction_features[feature_columns] # 标准化 X_pred = scaler_X.transform(prediction_features) print(f"预测输入形状: {X_pred.shape}") return X_pred # ===== 预测函数 ===== def predict_next_period(models): """预测下一期开奖结果""" print("\n===== 步骤6: 预测 =====") # 加载历史数据和缩放器 scaler_X = joblib.load('scaler_X.save') historical_data = joblib.load('historical_data.pkl') # 获取特征列名 feature_columns = joblib.load('feature_columns.pkl') n_features = len(feature_columns) # 构建时间序列输入 time_steps = 10 if len(historical_data) >= time_steps: # 使用完整的历史数据 X_seq = historical_data[-time_steps:].reshape(1, time_steps, n_features) else: # 数据不足时复制最后一个时间点 X_seq = np.repeat(historical_data[-1:], time_steps, axis=0).reshape(1, time_steps, n_features) print(f"模型输入序列形状: {X_seq.shape}") # 集成模型预测 red_probs = np.zeros((1, 33)) blue_probs = np.zeros((1, 16)) total_weight = 0 for i, model in enumerate(models): r_prob, b_prob = model.predict(X_seq, verbose=0) weight = 0.3 + i * 0.2 # 加权集成 red_probs += r_prob * weight blue_probs += b_prob * weight total_weight += weight # 归一化概率 red_probs /= total_weight blue_probs /= total_weight # 获取预测结果 red_indices = np.argsort(red_probs[0])[::-1][:6] blue_indices = np.argsort(blue_probs[0])[::-1][:3] return ( [i+1 for i in red_indices], [red_probs[0][i] for i in red_indices], [i+1 for i in blue_indices], [blue_probs[0][i] for i in blue_indices] ) # ===== 主函数 ===== def main(): # 执行数据处理步骤 step1_format_data() df = step2_process_data() # 特征工程 features, red_targets, blue_targets = create_features(df) # 准备训练数据 X, y_red, y_blue, scaler_X = prepare_data(features, red_targets, blue_targets) # 训练模型 models = train_model(X, y_red, y_blue) # 预测 red_nums, red_probs, blue_nums, blue_probs = predict_next_period(models) # 打印结果 print("\n" + "="*50) print("双色球下一期预测结果") print("="*50) print("\n红球预测 (前6个):") for num, prob in zip(red_nums, red_probs): print(f"号码 {num:2d} : 概率 {prob:.4f}") print("\n蓝球预测 (前3个):") for num, prob in zip(blue_nums, blue_probs): print(f"号码 {num:2d} : 概率 {prob:.4f}") # 保存结果 result_df = pd.DataFrame({ '红球预测': red_nums, '红球概率': red_probs, '蓝球预测': blue_nums, '蓝球概率': blue_probs }) result_df.to_excel('prediction_results.xlsx', index=False) print("\n预测结果已保存至: prediction_results.xlsx") if __name__ == "__main__": main() # main.py import tensorflow as tf from tensorflow.keras.models import Model from tensorflow.keras.layers import Input, LSTM, Dense, Dropout, Layer from tensorflow.keras.optimizers import Adam # 内联定义自定义层(避免导入问题) class AttentionLayer(Layer): """自定义注意力层""" def __init__(self, **kwargs): super(AttentionLayer, self).__init__(**kwargs) def build(self, input_shape): self.time_steps = input_shape[1] self.feature_dim = input_shape[2] self.W = self.add_weight( name='att_weight', shape=(self.feature_dim, self.feature_dim), initializer='glorot_uniform', trainable=True ) self.b = self.add_weight( name='att_bias', shape=(self.feature_dim,), initializer='zeros', trainable=True ) self.V = self.add_weight( name='att_v', shape=(self.feature_dim, 1), initializer='glorot_uniform', trainable=True ) super(AttentionLayer, self).build(input_shape) def call(self, inputs): score = tf.tanh(tf.matmul(inputs, self.W) + self.b) score = tf.matmul(score, self.V) score = tf.squeeze(score, axis=-1) alpha = tf.nn.softmax(score, axis=-1) alpha = tf.expand_dims(alpha, axis=-1) context = tf.reduce_sum(alpha * inputs, axis=1) return context def compute_output_shape(self, input_shape): return (input_shape[0], input_shape[2]) # 模型构建函数 def build_attention_lstm_model(input_shape): inputs = Input(shape=input_shape) # LSTM层 lstm_out = LSTM(128, return_sequences=True)(inputs) lstm_out = Dropout(0.3)(lstm_out) # 使用自定义层 attention_out = AttentionLayer()(lstm_out) # 输出分支 red_branch = Dense(64, activation='relu')(attention_out) red_output = Dense(33, activation='sigmoid', name='red_output')(red_branch) blue_branch = Dense(32, activation='relu')(attention_out) blue_output = Dense(16, activation='sigmoid', name='blue_output')(blue_branch) model = Model(inputs=inputs, outputs=[red_output, blue_output]) model.compile( optimizer=Adam(0.001), loss={'red_output': 'binary_crossentropy', 'blue_output': 'binary_crossentropy'}, # 这里也需要修改为字典形式 loss_weights={'red_output': 0.7, 'blue_output': 0.3} ) return model # 测试模型构建 if __name__ == "__main__": model = build_attention_lstm_model(input_shape=(10, 20)) model.summary() print("模型构建成功!") #请优化代码,当前报错:All arrays must be of the same length

帮我解决代码报错: If the loss argument is provided as a dict, the loss_weight argument should also be provided as a dict. Received: loss_weights=[0.7, 0.3];代码如下:import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.models import Model from tensorflow.keras.layers import Input, LSTM, Dense, Dropout, Layer from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau from tensorflow.keras.optimizers import Adam from sklearn.model_selection import TimeSeriesSplit import joblib import tensorflow as tf from tensorflow.keras.models import Model from tensorflow.keras.layers import Input, LSTM, Dense, Dropout, Layer from tensorflow.keras.optimizers import Adam import warnings import tensorflow as tf warnings.filterwarnings('ignore') # ===== 自定义注意力层 ===== class AttentionLayer(Layer): def __init__(self, **kwargs): super(AttentionLayer, self).__init__(**kwargs) def build(self, input_shape): self.time_steps = input_shape[1] self.feature_dim = input_shape[2] # 创建可训练权重 self.W = self.add_weight( name='att_weight', shape=(self.feature_dim, self.feature_dim), initializer='glorot_uniform', trainable=True ) self.b = self.add_weight( name='att_bias', shape=(self.feature_dim,), initializer='zeros', trainable=True ) self.V = self.add_weight( name='att_v', shape=(self.feature_dim, 1), initializer='glorot_uniform', trainable=True ) super(AttentionLayer, self).build(input_shape) def call(self, inputs): # 计算注意力分数 score = tf.tanh(tf.matmul(inputs, self.W) + self.b) # (batch, time_steps, feature_dim) score = tf.matmul(score, self.V) # (batch, time_steps, 1) score = tf.squeeze(score, axis=-1) # (batch, time_steps) # 应用softmax获取注意力权重 alpha = tf.nn.softmax(score, axis=-1) # (batch, time_steps) alpha = tf.expand_dims(alpha, axis=-1) # (batch, time_steps, 1) # 加权求和 context = tf.reduce_sum(alpha * inputs, axis=1) # (batch, feature_dim) return context def compute_output_shape(self, input_shape): return (input_shape[0], input_shape[2]) # (batch_size, feature_dim) # ===== 模型构建函数 ===== def build_attention_lstm_model(input_shape): time_steps, num_features = input_shape inputs = Input(shape=input_shape) # LSTM层 lstm_out = LSTM(128, return_sequences=True)(inputs) lstm_out = Dropout(0.3)(lstm_out) # 使用自定义注意力层 attention_out = AttentionLayer()(lstm_out) # 红球分支 red_branch = Dense(64, activation='relu')(attention_out) red_branch = Dropout(0.2)(red_branch) red_output = Dense(33, activation='sigmoid', name='red_output')(red_branch) # 蓝球分支 blue_branch = Dense(32, activation='relu')(attention_out) blue_branch = Dropout(0.2)(blue_branch) blue_output = Dense(16, activation='sigmoid', name='blue_output')(blue_branch) model = Model(inputs=inputs, outputs=[red_output, blue_output]) optimizer = Adam(learning_rate=0.001) model.compile( optimizer=optimizer, loss={'red_output': 'binary_crossentropy', 'blue_output': 'binary_crossentropy'}, metrics={'red_output': 'binary_accuracy', 'blue_output': 'binary_accuracy'}, loss_weights=[0.7, 0.3] ) model.summary() return model # ===== 其他函数保持不变 ===== # step1_format_data, step2_process_data, create_features, prepare_data, # ===== 数据预处理函数 ===== def step1_format_data(): """格式化原始数据""" print("===== 步骤1: 格式化原始数据 =====") df = pd.read_excel('01hand.xlsx', sheet_name='Sheet1', header=None) # 提取A列和C列数据 new_df = pd.DataFrame({ 'A': pd.to_numeric(df.iloc[:, 0], errors='coerce'), 'B': pd.to_numeric(df.iloc[:, 2], errors='coerce') }).dropna() # 保存新文件 new_df.to_excel('01hand2.xlsx', index=False, header=False) print(f"新表格 '01hand2.xlsx' 创建成功! 包含 {len(new_df)} 行数据") def step2_process_data(): """数据去重和排序""" print("\n===== 步骤2: 数据去重和排序 =====") input_file = "01hand2.xlsx" output_file1 = "02resultA.xlsx" # 降序输出 output_file2 = "02resultB.xlsx" # 升序输出 # 读取数据并转换为长格式 df = pd.read_excel(input_file, header=None) all_values = df.stack().dropna().astype(str).tolist() # 确保数据长度是8的倍数 valid_length = len(all_values) - (len(all_values) % 8) if len(all_values) != valid_length: print(f"警告: 数据总量 {len(all_values)} 不符合8的倍数, 截断至 {valid_length} 个元素") all_values = all_values[:valid_length] # 转换数据格式 new_data = [] for i in range(0, len(all_values), 8): group = all_values[i:i+8] try: # 转换日期和数字 date = int(group[0]) numbers = [int(float(num)) if '.' in num else int(num) for num in group[1:]] new_data.append([date] + numbers) except: continue # 创建DataFrame并去重 columns = ['日期', '数字1', '数字2', '数字3', '数字4', '数字5', '数字6', '数字7'] df = pd.DataFrame(new_data, columns=columns) df = df.drop_duplicates(subset='日期').dropna() # 保存降序文件 df.sort_values('日期', ascending=False).to_excel(output_file1, index=False) print(f"降序文件保存至: {output_file1}") # 保存升序文件 df.sort_values('日期', ascending=True).to_excel(output_file2, index=False) print(f"升序文件保存至: {output_file2}") print(f"最终数据维度: {df.shape}") return df # ===== 特征工程函数 ===== def create_features(df, save_features=True): """创建模型特征并保存特征处理器""" print("\n===== 步骤3: 特征工程 =====") features = df[['日期']].copy() red_cols = ['数字1', '数字2', '数字3', '数字4', '数字5', '数字6'] # 基础特征 features['红球和值'] = df[red_cols].sum(axis=1) features['蓝球值'] = df['数字7'] features['奇偶比'] = df[red_cols].applymap(lambda x: x % 2).sum(axis=1) features['大小比'] = df[red_cols].applymap(lambda x: 1 if x > 16 else 0).sum(axis=1) # 窗口特征 (窗口大小10) window_size = 10 for col in ['红球和值', '奇偶比', '大小比']: features[f'{col}_MA{window_size}'] = features[col].rolling(window=window_size).mean() features[f'{col}_STD{window_size}'] = features[col].rolling(window=window_size).std() # 滞后特征 (滞后1-9期) for lag in range(1, 10): for col in red_cols + ['数字7']: features[f'{col}_lag{lag}'] = df[col].shift(lag) # 目标变量 (下一期开奖结果) red_targets = [] blue_targets = [] for i in range(len(df) - 1): next_row = df.iloc[i + 1] # 红球目标 (33选6) red_target = [1 if num in next_row[red_cols].values else 0 for num in range(1, 34)] # 蓝球目标 (16选1) blue_target = [1 if i == next_row['数字7'] else 0 for i in range(1, 17)] red_targets.append(red_target) blue_targets.append(blue_target) # 转换为numpy数组 red_targets = np.array(red_targets) blue_targets = np.array(blue_targets) # 移除无效数据 (前window_size行和最后一行) features = features.iloc[window_size:-1].reset_index(drop=True) red_targets = red_targets[window_size-1:-1] # 对齐索引 blue_targets = blue_targets[window_size-1:-1] # 保存特征处理器 feature_columns = features.drop(columns=['日期']).columns.tolist() joblib.dump(feature_columns, 'feature_columns.pkl') print(f"特征列名已保存: {len(feature_columns)}个特征") if save_features: features.to_excel('04_features.xlsx', index=False) print(f"特征工程完成, 维度: {features.shape}") return features, red_targets, blue_targets # ===== 模型构建函数 ===== def prepare_data(features, red_targets, blue_targets): """准备训练数据并保存数据处理器""" print("\n===== 步骤4: 数据准备 =====") scaler_X = MinMaxScaler() X_scaled = scaler_X.fit_transform(features.drop(columns=['日期'])) # 保存特征处理器 joblib.dump(scaler_X, 'scaler_X.save') print("特征缩放器已保存") # 创建时间序列数据 time_steps = 10 X_seq, y_red_seq, y_blue_seq = [], [], [] for i in range(time_steps, len(X_scaled)): X_seq.append(X_scaled[i-time_steps:i, :]) y_red_seq.append(red_targets[i-1]) # 使用当前时间步的目标 y_blue_seq.append(blue_targets[i-1]) X_seq = np.array(X_seq) y_red_seq = np.array(y_red_seq) y_blue_seq = np.array(y_blue_seq) print(f"时间序列数据形状: X={X_seq.shape}, y_red={y_red_seq.shape}, y_blue={y_blue_seq.shape}") # 保存历史数据用于预测 joblib.dump(X_scaled[-10:], 'historical_data.pkl') print("历史数据已保存用于预测") return X_seq, y_red_seq, y_blue_seq, scaler_X # train_model, plot_training_history, prepare_prediction_input, predict_next_period, main # ===== 模型训练函数 ===== def train_model(X, y_red, y_blue): """训练模型""" print("\n===== 步骤5: 模型训练 =====") best_models = [] tscv = TimeSeriesSplit(n_splits=3) for fold, (train_index, val_index) in enumerate(tscv.split(X)): print(f"\n===== 训练 Fold {fold+1}/3 =====") X_train, X_val = X[train_index], X[val_index] y_red_train, y_red_val = y_red[train_index], y_red[val_index] y_blue_train, y_blue_val = y_blue[train_index], y_blue[val_index] model = build_attention_lstm_model((X_train.shape[1], X_train.shape[2])) callbacks = [ EarlyStopping(monitor='val_loss', patience=15, restore_best_weights=True, verbose=1), ReduceLROnPlateau(monitor='val_loss', factor=0.3, patience=7, min_lr=1e-6, verbose=1) ] history = model.fit( X_train, {'red_output': y_red_train, 'blue_output': y_blue_train}, epochs=100, batch_size=32, validation_data=(X_val, {'red_output': y_red_val, 'blue_output': y_blue_val}), callbacks=callbacks, verbose=1 ) model.save(f'best_model_fold{fold+1}.h5') best_models.append(model) # 保存训练历史图 plot_training_history(history, fold+1) return best_models def plot_training_history(history, fold): """绘制训练历史图表""" plt.figure(figsize=(15, 10)) # 损失曲线 plt.subplot(2, 2, 1) plt.plot(history.history['loss'], label='训练损失') plt.plot(history.history['val_loss'], label='验证损失') plt.title(f'Fold {fold} - 总损失曲线') plt.ylabel('损失') plt.xlabel('Epoch') plt.legend() # 红球准确率 plt.subplot(2, 2, 2) plt.plot(history.history['red_output_binary_accuracy'], label='红球训练准确率') plt.plot(history.history['val_red_output_binary_accuracy'], label='红球验证准确率') plt.title(f'Fold {fold} - 红球准确率') plt.ylabel('准确率') plt.xlabel('Epoch') plt.legend() # 蓝球准确率 plt.subplot(2, 2, 3) plt.plot(history.history['blue_output_binary_accuracy'], label='蓝球训练准确率') plt.plot(history.history['val_blue_output_binary_accuracy'], label='蓝球验证准确率') plt.title(f'Fold {fold} - 蓝球准确率') plt.ylabel('准确率') plt.xlabel('Epoch') plt.legend() # 学习率 plt.subplot(2, 2, 4) if 'lr' in history.history: plt.plot(history.history['lr'], label='学习率') plt.title(f'Fold {fold} - 学习率变化') plt.ylabel('学习率') plt.xlabel('Epoch') plt.legend() plt.tight_layout() plt.savefig(f'training_history_fold{fold}.png') plt.close() # ===== 预测准备函数 ===== def prepare_prediction_input(df, features, scaler_X): """准备预测输入,确保特征一致性""" print("\n===== 准备预测输入 =====") # 加载特征列名 feature_columns = joblib.load('feature_columns.pkl') print(f"预期特征数量: {len(feature_columns)}") # 创建空DataFrame prediction_features = pd.DataFrame(columns=feature_columns) # 获取最后10行有效数据 last_10 = features.iloc[-10:] # 填充基础特征 red_cols = ['数字1', '数字2', '数字3', '数字4', '数字5', '数字6'] current_row = df.iloc[-1] prediction_features.loc[0, '红球和值'] = current_row[red_cols].sum() prediction_features.loc[0, '蓝球值'] = current_row['数字7'] prediction_features.loc[0, '奇偶比'] = current_row[red_cols].apply(lambda x: x % 2).sum() prediction_features.loc[0, '大小比'] = current_row[red_cols].apply(lambda x: 1 if x > 16 else 0).sum() # 填充窗口特征 window_size = 10 for col in ['红球和值', '奇偶比', '大小比']: col_values = features[col].iloc[-window_size:] prediction_features.loc[0, f'{col}_MA{window_size}'] = col_values.mean() prediction_features.loc[0, f'{col}_STD{window_size}'] = col_values.std() # 填充滞后特征 - 修正逻辑 for lag in range(1, 10): # 确保滞后索引有效 lag_index = -lag - 1 # 从当前行向前追溯 for col in red_cols + ['数字7']: feature_name = f'{col}_lag{lag}' if feature_name in feature_columns: if len(df) > lag: prediction_features.loc[0, feature_name] = df[col].iloc[lag_index] else: # 数据不足时使用平均值 prediction_features.loc[0, feature_name] = df[col].mean() # 处理缺失特征 missing_cols = set(feature_columns) - set(prediction_features.columns) for col in missing_cols: prediction_features[col] = 0 # 默认填充0 # 确保顺序一致 prediction_features = prediction_features[feature_columns] # 标准化 X_pred = scaler_X.transform(prediction_features) print(f"预测输入形状: {X_pred.shape}") return X_pred # ===== 预测函数 ===== def predict_next_period(models): """预测下一期开奖结果""" print("\n===== 步骤6: 预测 =====") # 加载历史数据和缩放器 scaler_X = joblib.load('scaler_X.save') historical_data = joblib.load('historical_data.pkl') # 获取特征列名 feature_columns = joblib.load('feature_columns.pkl') n_features = len(feature_columns) # 构建时间序列输入 time_steps = 10 if len(historical_data) >= time_steps: # 使用完整的历史数据 X_seq = historical_data[-time_steps:].reshape(1, time_steps, n_features) else: # 数据不足时复制最后一个时间点 X_seq = np.repeat(historical_data[-1:], time_steps, axis=0).reshape(1, time_steps, n_features) print(f"模型输入序列形状: {X_seq.shape}") # 集成模型预测 red_probs = np.zeros((1, 33)) blue_probs = np.zeros((1, 16)) total_weight = 0 for i, model in enumerate(models): r_prob, b_prob = model.predict(X_seq, verbose=0) weight = 0.3 + i * 0.2 # 加权集成 red_probs += r_prob * weight blue_probs += b_prob * weight total_weight += weight # 归一化概率 red_probs /= total_weight blue_probs /= total_weight # 获取预测结果 red_indices = np.argsort(red_probs[0])[::-1][:6] blue_indices = np.argsort(blue_probs[0])[::-1][:3] return ( [i+1 for i in red_indices], [red_probs[0][i] for i in red_indices], [i+1 for i in blue_indices], [blue_probs[0][i] for i in blue_indices] ) # ===== 主函数 ===== def main(): # 执行数据处理步骤 step1_format_data() df = step2_process_data() # 特征工程 features, red_targets, blue_targets = create_features(df) # 准备训练数据 X, y_red, y_blue, scaler_X = prepare_data(features, red_targets, blue_targets) # 训练模型 models = train_model(X, y_red, y_blue) # 预测 red_nums, red_probs, blue_nums, blue_probs = predict_next_period(models) # 打印结果 print("\n" + "="*50) print("双色球下一期预测结果") print("="*50) print("\n红球预测 (前6个):") for num, prob in zip(red_nums, red_probs): print(f"号码 {num:2d} : 概率 {prob:.4f}") print("\n蓝球预测 (前3个):") for num, prob in zip(blue_nums, blue_probs): print(f"号码 {num:2d} : 概率 {prob:.4f}") # 保存结果 result_df = pd.DataFrame({ '红球预测': red_nums, '红球概率': red_probs, '蓝球预测': blue_nums, '蓝球概率': blue_probs }) result_df.to_excel('prediction_results.xlsx', index=False) print("\n预测结果已保存至: prediction_results.xlsx") if __name__ == "__main__": main() # main.py import tensorflow as tf from tensorflow.keras.models import Model from tensorflow.keras.layers import Input, LSTM, Dense, Dropout, Layer from tensorflow.keras.optimizers import Adam # 内联定义自定义层(避免导入问题) class AttentionLayer(Layer): """自定义注意力层""" def __init__(self, **kwargs): super(AttentionLayer, self).__init__(**kwargs) def build(self, input_shape): self.time_steps = input_shape[1] self.feature_dim = input_shape[2] self.W = self.add_weight( name='att_weight', shape=(self.feature_dim, self.feature_dim), initializer='glorot_uniform', trainable=True ) self.b = self.add_weight( name='att_bias', shape=(self.feature_dim,), initializer='zeros', trainable=True ) self.V = self.add_weight( name='att_v', shape=(self.feature_dim, 1), initializer='glorot_uniform', trainable=True ) super(AttentionLayer, self).build(input_shape) def call(self, inputs): score = tf.tanh(tf.matmul(inputs, self.W) + self.b) score = tf.matmul(score, self.V) score = tf.squeeze(score, axis=-1) alpha = tf.nn.softmax(score, axis=-1) alpha = tf.expand_dims(alpha, axis=-1) context = tf.reduce_sum(alpha * inputs, axis=1) return context def compute_output_shape(self, input_shape): return (input_shape[0], input_shape[2]) # 模型构建函数 def build_attention_lstm_model(input_shape): inputs = Input(shape=input_shape) # LSTM层 lstm_out = LSTM(128, return_sequences=True)(inputs) lstm_out = Dropout(0.3)(lstm_out) # 使用自定义层 attention_out = AttentionLayer()(lstm_out) # 输出分支 red_branch = Dense(64, activation='relu')(attention_out) red_output = Dense(33, activation='sigmoid', name='red_output')(red_branch) blue_branch = Dense(32, activation='relu')(attention_out) blue_output = Dense(16, activation='sigmoid', name='blue_output')(blue_branch) model = Model(inputs=inputs, outputs=[red_output, blue_output]) model.compile( optimizer=Adam(0.001), loss={'red_output': 'binary_crossentropy', 'blue_output': 'binary_crossentropy'}, loss_weights={'red_output': 0.7, 'blue_output': 0.3} ) return model # 测试模型构建 if __name__ == "__main__": model = build_attention_lstm_model(input_shape=(10, 20)) model.summary() print("模型构建成功!")

最新推荐

recommend-type

工业自动化领域中步科触摸屏与台达VFD-M变频器通讯实现电机控制功能 - 电机控制

内容概要:本文档详细介绍了使用步科触摸屏和台达VFD-M变频器实现电机控制功能的技术细节。主要内容涵盖所需的硬件配置(如步科T070触摸屏和支持485功能的USB转485转换头),以及具体的功能实现方法,包括正反转控制、点动停止、频率设定、运行频率读取、电流电压和运行状态的监控。此外,还强调了通讯协议的重要性及其具体实施步骤。 适用人群:从事工业自动化领域的工程师和技术人员,特别是那些负责电机控制系统设计和维护的专业人士。 使用场景及目标:适用于需要集成步科触摸屏与台达VFD-M变频器进行电机控制的应用场合,旨在帮助技术人员掌握正确的硬件选型、安装配置及编程技巧,从而确保系统的稳定性和可靠性。 其他说明:文中提到的操作流程和注意事项有助于避免常见的错误并提高工作效率。同时,提供了详细的通讯说明,确保不同设备之间的兼容性和数据传输的准确性。
recommend-type

langchain4j-community-core-1.0.0-beta4.jar中文-英文对照文档.zip

1、压缩文件中包含: 中文-英文对照文档、jar包下载地址、Maven依赖、Gradle依赖、源代码下载地址。 2、使用方法: 解压最外层zip,再解压其中的zip包,双击 【index.html】 文件,即可用浏览器打开、进行查看。 3、特殊说明: (1)本文档为人性化翻译,精心制作,请放心使用; (2)只翻译了该翻译的内容,如:注释、说明、描述、用法讲解 等; (3)不该翻译的内容保持原样,如:类名、方法名、包名、类型、关键字、代码 等。 4、温馨提示: (1)为了防止解压后路径太长导致浏览器无法打开,推荐在解压时选择“解压到当前文件夹”(放心,自带文件夹,文件不会散落一地); (2)有时,一套Java组件会有多个jar,所以在下载前,请仔细阅读本篇描述,以确保这就是你需要的文件。 5、本文件关键字: jar中文-英文对照文档.zip,java,jar包,Maven,第三方jar包,组件,开源组件,第三方组件,Gradle,中文API文档,手册,开发手册,使用手册,参考手册。
recommend-type

介电弹性体PID DEA模型的参数配置、控制策略与MatlabSimulink建模研究 实战版

内容概要:本文详细探讨了介电弹性体(DEA)PID控制模型的参数配置、控制策略及其在Matlab/Simulink环境中的建模方法。首先介绍了DEA的基本特性如迟滞和非线性响应,并给出了具体的机械系统参数(如刚度、质量和阻尼)。接着讨论了PID控制器的设计,包括基础的位置式PID实现以及针对实际应用需要加入的抗饱和和滤波措施。对于存在输入延迟的情况,提出了使用Smith预估器的方法,并指出其对模型精度的要求。面对突加负载等扰动,推荐采用串级控制提高系统的稳定性。最后强调了利用Automated PID Tuning工具进行参数调整时应注意的问题。 适合人群:从事智能材料控制系统研究的科研人员和技术开发者。 使用场景及目标:适用于希望深入了解并优化介电弹性体驱动器性能的研究者,在理论学习的基础上掌握具体的操作技能,从而更好地应对实际工程中的挑战。 其他说明:文中提供了详细的MATLAB代码片段用于指导读者构建自己的DEA控制模型,同时分享了许多实践经验,帮助避免常见的错误。
recommend-type

pso_uav.zip

1.版本:matlab2014a/2019b/2024b 2.附赠案例数据可直接运行。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。
recommend-type

Webdiy.net新闻系统v1.0企业版发布:功能强大、易操作

标题中提到的"Webdiy.net新闻系统 v1.0 企业版"是一个针对企业级应用开发的新闻内容管理系统,是基于.NET框架构建的。从描述中我们可以提炼出以下知识点: 1. **系统特性**: - **易用性**:系统设计简单,方便企业用户快速上手和操作。 - **可定制性**:用户可以轻松修改网站的外观和基本信息,例如网页标题、页面颜色、页眉和页脚等,以符合企业的品牌形象。 2. **数据库支持**: - **Access数据库**:作为轻量级数据库,Access对于小型项目和需要快速部署的场景非常合适。 - **Sql Server数据库**:适用于需要强大数据处理能力和高并发支持的企业级应用。 3. **性能优化**: - 系统针对Access和Sql Server数据库进行了特定的性能优化,意味着它能够提供更为流畅的用户体验和更快的数据响应速度。 4. **编辑器功能**: - **所见即所得编辑器**:类似于Microsoft Word,允许用户进行图文混排编辑,这样的功能对于非技术人员来说非常友好,因为他们可以直观地编辑内容而无需深入了解HTML或CSS代码。 5. **图片管理**: - 新闻系统中包含在线图片上传、浏览和删除的功能,这对于新闻编辑来说是非常必要的,可以快速地为新闻内容添加相关图片,并且方便地进行管理和更新。 6. **内容发布流程**: - **审核机制**:后台发布新闻后,需经过审核才能显示到网站上,这样可以保证发布的内容质量,减少错误和不当信息的传播。 7. **内容排序与类别管理**: - 用户可以按照不同的显示字段对新闻内容进行排序,这样可以突出显示最新或最受欢迎的内容。 - 新闻类别的动态管理及自定义显示顺序,可以灵活地对新闻内容进行分类,方便用户浏览和查找。 8. **前端展示**: - 系统支持Javascript前端页面调用,这允许开发者将系统内容嵌入到其他网页或系统中。 - 支持iframe调用,通过这种HTML元素可以将系统内容嵌入到网页中,实现了内容的跨域展示。 9. **安全性**: - 提供了默认的管理账号和密码(webdiy / webdiy.net),对于企业应用来说,这些默认的凭证需要被替换,以保证系统的安全性。 10. **文件结构**: - 压缩包文件名称为"webdiynetnews",这可能是系统的根目录名称或主要安装文件。 11. **技术栈**: - 系统基于ASP.NET技术构建,这表明它使用.NET框架开发,并且可以利用.NET生态中的各种库和工具来实现功能的扩展和维护。 在实施和部署这样的系统时,企业可能还需要考虑以下方面: - **可扩展性**:随着业务的增长,系统应该能容易地扩展,以支持更多的用户和内容。 - **安全性**:除了更改为安全的管理员凭证外,还需考虑防止SQL注入、XSS攻击等网络安全问题。 - **备份和恢复**:定期备份数据库和内容是很重要的,以防数据丢失或需要恢复到先前的状态。 - **多用户和权限管理**:企业环境可能需要多级用户权限设置,以适应不同的团队和角色。 - **SEO优化**:系统应支持良好的搜索引擎优化实践,以便于内容在搜索引擎中的排名和发现。 - **移动适应性**:由于移动设备的广泛使用,系统应具备良好的响应式设计,以提供良好的移动用户体验。 根据描述,该系统似乎是一个成熟的解决方案,适用于需要快速搭建新闻网站的企业用户,但同时也应该注意定期的维护和更新,以确保系统的稳定性和安全性。
recommend-type

【Windows 11用户的福音】:一步到位解决GX Works2安装问题,让兼容性不再是问题!

# 1. GX Works2简介与Windows 11兼容性问题 ## 简介GX Works2 GX Works2是由三菱电机开发的一款针对其PLC(可编程逻辑控制器)产品的编程和调试软件。该软件以其直观的用户界面和强大的编程功能闻名于工业自动化领域,支持从简单的逻辑控制到复杂的系统集成项目。随着Windows操作系统的迭代升级,尤其是新推
recommend-type

电磁加热双边谐振和单边谐振的区别

<think>我们正在处理关于电磁加热技术中双边谐振与单边谐振的工作原理及区别的问题。 首先,需要明确用户意图是了解这两种谐振方式的区别以及它们的工作原理。 我们将通过以下步骤进行: 1. 调用网络搜索工具,检索关于电磁加热中双边谐振和单边谐振的信息。 2. 整合检索到的内容,按照要求生成回答,包括工作原理和区别,并组织成多个方法或步骤(但避免使用步骤词汇,用换行分隔)。 3. 在回答中,如果有公式或代码,按照指定格式处理。 4. 最后,添加相关问题部分。 注意:避免使用第一人称,避免步骤词汇,引用内容不集中末尾,而是融入回答中。 根据搜索,电磁加热中的谐振通常指的是感应加
recommend-type

EnvMan源代码压缩包内容及功能解析

根据给定文件信息,我们需要生成关于“EnvMan-source.zip”这一压缩包的知识点。首先,由于提供的信息有限,我们无法直接得知EnvMan-source.zip的具体内容和功能,但可以通过标题、描述和标签中的信息进行推断。文件名称列表只有一个“EnvMan”,这暗示了压缩包可能包含一个名为EnvMan的软件或项目源代码。以下是一些可能的知识点: ### EnvMan软件/项目概览 EnvMan可能是一个用于环境管理的工具或框架,其源代码被打包并以“EnvMan-source.zip”的形式进行分发。通常,环境管理相关的软件用于构建、配置、管理和维护应用程序的运行时环境,这可能包括各种操作系统、服务器、中间件、数据库等组件的安装、配置和版本控制。 ### 源代码文件说明 由于只有一个名称“EnvMan”出现在文件列表中,我们可以推测这个压缩包可能只包含一个与EnvMan相关的源代码文件夹。源代码文件夹可能包含以下几个部分: - **项目结构**:展示EnvMan项目的基本目录结构,通常包括源代码文件(.c, .cpp, .java等)、头文件(.h, .hpp等)、资源文件(图片、配置文件等)、文档(说明文件、开发者指南等)、构建脚本(Makefile, build.gradle等)。 - **开发文档**:可能包含README文件、开发者指南或者项目wiki,用于说明EnvMan的功能、安装、配置、使用方法以及可能的API说明或开发者贡献指南。 - **版本信息**:在描述中提到了版本号“-1101”,这表明我们所见的源代码包是EnvMan的1101版本。通常版本信息会详细记录在版本控制文件(如ChangeLog或RELEASE_NOTES)中,说明了本次更新包含的新特性、修复的问题、已知的问题等。 ### 压缩包的特点 - **命名规范**:标题、描述和标签中的一致性表明这是一个正式发布的软件包。通常,源代码包的命名会遵循一定的规范,如“项目名称-版本号-类型”,在这里类型是“source”。 - **分发形式**:以.zip格式的压缩包进行分发,是一种常见的软件源代码分发方式。虽然较现代的版本控制系统(如Git、Mercurial)通常支持直接从仓库克隆源代码,但打包成zip文件依然是一种便于存储和传输的手段。 ### 可能的应用场景 - **开发环境配置**:EnvMan可能是用于创建、配置和管理开发环境的工具,这种工具在开发人员设置新的开发机或新的项目环境时非常有用。 - **自动化部署**:EnvMan可能包含自动化部署环境的脚本或命令,使得部署流程变得快捷且高效。 - **监控与维护**:作为环境管理工具,EnvMan可能还支持对环境的监控功能,包括系统资源监控、服务状态检查等,以保证生产环境的稳定性。 ### 总结 尽管以上知识点是基于有限的信息进行的假设性推论,但EnvMan-source.zip包可能是一个用于环境管理的软件或项目的源代码包。该软件或项目可能包含构建和部署自动化环境的能力,以及对运行时环境的监控和维护。文件命名的一致性暗示这是一个正式的版本发布。如果要深入了解EnvMan的功能与用法,建议直接查看压缩包中的文档或源代码注释。同时,考虑到源代码的开发,我们还应该探究该项目所使用的技术栈、编程语言以及版本控制工具等,这将有助于进一步了解EnvMan的技术细节。
recommend-type

【Windows 11终极解决方案】:彻底攻克GX Works2安装中难缠的.Net Framework 3.5障碍!

# 1. Windows 11与GX Works2简介 ## 1.1 Windows 11操作系统概览 Windows 11,作为微软最新的操作系统,不仅仅提供了一种现代的用户体验,而且加强了在企业环境中的安全性与生产力工具。其引入了全新的界面设计、改进的多任务处理以及对Android应用的支持,使它成为IT专业人
recommend-type

贝叶斯gmm

<think>首先,用户的问题是关于贝叶斯高斯混合模型(Bayesian Gaussian Mixture Model, BGMM)的原理和应用。我需要根据系统指令来构建回答。 系统指令包括: - 所有行内数学表达式使用 `$...$` 格式。 - 独立公式使用 `$$...$$` 格式并单独成段。 - LaTeX语法正确。 - 使用中文回答。 - 生成相关问题。 - 在回答中引用的段落末尾自然地添加引用标识,如 `[^1]`。 - 回答结构清晰,帮助用户逐步解决问题。 - 保证回答真实可靠。 参考提供的引用: - 引用[1]:讨论了高斯混合模型在机器学习中的应用,包括其优点和挑战。 -