House Price Prediction
from tensorflow.keras.datasets import boston_housing
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
# Load dataset
(x_train, y_train), (x_test, y_test) = boston_housing.load_data()
# Normalize data
mean, std = x_train.mean(axis=0), x_train.std(axis=0)
x_train = (x_train - mean) / std
x_test = (x_test - mean) / std
# Define model
model = Sequential([
Dense(64, activation='relu', input_shape=(x_train.shape[1],)),
Dense(64, activation='relu'),
Dense(1)
])
# Compile model
model.compile(optimizer='adam', loss='mse', metrics=['mae'])
# Train model
model.fit(x_train, y_train, epochs=50, batch_size=8, validation_data=(x_test, y_test))
# -------- Prediction Step --------
# Predict on test set
predictions = model.predict(x_test)
# Display first 5 predictions with actual values
for i in range(5):
print(f"Predicted Price: {predictions[i][0]:.2f}, Actual Price: {y_test[i]:.2f}")
Numbers prediction
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.utils import to_categorical
import numpy as np
# Load dataset
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# Normalize inputs
x_train, x_test = x_train / 255.0, x_test / 255.0
# One-hot encode outputs
y_train, y_test = to_categorical(y_train), to_categorical(y_test)
# Build the model
model = Sequential([
Flatten(input_shape=(28, 28)),
Dense(128, activation='relu'),
Dense(10, activation='softmax')
])
# Compile the model
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# Train the model
model.fit(x_train, y_train, epochs=5, validation_data=(x_test, y_test))
# Evaluate model
loss, accuracy = model.evaluate(x_test, y_test)
print(f"\nTest Accuracy: {accuracy:.4f}")
# ---------------------------
# Prediction on a sample image
# ---------------------------
# Take the first test image
sample_image = x_test[0].reshape(1, 28, 28) # reshape for prediction
pred_prob = model.predict(sample_image) # predicted probabilities
pred_class = np.argmax(pred_prob) # get class with highest probability
print(f"Predicted Label: {pred_class}")
print(f"Actual Label: {np.argmax(y_test[0])}")
Comments
Post a Comment