Refactored Import Statements
The provided import statements have several issues:
- Duplicates: Some libraries are imported multiple times (e.g.,
torch, re, numpy as np, os).
- Unused imports: Some libraries are imported but not used in the provided snippet (e.g.,
requests, tarfile, joblib, matplotlib.pyplot as plt).
- Unordered imports: Import statements are not grouped by category (standard library, third-party libraries, local modules).
Here's the refactored version:
# Standard library imports
import os
import re
from collections import Counter
# Third-party library imports
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, Dataset, TensorDataset
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
import shap
from lime import lime_text
# No local module imports (since there are no local modules in this snippet)
Explanation of Changes
- Removed duplicate imports.
- Removed unused imports (if you're using them elsewhere in your code, add them back).
- Grouped imports by category:
- Standard library (
os, re, collections).
- Third-party libraries (
numpy, pandas, torch, sklearn, shap, lime).
- No local module imports are present in this snippet.
Best Practices
- Keep imports at the top of the file, after the shebang line (if present) and any module docstrings.
- Use the following order:
- Standard library imports.
- Related third-party imports (e.g., all
torch imports together).
- Local application imports (not applicable here).
- Avoid wildcard imports (
from module import *); instead, import specific symbols or use the module name (module.symbol).
- Use
isort or a similar tool to automatically sort and format your imports.
Additional Advice
Consider using a linter (e.g., flake8, pylint) and a code formatter (e.g., black) to maintain consistent coding style and catch potential issues early.
To take it a step further, you can configure your IDE or text editor to:
- Automatically sort imports on save (using
isort).
- Format code according to a style guide (e.g., PEP 8 with
black).
Example .isort.cfg for automatic import sorting:
[settings]
profile = black
known_first_party = your_project_name
Replace your_project_name with the actual name of your project.
By following these guidelines, you'll keep your imports organized, readable, and maintainable. Happy coding!
Here's a simple python script using the above import statements.
# Standard library imports
import os
import re
from collections import Counter
# Third-party library imports
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, Dataset, TensorDataset
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
import shap
from lime import lime_text
class TextDataset(Dataset):
def __init__(self, texts, labels, vectorizer):
self.texts = texts
self.labels = labels
self.vectorizer = vectorizer
def __len__(self):
return len(self.texts)
def __getitem__(self, idx):
text = self.texts[idx]
label = self.labels[idx]
encoding = self.vectorizer.transform([text])
encoding = torch.tensor(encoding.toarray()[0], dtype=torch.float32)
return {
'text': encoding,
'label': torch.tensor(label, dtype=torch.long)
}
class SimpleNN(nn.Module):
def __init__(self, input_dim):
super(SimpleNN, self).__init__()
self.fc1 = nn.Linear(input_dim, 128) # input layer (input_dim) -> hidden layer (128)
self.relu = nn.ReLU()
self.dropout = nn.Dropout(p=0.2)
self.fc2 = nn.Linear(128, 2) # hidden layer (128) -> output layer (2)
def forward(self, x):
x = self.relu(self.fc1(x)) # activation function for hidden layer
x = self.dropout(x)
x = self.fc2(x)
return x
def train(model, device, loader, criterion, optimizer):
model.train()
total_loss = 0
for batch in loader:
inputs = batch['text'].to(device)
labels = batch['label'].to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
total_loss += loss.item()
return total_loss / len(loader)
def evaluate(model, device, loader, criterion):
model.eval()
total_loss = 0
correct = 0
with torch.no_grad():
for batch in loader:
inputs = batch['text'].to(device)
labels = batch['label'].to(device)
outputs = model(inputs)
loss = criterion(outputs, labels)
total_loss += loss.item()
_, predicted = torch.max(outputs.scores, dim=1)
correct += (predicted == labels).sum().item()
accuracy = correct / len(loader.dataset)
return total_loss / len(loader), accuracy
def main():
# Sample dataset
data = {
'text': [
'This is a positive review',
'This is a negative review',
'Another positive one',
'And another negative review',
'Positive vibes only',
'Hate this product'
],
'label': [1, 0, 1, 0, 1, 0] # 1 = Positive, 0 = Negative
}
df = pd.DataFrame(data)
# Split data
train_texts, val_texts, train_labels, val_labels = train_test_split(df['text'], df['label'], test_size=0.2, random_state=42)
# Vectorize text data
vectorizer = TfidfVectorizer(max_features=5000)
vectorizer.fit(train_texts)
# Prepare datasets and data loaders
train_dataset = TextDataset(train_texts, train_labels, vectorizer)
val_dataset = TextDataset(val_texts, val_labels, vectorizer)
train_loader = DataLoader(train_dataset, batch_size=2, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=2, shuffle=False)
# Initialize model, device, criterion, optimizer
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = SimpleNN(input_dim=5000).to(device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
# Train
for epoch in range(5):
train_loss = train(model, device, train_loader, criterion, optimizer)
val_loss, val_accuracy = evaluate(model, device, val_loader, criterion)
print(f'Epoch {epoch+1}, Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Acc: {val_accuracy:.4f}')
if __name__ == '__main__':
main()
This code trains a simple neural network on a toy text classification dataset. It covers:
- Data preparation (splitting, vectorizing).
- Custom
Dataset class for text data.
- A basic neural network model (
SimpleNN).
- Training and evaluation loops.
Feel free to expand upon this foundation!
Hope this helps! Let me know if you need further assistance.