DEV Community

Cover image for 5 Python Snippets for Machine Learning You Need to Bookmark
Neurolov
Neurolov

Posted on

5 Python Snippets for Machine Learning You Need to Bookmark

Here are 5 must-have Python snippets for your AI projects:

1. Loading a Dataset:

Python
Copy code

import pandas as pd  
data = pd.read_csv('dataset.CSV')  
print(data.head())  

Enter fullscreen mode Exit fullscreen mode

2. Training a Model:

Python
Copy code

from sklearn.ensemble import RandomForestClassifier  
model = RandomForestClassifier()  
model.fit(X_train, y_train)

Enter fullscreen mode Exit fullscreen mode

3. Evaluating Accuracy:

Python
Copy code

from sklearn.metrics import accuracy_score  
accuracy = accuracy_score(y_test, model.predict(X_test))  
print(f'Accuracy: {accuracy}')

Enter fullscreen mode Exit fullscreen mode

4. Data Preprocessing:

Python
Copy code

from sklearn.preprocessing import StandardScaler  
scaler = StandardScaler()  
X_scaled = scaler.fit_transform(X)

Enter fullscreen mode Exit fullscreen mode

5. Visualization with Matplotlib:

Python
Copy code

import matplotlib.pyplot as plt  
plt.plot(data['column'])  
plt.show()  

Enter fullscreen mode Exit fullscreen mode

Which snippet do you use the most❓

Let us know‼️

Top comments (0)