numpy - 'tuple' object has no attribute 'reshape'
问题描述
I used a dataset "ex1data1.txt", but when I am running it to convert, it is showing the following error:
AttributeError Traceback (most recent call last)
<ipython-input-52-7c523f7ba9e1> in <module>()
1 # Converting loaded dataset into numpy array
2
----> 3 X = np.concatenate((np.ones(len(population)).reshape(len(population), 1), population.reshape(len(population),1)), axis=1)
4
5
AttributeError: 'tuple' object has no attribute 'reshape'
The code is given below:
import csv
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
import pandas as pd
import numpy as np
# Loading Dataset
with open('ex1data1.txt') as csvfile:
population, profit = zip(*[(float(row['Population']), float(row['Profit'])) for row in csv.DictReader(csvfile)])
# Creating DataFrame
df = pd.DataFrame()
df['Population'] = population
df['Profit'] = profit
# Plotting using Seaborn
sns.lmplot(x="Population", y="Profit", data=df, fit_reg=False, scatter_kws={'s':45})
# Converting loaded dataset into numpy array
X = np.concatenate((np.ones(len(population)).reshape(len(population), 1), population.reshape(len(population),1)), axis=1)
y = np.array(profit).reshape(len(profit), 1)
# Creating theta matrix , theta = [[0], [0]]
theta = np.zeros((2, 1))
# Learning rate
alpha = 0.1
# Iterations to be taken
iterations = 1500
# Updated theta and calculated cost
theta, cost = gradientDescent(X, y, theta, alpha, iterations)
I don't know how to solve this reshape problem. Can anyone tell how can I solve this problem?
解决方案
根据您的定义,population
是一个元组。我建议两个选项,第一个是将其转换为数组,即
population = np.asarray(population)
或者,您可以使用 DataFrame 列.values
属性,它本质上是一个 numpy 数组:
X = np.concatenate((np.ones(len(population)).reshape(len(population), 1), df['Population'].values.reshape(len(population),1)), axis=1)
推荐阅读
- css - 什么是非 CSS 展示提示?
- google-cloud-platform - 识别比较句
- javascript - 无法通过不完整的名称获取频道 twillio programmabale 聊天节点 js
- flutter - ScopedModel - 如何传递多个模型
- python - 突然无法在 Google Colab 中更改 Python 版本的运行时
- java - 如何使用 redisson 客户端获取缓存值
- ruby-on-rails - 使用inf Rspec测试控制器时出现UrlGenerationError
- docker - Traefik - 角度应用程序的后端代理
- grails - 如何使用 .gsp 文件在 grails 应用程序中以可编辑模式隐藏字段?
- javascript - 在 mongoose 中创建带有 { strict: false } 的文档