Advertisement
gandalfbialy

Untitled

Jun 7th, 2025
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. import tensorflow as tf # importujemy TensorFlow jako tf
  2. import numpy as np # importujemy NumPy jako np, do operacji na tablicach
  3. import matplotlib.pyplot as plt # do wizualizacji
  4. from tensorflow.keras import Sequential # import klasy modelu sekwencyjnego
  5. from tensorflow.keras.layers import Dense # import warstwy Dense (gęstej)
  6.  
  7. # 1) Budujemy prosty model: pojedyncza warstwa Dense (regresja liniowa)
  8. model = Sequential([
  9. Dense(units=1, input_shape=[1]) # 1 neuron, 1 wymiar wejścia
  10. ])
  11. model.compile(optimizer='sgd', loss='mean_squared_error')
  12.  
  13. # 2) Dane treningowe: wektory xs (wejścia) i ys (cele)
  14. xs = np.array([-1, 0, 1, 2, 3, 4], dtype=float)
  15. ys = np.array([-5, -2, 1, 4, 7, 10], dtype=float)
  16.  
  17. # 3) Trening modelu przez 500 epok
  18. history = model.fit(xs, ys, epochs=500, verbose=0)
  19.  
  20. # 4) Wyciągamy parametry (w, b) i prognozy
  21. w, b = model.get_weights()
  22. y_pred = model.predict(xs).flatten()
  23.  
  24. # 5) Wizualizacja:
  25. plt.figure(figsize=(6,4))
  26. plt.scatter(xs, ys, color='blue', label='Dane treningowe')
  27. plt.plot(xs, y_pred, color='red', linewidth=2,
  28. label=f'y = {w[0,0]:.2f} x + {b[0]:.2f}')
  29. plt.title('Regresja liniowa z TensorFlow')
  30. plt.xlabel('x')
  31. plt.ylabel('y')
  32. plt.legend()
  33. plt.grid(True)
  34. plt.show()
  35.  
  36. # 6) Wykres funkcji straty podczas treningu:
  37. plt.figure(figsize=(6,4))
  38. plt.plot(history.history['loss'], label='Loss (MSE)')
  39. plt.title('Spadek funkcji straty podczas treningu')
  40. plt.xlabel('Epoka')
  41. plt.ylabel('MSE')
  42. plt.legend()
  43. plt.grid(True)
  44. plt.show()
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement