I have the following pandas code that I need help with as I'm getting an error. Could anyone review and help out? Thanks.
This is the whole code:
# Step 1: Data Preparation (ETL)
import pandas as pd
# Load the original CSV file
df = pd.read_csv('outdoors.csv')
# Perform data transformation
# Assuming that the "Weather" column contains strings like "Sunny", "Cloudy", and "Rainy"
# We will convert them to numerical values using dummy encoding.
df = pd.get_dummies(df, columns=['Weather'], drop_first=True)
# Map 'Yes' to 1 and 'No' to 0 in the "Outdoors" column
df['Outdoors'] = df['Outdoors'].map({'Yes': 1, 'No': 0})
# Save the corrected data to a new CSV file
df.to_csv('outdoors-corrected.csv', index=False)
# Step 2: Decision Tree Creation
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.tree import export_graphviz
import graphviz
# Load the corrected CSV file
df = pd.read_csv('outdoors-corrected.csv')
# Separate features (X) and target (y)
X = df.drop('Outdoors', axis=1)
y = df['Outdoors']
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Create a decision tree model
dt_model = DecisionTreeClassifier()
# Fit the model on the training data
dt_model.fit(X_train, y_train)
# Make predictions on the test data
y_pred = dt_model.predict(X_test)
# Calculate the accuracy of the model
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy of Decision Tree: {accuracy:.2f}")
# Visualize the decision tree and save it as "outdoors.jpg"
dot_data = export_graphviz(dt_model, feature_names=X.columns, class_names=['No', 'Yes'], filled=True, rounded=True, special_characters=True)
graph = graphviz.Source(dot_data)
graph.format = 'jpg'
graph.render('outdoors', view=False)