การทำนายข้อมูลด้วย MLPRegressor (Train)
..
👉..
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import pickle
import joblib
from sklearn.model_selection import train_test_split, learning_curve
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPRegressor
from sklearn.metrics import mean_squared_error, r2_score
# 1. Load the data from a CSV file
data = pd.read_csv(r"C:\Users\user\Desktop\motor_log.csv") # Replace with your CSV file path
# Suppose the CSV has features 'current', 'volt', 'vibration' and the target 'perform'
X = data[['current', 'volt', 'vibration']].values
y = data['perform'].values
# 2. Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 3. Scale the features (important for neural networks)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# 4. Create and train the nonlinear regression neural network using MLPRegressor
# Define a network with two hidden layers: first with 100 nodes, second with 50 nodes
mlp = MLPRegressor(hidden_layer_sizes=(100, 50),
activation='relu',
solver='adam',
max_iter=1000,
random_state=42)
for epoch in range(1000): # Manually iterate over epochs
mlp.partial_fit(X_train_scaled, y_train)
print(f"Epoch {epoch+1}, Loss: {mlp.loss_:.4f}")
# Fit the model on the training data
mlp.fit(X_train_scaled, y_train)
# 5. Plot the learning curve
# The learning_curve function returns training sizes, training scores, and cross-validation scores.
train_sizes, train_scores, test_scores = learning_curve(
mlp,
X_train_scaled,
y_train,
cv=2, # Changed from 5 to 2 folds to avoid the error
scoring="neg_mean_squared_error",
train_sizes=np.linspace(0.1, 1.0, 10)
)
# Convert negative MSE to positive values by negating the scores for plot data
train_errors = -np.mean(train_scores, axis=1)
test_errors = -np.mean(test_scores, axis=1)
# 6. Plot the learning curve
plt.figure(figsize=(10, 6))
plt.plot(train_sizes, train_errors, 'o-', color="r", label="Training Error")
plt.plot(train_sizes, test_errors, 'o-', color="g", label="Cross-Validation Error")
plt.xlabel("Training Set Size")
plt.ylabel("Mean Squared Error")
plt.title("Learning Curve for MLPRegressor")
plt.legend(loc="best")
plt.grid(True)
plt.show()
# 7. Save the model and scaler to disk
with open(r"C:\Users\user\Desktop\mlp_model.pkl", "wb") as file:
pickle.dump(mlp, file)
joblib.dump(scaler, r"C:\Users\user\Desktop\scaler.pkl")
print("Model and scaler saved successfully!")
เมื่อรันโปรแกรมแล้วผลลัพท์ที่ได้