wine_predictor / train_model.py
roseyshi's picture
Upload 7 files
3d5a2b6 verified
Raw
History Blame Contribute Delete
986 Bytes
import pickle
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import StandardScaler
# Load the wine dataset
wine = load_wine()
X, y = wine.data, wine.target
# Split the data
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# Scale features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Train the model
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train_scaled, y_train)
# Evaluate
accuracy = model.score(X_test_scaled, y_test)
print(f"Model accuracy: {accuracy:.2f}")
# Save both the model and scaler
with open('model.pkl', 'wb') as f:
pickle.dump(model, f)
with open('scaler.pkl', 'wb') as f:
pickle.dump(scaler, f)
print("Model and scaler saved successfully!")