Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import tensorflow as tf # importujemy TensorFlow jako tf
- import numpy as np # importujemy NumPy jako np, do operacji na tablicach
- import matplotlib.pyplot as plt # do wizualizacji
- from tensorflow.keras import Sequential # import klasy modelu sekwencyjnego
- from tensorflow.keras.layers import Dense # import warstwy Dense (gęstej)
- # 1) Budujemy prosty model: pojedyncza warstwa Dense (regresja liniowa)
- model = Sequential([
- Dense(units=1, input_shape=[1]) # 1 neuron, 1 wymiar wejścia
- ])
- model.compile(optimizer='sgd', loss='mean_squared_error')
- # 2) Dane treningowe: wektory xs (wejścia) i ys (cele)
- xs = np.array([-1, 0, 1, 2, 3, 4], dtype=float)
- ys = np.array([-5, -2, 1, 4, 7, 10], dtype=float)
- # 3) Trening modelu przez 500 epok
- history = model.fit(xs, ys, epochs=500, verbose=0)
- # 4) Wyciągamy parametry (w, b) i prognozy
- w, b = model.get_weights()
- y_pred = model.predict(xs).flatten()
- # 5) Wizualizacja:
- plt.figure(figsize=(6,4))
- plt.scatter(xs, ys, color='blue', label='Dane treningowe')
- plt.plot(xs, y_pred, color='red', linewidth=2,
- label=f'y = {w[0,0]:.2f} x + {b[0]:.2f}')
- plt.title('Regresja liniowa z TensorFlow')
- plt.xlabel('x')
- plt.ylabel('y')
- plt.legend()
- plt.grid(True)
- plt.show()
- # 6) Wykres funkcji straty podczas treningu:
- plt.figure(figsize=(6,4))
- plt.plot(history.history['loss'], label='Loss (MSE)')
- plt.title('Spadek funkcji straty podczas treningu')
- plt.xlabel('Epoka')
- plt.ylabel('MSE')
- plt.legend()
- plt.grid(True)
- plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement