#๐Ÿ”’ Uni classwork example error

73 messages ยท Page 1 of 1 (latest)

gleaming cobaltBOT
#

@mortal quest

Python help channel opened

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.

mortal quest
#

Oops

#

I added a PDF file and it deleted everything I wrote evaporatedisappear

#

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

twilit fulcrum
#

this is quite explcit, you never defined df

#

you need to define a variable before using it

mortal quest
twilit fulcrum
#

well, we can't help you without context neither

#

this dataframe surely comes from somwhere

mortal quest
#

I can send the PDF file here if it's allowed

twilit fulcrum
#

probably the same thing used to compute target_names ?

potent mountain
#

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()

twilit fulcrum
#

but I am pretty sure it is defined somewhere

#

or maybe there is another dataframe with a different name, but you should use it

twilit fulcrum
twilit fulcrum
mortal quest
#

This is the rest of the PDF

potent mountain
#

please share full code

mortal quest
#
# 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()
twilit fulcrum
#

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 ?

bleak sigil
#

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"

mortal quest
#

The df part doesn't get reused anwhere or at least it doesn't tell you where to use it

bleak sigil
#

Let's back up for a sec: "df" is wrong because there's no point in which you define a df variable.

mortal quest
#

Original code works just as fine, no idea why they want to replace/fix it

bleak sigil
#

Add "df = data.frame" before that line

mortal quest
#

Unless I did it wrong

bleak sigil
#

Ther'es three levels of problems here:

#

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.

twilit fulcrum
#

so why not doing

df= load_breast_cancer(as_frame=True)
and keep
data=load_breast_cancer()

mortal quest
bleak sigil
bleak sigil
mortal quest
#

Unless the data/output is incorrect

potent mountain
gleaming cobaltBOT
bleak sigil
#

but I don't think it affects your output

potent mountain
gleaming cobaltBOT
mortal quest
bleak sigil
bleak sigil
mortal quest
gleaming cobaltBOT
bleak sigil
mortal quest
twilit fulcrum
#

!rule 8

gleaming cobaltBOT
#

8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.

gleaming cobaltBOT
#
Python help channel closed using Discord native close action

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.