python之机械学习题1求房间数,面积,价格得关系图

用Spyder求代价函数

// An highlighted block
# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['SimHei']

data = np.loadtxt('C:/Users/Administrator.114-20151027FLP/Desktop/data2.txt',delimiter=',')
x,y = data[:,:-1],data[:,-1]
def h(x,theta):
    h=np.dot(x,theta.T)
    return h

#求代价函数
def computeCost(X,y,theta):
    temp = np.power((X*theta.T-y),2)
    return np.sum(temp)/(2*X.shape[0])

def gradientDescent(X,y,theta,alpha,iters):
    #、初始化临时矩阵temp
    temp = np.matrix(np.zeros(theta.shape))
    #初始化代价函数举证,维数为迭代次数
    cost = np.zeros(iters)
    m = X.shape[0]
    for i in range(iters):
        #根据theta个数循环跟新theta
        temp = theta - (alpha/m) * (X*theta.T-y).T * X
        #得到跟新后的theta
        theta = temp
        #计算代价
        cost[i]=computeCost(X,y,theta)
    return theta,cost

#初始化一些附加变量 --学习速率α和要执行的迭代次数
#学习率
alpha=0.01
#迭代次数
iters=2000
theta=np.matrix(np.array([0,0]))

def preProcess(x,y):
    #标准化特征缩放
#  x-=np.mean(X,axis=0)
# x/=np.std(x,axis=0,dd0f=1)
    #均值归一化
    x=(x-np.average(x))/(np.max(x)-np.min(x))
    x=np.c_[np.ones(len(x)),x]
    y=np.c_[y]
    return x,y

x2,y2=preProcess(x,y)
x2=np.matrix(x2)
y2=np.matrix(y2)
theta2 = np.matrix(np.array([0,0,0]))

#梯度下降法
g2,cost2 = gradientDescent(x2,y2,theta2,alpha,iters)
h = h(x2,g2)
#get the cost (error) of the model
computeCost(x2,y2,g2)
#绘出损失图像

fig,ax = plt.subplots(figsize=(12,8))
plt.plot(np.arange(iters),cost2,'r')
#fig = plt.figure()
fig,ax = plt.subplots(figsize=(12,8))
axes=plt.subplot(111,projection='3d')
axes.scatter(x2[:,1],x2[:,2],y2)            
axes.scatter(x2[:,1],x2[:,2],h,c='r')
axes.set(xlabel='面积',ylabel='房间数',zlabel='价格')

在这里插入图片描述

我的data数据是放在Desktop上的
所以地址就是如上

data.txt数据为:

// An data.text
2104,3,399900
1600,3,329900
2400,3,369000
1416,2,232000
3000,4,539900
1985,4,299900
1534,3,314900
1427,3,198999
1380,3,212000
1494,3,242500
1940,4,239999
2000,3,347000
1890,3,329999
4478,5,699900
1268,3,259900
2300,4,449900
1320,2,299900
1236,3,199900
2609,4,499998
3031,4,599000
1767,3,252900
1888,2,255000
1604,3,242900
1962,4,259900
3890,3,573900
1100,3,249900
1458,3,464500
2526,3,469000
2200,3,475000
2637,3,299900
1839,2,349900
1000,1,169900
2040,4,314900
3137,3,579900
1811,4,285900
1437,3,249900
1239,3,229900
2132,4,345000
4215,4,549000
2162,4,287000
1664,2,368500
2238,3,329900
2567,4,314000
1200,3,299000
852,2,179900
1852,4,299900
1203,3,239500

持续跟新
ヾ(◍°∇°◍)ノ゙
jiayou

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值