1.參考Python實戰:BP神經網絡_bp神經網絡實戰python-CSDN博客
2.實踐
(1)運行環境
anocanda Powershell Prompt(anocanda3)
(2)創建虛擬環境,解決安裝包的版本問題
*打開終端(Terminal)或命令提示符(Command Prompt):
??? 在Windows上,可以通過搜索“cmd”來打開命令提示符。
*創建新的虛擬環境:
使用conda命令來創建虛擬環境。下面是一個基本的例子,其中myenv是你的環境名稱,而python=3.8指定了你希望在這個環境中使用的Python版本。
conda create --name myenv python=3.8
*激活虛擬環境:
創建完成后,你需要通過以下命令激活這個環境:
??? 對于Windows用戶:
conda activate myenv
*安裝所需要的包
(3)運行代碼:
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 使用黑體字體
plt.rcParams['axes.unicode_minus'] = False # 解決負號 '-' 顯示為方塊的問題
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn.model_selection import train_test_split# 定義學生成績數據集,這里為方便演示,手動創建示例數據
data = np.array([[80, 75],[85, 80],[70, 65],[90, 88],[75, 70],[88, 82],[65, 60],[92, 90]
])
final_scores = np.array([82, 88, 72, 92, 76, 86, 68, 95])# 劃分訓練集和測試集,按照8:2的比例劃分,設置隨機種子以保證每次劃分結果可重復
X_train, X_test, y_train, y_test = train_test_split(data, final_scores, test_size=0.2, random_state=42)# 構建BP神經網絡模型
model = Sequential()
# 輸入層,有2個神經元,對應2個輸入特征(作業成績和小測驗成績),激活函數為ReLU
model.add(Dense(16, input_dim=2, activation='relu'))
# 隱藏層,16個神經元,激活函數為ReLU
model.add(Dense(16, activation='relu'))
# 輸出層,1個神經元,對應期末考試成績,激活函數為線性(因為是回歸任務)
model.add(Dense(1, activation='linear'))# 編譯模型,指定優化器、損失函數和評估指標
model.compile(optimizer='adam',loss='mean_squared_error',metrics=['mae']) # 平均絕對誤差(MAE)作為評估指標# 訓練模型,指定訓練輪數、批量大小等參數
epochs = 100
batch_size = 2
history = model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size,validation_data=(X_test, y_test), verbose=0)# 獲取訓練過程中的損失和驗證損失歷史數據
loss_history = history.history['loss']
val_loss_history = history.history['val_loss']# 可視化訓練損失和驗證損失曲線
plt.figure(figsize=(10, 6))
plt.plot(range(1, epochs + 1), loss_history, label='訓練損失')
plt.plot(range(1, epochs + 1), val_loss_history, label='驗證損失')
plt.xlabel('輪數')
plt.ylabel('損失值')
plt.title('BP神經網絡訓練損失曲線')
plt.legend()
plt.show()# 使用訓練好的模型對測試集進行預測
y_pred = model.predict(X_test).flatten() # 將二維數組展平為一維數組# 可視化預測結果與實際結果(簡單示例,以測試集為例)
plt.figure(figsize=(10, 6))
plt.scatter(range(len(y_test)), y_test, label='實際成績', color='blue')
plt.scatter(range(len(y_pred)), y_pred, label='預測成績', color='red')
plt.xlabel('樣本索引')
plt.ylabel('期末考試成績')
plt.title('BP神經網絡預測學生成績結果')
plt.legend()
plt.show()# 調試信息
print("y_test shape:", y_test.shape)
print("y_pred shape:", y_pred.shape)
print("y_test type:", type(y_test))
print("y_pred type:", type(y_pred))