Keras: Modeling A X1 + B X2 + C = Y

From OnnoWiki
Jump to navigation Jump to search

Prompt chatgpt

buat source code python menggunakan keras untuk analisa data
A*X1 + B*X2 + C = Y. Plot loss, plot grafik model vs X1, X2, Y

Source code:

Berikut adalah source code Python lengkap menggunakan Keras untuk menganalisis data berbentuk persamaan linier `Y = A*X1 + B*X2 + C`. Kode ini melibatkan:

  1. Pembuatan data sintetis.
  2. Pembuatan model Keras.
  3. Pelatihan model dan visualisasi loss.
  4. Plot hasil prediksi terhadap nilai sebenarnya.
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam

# 1. Generate synthetic data: Y = A*X1 + B*X2 + C
np.random.seed(0)
A, B, C = 3.5, -2.2, 7.0  # ground truth parameters

num_samples = 500
X1 = np.random.uniform(-10, 10, num_samples)
X2 = np.random.uniform(-10, 10, num_samples)
noise = np.random.normal(0, 2, num_samples)  # add some noise

Y = A * X1 + B * X2 + C + noise

# Prepare input features and output
X = np.stack((X1, X2), axis=1)

# 2. Build a simple Keras model
model = Sequential()
model.add(Dense(1, input_dim=2))  # linear regression model

model.compile(optimizer=Adam(learning_rate=0.01), loss='mse')

# 3. Train the model
history = model.fit(X, Y, epochs=100, verbose=0)

# 4. Plot training loss
plt.figure()
plt.plot(history.history['loss'])
plt.title("Training Loss Over Epochs")
plt.xlabel("Epoch")
plt.ylabel("MSE Loss")
plt.grid(True)
plt.show()

# 5. Predict using the model
Y_pred = model.predict(X).flatten()

# 6. Plot predicted Y vs true Y
plt.figure()
plt.scatter(Y, Y_pred, alpha=0.5)
plt.xlabel("True Y")
plt.ylabel("Predicted Y")
plt.title("Model Prediction vs True Values")
plt.plot([Y.min(), Y.max()], [Y.min(), Y.max()], 'r--')  # ideal line
plt.grid(True)
plt.show()

# 7. Plot 3D surface of predictions
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X1, X2, Y, label='True Y', alpha=0.4)
ax.scatter(X1, X2, Y_pred, label='Predicted Y', alpha=0.4)
ax.set_xlabel("X1")
ax.set_ylabel("X2")
ax.set_zlabel("Y / Y_pred")
plt.title("3D Plot: X1, X2 vs Y and Predicted Y")
plt.legend()
plt.show()


Penjelasan Singkat:

  • **Model**: Ini adalah model regresi linier sederhana (`Dense(1)` tanpa aktivasi).
  • **Data**: Dibuat menggunakan persamaan linear dengan sedikit noise untuk menyerupai data dunia nyata.
  • **Visualisasi**:
    • Plot **loss** untuk melihat konvergensi.
    • Plot **prediksi vs nilai asli**.
    • Plot **3D** untuk melihat bagaimana model mendekati permukaan sebenarnya.

Jika kamu ingin menguji apakah model mempelajari nilai A, B, dan C yang benar, kamu bisa melihat bobot model:


weights = model.get_weights()
print("Learned weights (A, B):", weights[0].flatten())
print("Learned bias (C):", weights[1])

Ingin saya ubah agar model ini bisa memprediksi dari file data CSV atau ingin visualisasi lain?