我的问题是关于值错误:形状(97,)和(2,1)未对齐:97(dim 0)!= 2(dim 0)

时间:2018-11-06 22:38:56

标签: python

这是我的代码。我只想绘制线性回归图。运行时显示此类型的错误值错误:形状(97,)和(2,1)不对齐:97(dim 0)!= 2(dim 0)。每次我运行它时,我都无法处理。有人请更正我的代码吗?

from __future__ import division
#import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 
#import math

#read data into array
data = np.genfromtxt('ex1data1.txt',delimiter=',')
x=data[:,0]
y=data[:,1]

m = y.size
alpha = .01
yp = None
savePng=False
iterations=1500
#a=ones(m,2)
theta=np.zeros((2,1))

def hypo(x,theta): 
h=x * theta
return h

标题##

def cost(theta, x, y):
"""Computes the cost of linear regression
theta = parameter for linear regression
x and y are the data points
This is done to monitor the cost of gradient descent"""
m = len(x)
J = 1/(2*m) * sum(np.power(x.dot(theta).flatten()- y),2)
return J

def gradientDesc(x, y, theta, alpha, iterations):
""""Gradient Descent implementation of 
linear regression with one variable"""
m = y.size
J = []
for numbers in range(iterations):
a = theta[0][0] - alpha*(1/m)*sum((x.dot(theta).flatten() - y)*x[:,0])
b = theta[1][0] - alpha*(1/m)*sum((x.dot(theta).flatten() - y)*x[:,1])
theta[0][0],theta[1][0]=a,b
print (theta[0][0])
print (theta[1][0])
J.append(cost(x,y,theta))
print ('Cost: ' + str(J[-1]))
return theta

#scatterplot of data with option to save figure.

def scatterPlot(x,y,yp,savePng):
plt.xlabel('Population of City in 10,000s')
plt.ylabel('Profit in $10,000s')
plt.scatter(x, y, marker='x')
if yp != None:
plt.plot(x,yp)

if (savePng == False):
plt.show()

hypo(x, theta) 
cost(theta, x, y)
gradientDesc(x, y, theta, alpha, iterations)      
scatterPlot(x,y,yp,savePng)

0 个答案:

没有答案