#๐ Uni classwork example error
73 messages ยท Page 1 of 1 (latest)
@mortal quest
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
Oops
I added a PDF file and it deleted everything I wrote 
Long story short: I'm doing the classwork last minute cause I need to upload it alongside my assignment and didn't do them in class (lazy ass) so I don't know what the fix for this is
The code says
# Visualizing the classes distribution
plt.figure(figsize=(6, 4))
plt.bar(target_names, np.bincount(y))
plt.xlabel('Class')
plt.ylabel('Count')
plt.title('Class Distribution')
plt.show()
And I need to replace the "plt.bar(target_names, np.bincount(y))" part with the blue text that says "df['diagnosis'].value_counts().plot.bar()"
Shows this when I do that then run
@bleak sigil here's the thread
this is quite explcit, you never defined df
you need to define a variable before using it
I'm following what the PDF file says, and it just vaguely tells you to replace something with no other context
well, we can't help you without context neither
this dataframe surely comes from somwhere
I can send the PDF file here if it's allowed
probably the same thing used to compute target_names ?
Visualizing the classes distribution
plt.figure(figsize=(6, 4))
df["diagnosis"].value_counts.plot.bar()
plt.xlabel('Class')
plt.ylabel('Count')
plt.title('Class Distribution')
plt.show()
?
send a screenshot
but I am pretty sure it is defined somewhere
or maybe there is another dataframe with a different name, but you should use it
try this
Might be that
did you read the error OP sent ?
also, this is classwork, so don't just give people answers
This is the rest of the PDF
please share full code
# Importing the libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report,confusion_matrix, roc_curve, roc_auc_score
# Use the dataset from ther sklearn library
from sklearn.datasets import load_breast_cancer
# Loading the breast cancer dataset
data = load_breast_cancer()
X = data.data
y = data.target
feature_names = data.feature_names
target_names = data.target_names
# Visualizing the classes distribution
plt.figure(figsize=(6, 4))
bar_plt = df['diagnosis'].value_counts().plot.bar()
plt.xlabel('Class')
plt.ylabel('Count')
plt.title('Class Distribution')
plt.show()
# Splitting the dataset 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)
# Feature scaling
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# Fitting logistic regression to the training set
classifier = LogisticRegression(random_state=0)
classifier.fit(X_train, y_train)
# Predicting the test set results
y_pred = classifier.predict(X_test)
# Evaluating the model
print("Accuracy:", accuracy_score(y_test, y_pred))
print("\nClassification Report:\n", classification_report(y_test, y_pred))
print("\nConfusion Matrix:\n", confusion_matrix(y_test, y_pred))
# Evaluating the model
print("Accuracy:", accuracy_score(y_test, y_pred))
print("\nClassification Report:\n", classification_report(y_test, y_pred))
print("\nConfusion Matrix:\n", confusion_matrix(y_test, y_pred))
# Plotting the confusion matrix
conf_matrix = confusion_matrix(y_test, y_pred)
plt.imshow(conf_matrix, cmap='Blues', interpolation='nearest')
plt.title('Confusion Matrix')
plt.colorbar()
tick_marks = np.arange(2)
plt.xticks(tick_marks, target_names)
plt.yticks(tick_marks, target_names)
plt.xlabel('Predicted')
plt.ylabel('Actual')
plt.show()
# Plotting the ROC curve
y_pred_proba = classifier.predict_proba(X_test)[:, 1]
fpr, tpr, thresholds = roc_curve(y_test, y_pred_proba)
plt.plot(fpr, tpr, label='ROC Curve')
plt.plot([0, 1], [0, 1], 'k--')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver Operating Characteristic (ROC) Curve')
plt.legend(loc='lower right')
plt.show()
# Plotting feature importance
coefficients = classifier.coef_[0]
sorted_indices = np.argsort(coefficients)
plt.barh(range(len(coefficients)), coefficients[sorted_indices],
tick_label=feature_names[sorted_indices])
plt.title('Feature Importance')
plt.xlabel('Coefficients')
plt.ylabel('Feature')
plt.show()
you have a dataset called data
it is probably what you are looking for
mmm, not exaclty
Maybe your teacher want you to create a pandas dataframe from the X and Y ?
The original bug, I think, was that they used "np.bincount" which is for int valued data: #ot0-lord-invers-spirit-animal message
And teacher said "use value_counts"
Yeah, to replace the "plt.bar(target_names, np.bincount(y))" part with the blue text that says "df['diagnosis'].value_counts().plot.bar()"
The df part doesn't get reused anwhere or at least it doesn't tell you where to use it
Let's back up for a sec: "df" is wrong because there's no point in which you define a df variable.
Original code works just as fine, no idea why they want to replace/fix it
Add "df = data.frame" before that line
Doesn't work
Unless I did it wrong
Ther'es three levels of problems here:
You can convert the data to a dataframe type using data = load_breast_cancer(as_frame=True) https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_breast_cancer.html
But I don't know the full assignment and whether you're changing stuff that you don't need to.
The second question is: what is the reason to make this change? Why value_counts vs bincount?
I assume it has to do with the limitations of bincount, which mean that your plot is incorrect.
And finally, you were plotting target_names, not "diagnosis", so I don't understand that.
so why not doing
df= load_breast_cancer(as_frame=True)
and keep
data=load_breast_cancer()
It might be that, the original code is fine but for some reason said to change it
How do you know original code is fine tho?
I ran it and it works
But is it correct?
Unless the data/output is incorrect
ye run this cide
Please react with โ
to upload your file(s) to our paste bin, which is more accessible for some users.
I don't see any NaN or negative values in this data, so I think this is more a "it's safer to use value_counts"
but I don't think it affects your output
you run this code
Please react with โ
to upload your file(s) to our paste bin, which is more accessible for some users.
Should I keep the original code or try and change it?
How would that help them? You're inserting a column that didn't exist, etc.
Up to you, you could use the data = load_breast_cancer(as_frame=True) version
It's not graded as it's just classwork so it might be fine

try this code ok
Please react with โ
to upload your file(s) to our paste bin, which is more accessible for some users.
You could just ask them to explain
It's 1:45 AM so maybe not 
stop doing other people's homework, that's how they learn
!rule 8
8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.
ok
This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.