๐ง TensorFlow Basics
TensorFlow is a powerful library for numerical computation and large-scale machine learning.
Mastering this concept will significantly boost your Python data science skills!
๐ป Code Example:
import tensorflow as tf from tensorflow import keras import numpy as np print("TensorFlow version:", tf.__version__) # 1. Basic tensor operations a = tf.constant([[1.0, 2.0], [3.0, 4.0]]) b = tf.constant([[5.0, 6.0], [7.0, 8.0]]) print("Matrix multiply:\n", tf.matmul(a, b).numpy()) # 2. Build a simple neural network (Classification) np.random.seed(42) X = np.random.randn(1000, 4).astype("float32") # 4 features y = (X[:, 0] + X[:, 1] > 0).astype("int32") # Binary target model = keras.Sequential([ keras.layers.Dense(16, activation="relu", input_shape=(4,), name="hidden_1"), keras.layers.Dropout(0.2), keras.layers.Dense(8, activation="relu", name="hidden_2"), keras.layers.Dense(1, activation="sigmoid", name="output"), ]) model.compile( optimizer=keras.optimizers.Adam(learning_rate=0.01), loss="binary_crossentropy", metrics=["accuracy"], ) model.summary() # 3. Train history = model.fit(X, y, epochs=10, batch_size=32, validation_split=0.2, verbose=0) train_acc = history.history["accuracy"][-1] val_acc = history.history["val_accuracy"][-1] print(f"\nTrain accuracy: {train_acc:.3f} | Val accuracy: {val_acc:.3f}") # 4. Predict sample = np.array([[1.5, 2.0, -0.5, 0.8]], dtype="float32") prob = model.predict(sample, verbose=0)[0][0] print(f"\nPrediction probability: {prob:.4f} โ Class: {int(prob > 0.5)}")
Keep exploring and happy coding! ๐ป