The error you're encountering:
TypeError: cannot concatenate object of type '<class 'type'>'; only Series and DataFrame objs are valid
suggests that one of the objects you're trying to concatenate with pd.concat is a type (like pd.DataFrame) rather than an actual DataFrame instance. This typically happens if score_data is not properly initialized before the loop or if it has been unintentionally set to a type instead of a DataFrame.
Common Cause
You likely haven't initialized score_data before the loop, or you initialized it incorrectly. For example, doing something like:
score_data = pd.DataFrame
This line sets score_data to the DataFrame class itself, not an instance of a DataFrame. When you later try to concatenate score_data (which is a type) with temp_score_data (a DataFrame), pandas raises the TypeError.
Solution
-
Initialize score_data as an Empty DataFrame Before the Loop
Before entering the loop, initialize score_data as an empty DataFrame instance. This ensures that you're concatenating DataFrame objects.
import pandas as pd
from sklearn import tree
from sklearn.model_selection import cross_val_score
# Initialize an empty DataFrame
score_data = pd.DataFrame()
for max_depth in range(1, 100):
clf = tree.DecisionTreeClassifier(criterion='entropy', max_depth=max_depth, random_state=rs)
clf.fit(X_train, y_train)
train_score = clf.score(X_train, y_train)
test_score = clf.score(X_test, y_test)
mean_cross_val_score = cross_val_score(clf, X_train, y_train, cv=5).mean()
temp_score_data = pd.DataFrame({
'max_depth': [max_depth],
'train_score': [train_score],
'test_score': [test_score],
'cross_val_score': [mean_cross_val_score]
})
# Concatenate the new DataFrame with the cumulative score_data
score_data = pd.concat([score_data, temp_score_data], ignore_index=True)
Key Points:
- Initialization: Use
score_data = pd.DataFrame() to create an empty DataFrame instance.
- Concatenation: Use
ignore_index=True in pd.concat to reset the index after each concatenation, avoiding duplicate indices.
-
Alternative Approach: Collect Data in a List and Create DataFrame Once
Concatenating DataFrames inside a loop can be inefficient, especially for large loops. A more efficient approach is to collect all the temporary data in a list and concatenate them once after the loop.
import pandas as pd
from sklearn import tree
from sklearn.model_selection import cross_val_score
# Initialize an empty list to collect score data
score_list = []
for max_depth in range(1, 100):
clf = tree.DecisionTreeClassifier(criterion='entropy', max_depth=max_depth, random_state=rs)
clf.fit(X_train, y_train)
train_score = clf.score(X_train, y_train)
test_score = clf.score(X_test, y_test)
mean_cross_val_score = cross_val_score(clf, X_train, y_train, cv=5).mean()
temp_score_data = {
'max_depth': max_depth,
'train_score': train_score,
'test_score': test_score,
'cross_val_score': mean_cross_val_score
}
# Append the dictionary to the list
score_list.append(temp_score_data)
# Create a DataFrame once after the loop
score_data = pd.DataFrame(score_list)
Benefits:
- Performance: Faster execution since it avoids repeated concatenations.
- Simplicity: Easier to read and maintain.
Final Recommendations
- Ensure Proper Initialization: Always initialize accumulators like
score_data correctly before using them in operations.
- Use Efficient Data Structures: When performing operations inside loops, consider the most efficient way to collect and process your data.
- Debugging Tips:
- Print Types: Use
print(type(score_data)) before the pd.concat line to verify that score_data is indeed a DataFrame.
- Check Initial Assignments: Ensure that nowhere in your code you assign
score_data to a type like pd.DataFrame without parentheses.
By following these steps, you should be able to resolve the TypeError and successfully concatenate your DataFrames.
Example Correction
Here's the corrected version of your code with proper initialization and the efficient list approach:
import pandas as pd
from sklearn import tree
from sklearn.model_selection import cross_val_score
# Using the list approach for efficiency
score_list = []
for max_depth in range(1, 100):
clf = tree.DecisionTreeClassifier(criterion='entropy', max_depth=max_depth, random_state=rs)
clf.fit(X_train, y_train)
train_score = clf.score(X_train, y_train)
test_score = clf.score(X_test, y_test)
mean_cross_val_score = cross_val_score(clf, X_train, y_train, cv=5).mean()
temp_score_data = {
'max_depth': max_depth,
'train_score': train_score,
'test_score': test_score,
'cross_val_score': mean_cross_val_score
}
score_list.append(temp_score_data)
# Create the DataFrame once
score_data = pd.DataFrame(score_list)
This should eliminate the TypeError and efficiently build your score_data DataFrame.