Я получаю ошибку ValueError относительно входных массивов и их размеров. Я пытаюсь создать модель случайной лесной регрессии для прогнозирования цен, используя как числовые, так и категориальные функции. У меня по-прежнему возникает ошибка при добавлении строки кода для изменения формы.
Вот код модели:
cat_features = ['Manufacturer', 'Fuel type','Model']
num_features = ['Engine size', 'Year of manufacture', 'Mileage']
x_numerical = df[num_features]
x_cat = df[cat_features]
y = df['Price']
#scaling of the numerical data - using same scaler as previous for consistency
scale = StandardScaler()
scale.fit(x_numerical)
x_numerical_scaled = scale.transform(x_numerical)
#trasforming categorical data into numerical - one hot encoder as applying to multiple labels
from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder()
encoder.fit(x_cat)
#applying tranformation
x_cat_encoder = encoder.transform(x_cat)
#reshaping the data
#x_cat_endoder = x_cat_label.reshape(-1, 1)
#combining both categorical and numerical features
x = np.concatenate((x_numerical_scaled, x_cat_encoder), axis = 1)
#now splitting the data
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, random_state = 42)
forest = RandomForestRegressor()
forest.fit(x_train, y_train)
pred_forest = forest.predict(x_test)
#evalutating the model
evaluate_model(y_test, pred_forest)
#creating the visualisation
plt.scatter(y_test, pred_forest)
plt.plot([0,160000], [0,160000], 'k-')
plt.ylabel('Actual price (GDP)')
plt.xlabel('Predicted Price (GDP)')
plt.suptitle('Actual Price Vs Predicted Price')
plt.title('Random Forest Regressor')
plt.show()
И вот какую ошибку я получаю:
ValueError Traceback (most recent call last)
Cell In[35], line 25
19 x_cat_encoder = encoder.transform(x_cat)
21 #reshaping the data
22 #x_cat_label = x_cat_label.reshape(-1, 1)
23
24 #combining both categorical and numerical features
---> 25 x = np.concatenate((x_numerical_scaled, x_cat_encoder), axis = 1)
27 #now splitting the data
28 x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, random_state = 42)
ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 0 dimension(s)
Подробнее здесь: https://stackoverflow.com/questions/795 ... categorica
Проблема с входным массивом в модели случайного леса как с числовыми, так и с категориальными признаками ⇐ Python
Программы на Python
1773003692
Anonymous
Я получаю ошибку ValueError относительно входных массивов и их размеров. Я пытаюсь создать модель случайной лесной регрессии для прогнозирования цен, используя как числовые, так и категориальные функции. У меня по-прежнему возникает ошибка при добавлении строки кода для изменения формы.
Вот код модели:
cat_features = ['Manufacturer', 'Fuel type','Model']
num_features = ['Engine size', 'Year of manufacture', 'Mileage']
x_numerical = df[num_features]
x_cat = df[cat_features]
y = df['Price']
#scaling of the numerical data - using same scaler as previous for consistency
scale = StandardScaler()
scale.fit(x_numerical)
x_numerical_scaled = scale.transform(x_numerical)
#trasforming categorical data into numerical - one hot encoder as applying to multiple labels
from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder()
encoder.fit(x_cat)
#applying tranformation
x_cat_encoder = encoder.transform(x_cat)
#reshaping the data
#x_cat_endoder = x_cat_label.reshape(-1, 1)
#combining both categorical and numerical features
x = np.concatenate((x_numerical_scaled, x_cat_encoder), axis = 1)
#now splitting the data
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, random_state = 42)
forest = RandomForestRegressor()
forest.fit(x_train, y_train)
pred_forest = forest.predict(x_test)
#evalutating the model
evaluate_model(y_test, pred_forest)
#creating the visualisation
plt.scatter(y_test, pred_forest)
plt.plot([0,160000], [0,160000], 'k-')
plt.ylabel('Actual price (GDP)')
plt.xlabel('Predicted Price (GDP)')
plt.suptitle('Actual Price Vs Predicted Price')
plt.title('Random Forest Regressor')
plt.show()
И вот какую ошибку я получаю:
ValueError Traceback (most recent call last)
Cell In[35], line 25
19 x_cat_encoder = encoder.transform(x_cat)
21 #reshaping the data
22 #x_cat_label = x_cat_label.reshape(-1, 1)
23
24 #combining both categorical and numerical features
---> 25 x = np.concatenate((x_numerical_scaled, x_cat_encoder), axis = 1)
27 #now splitting the data
28 x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, random_state = 42)
ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 0 dimension(s)
Подробнее здесь: [url]https://stackoverflow.com/questions/79525975/issue-with-input-array-on-random-forest-model-with-both-numerical-and-categorica[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия