Coursera机器学习编程作业Python实现(Andrew Ng)—— 1.1 Linear regression with one variable...

1.1 Linear regression with one variable

import numpy as np
import matplotlib.pyplot as plt
data1 = np.loadtxt('ex1data1.txt', delimiter=',')

Plotting the Data

plt.scatter(data1[:,0], data1[:,1], c='red', marker='x')
plt.xlabel('Population of City in 10,000s')
plt.ylabel('Profit in $10,000s')
plt.show()

数据预处理及参数初始化

x0 = np.ones((len(data1),1))
x1 = data1[:,0]
x1 = x1.reshape([len(x1), 1])
X = np.hstack((x0, x1))
y = data1[:,1] y = y.reshape([len(y), 1])
theta = np.zeros((2,1))
iterations = 1500 alpha = 0.01

定义假设函数

def h(X, theta):
    return np.dot(X, theta)

定义代价函数

def computeCost(X, theta, y):
    return 0.5 * np.mean(np.square(h(X, theta) - y))

定义梯度下降函数

def gradientDescent(X, theta, y, iterations, alpha):
    Cost = []
    Cost.append(computeCost(X, theta, y))
    for i in range(iterations):
        grad0 = np.mean(h(X, theta) - y)
        grad1 = np.mean((h(X, theta) - y) * (X[:,1].reshape([len(X), 1])))
        theta[0] = theta[0] - alpha * grad0
        theta[1] = theta[1] - alpha * grad1
        Cost.append(computeCost(X, theta, y))
    return theta, Cost

运行并观察结果

theta_result, Cost_result = gradientDescent(X, theta, y, iterations, alpha)
theta_result
array([[-3.63029144],
       [ 1.16636235]])
predict1 = np.dot(np.array([1, 3.5]), theta_result)
predict1
array([0.45197679])
x_predict = [X[:,1].min(), X[:,1].max()]
y_predict = [theta_result[0]+theta_result[1]*(X[:,1].min()), theta_result[0]+theta_result[1]*(X[:,1].max())]
plt.plot(x_predict, y_predict, c='blue', label='predict')
plt.scatter(data1[:,0], data1[:,1], c='red', marker='x', label='train_data')
plt.xlabel('Population of City in 10,000s')
plt.ylabel('Profit in $10,000s')
plt.legend()
plt.show()
plt.plot(Cost_result)
plt.xlabel('Iterations')
plt.ylabel('Cost')
plt.show()

转载于:https://www.cnblogs.com/shouzhenghouchuqi/p/10585924.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Through exposure to the news and social media, you are probably aware of the fact that machine learning has become one of the most exciting technologies of our time and age. Large companies, such as Google, Facebook, Apple, Amazon, and IBM, heavily invest in machine learning research and applications for good reasons. While it may seem that machine learning has become the buzzword of our time and age, it is certainly not a fad. This exciting field opens the way to new possibilities and has become indispensable to our daily lives. This is evident in talking to the voice assistant on our smartphones, recommending the right product for our customers, preventing credit card fraud, filtering out spam from our email inboxes, detecting and diagnosing medical diseases, the list goes on and on. If you want to become a machine learning practitioner, a better problem solver, or maybe even consider a career in machine learning research, then this book is for you. However, for a novice, the theoretical concepts behind machine learning can be quite overwhelming. Many practical books have been published in recent years that will help you get started in machine learning by implementing powerful learning algorithms. Getting exposed to practical code examples and working through example applications of machine learning are a great way to dive into this field. Concrete examples help illustrate the broader concepts by putting the learned material directly into action. However, remember that with great power comes great responsibility! In addition to offering a hands-on experience with machine learning using the Python programming languages and Python-based machine learning libraries, this book introduces the mathematical concepts behind machine learning algorithms, which is essential for using machine learning successfully. Thus, this book is different from a purely practical book; it is a book that discusses the necessary details regarding machine learning concepts and offers intuitive yet informative explanations of how machine learning algorithms work, how to use them, and most importantly, how to avoid the most common pitfalls. Currently, if you type "machine learning" as a search term in Google Scholar, it returns an overwhelmingly large number of publications—1,800,000. Of course, we cannot discuss the nitty-gritty of all the different algorithms and applications that have emerged in the last 60 years. However, in this book, we will embark on an exciting journey that covers all the essential topics and concepts to give you a head start in this field. If you find that your thirst for knowledge is not satisfied, this book references many useful resources that can be used to follow up on the essential breakthroughs in this field. If you have already studied machine learning theory in detail, this book will show you how to put your knowledge into practice. If you have used machine learning techniques before and want to gain more insight into how machine learning actually works, this book is for you. Don't worry if you are completely new to the machine learning field; you have even more reason to be excited. Here is a promise that machine learning will change the way you think about the problems you want to solve and will show you how to tackle them by unlocking the power of data. Before we dive deeper into the machine learning field, let's answer your most important question, "Why Python?" The answer is simple: it is powerful yet very accessible. Python has become the most popular programming language for data science because it allows us to forget about the tedious parts of programming and offers us an environment where we can quickly jot down our ideas and put concepts directly into action. We, the authors, can truly say that the study of machine learning has made us better scientists, thinkers, and problem solvers. In this book, we want to share this knowledge with you. Knowledge is gained by learning. The key is our enthusiasm, and the real mastery of skills can only be achieved by practice. The road ahead may be bumpy on occasions and some topics may be more challenging than others, but we hope that you will embrace this opportunity and focus on the reward. Remember that we are on this journey together, and throughout this book, we will add many powerful techniques to your arsenal that will help us solve even the toughest problems the data-driven way.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值