ios 机器学习_利用机器学习的力量构建正面新闻iOS应用程序

ios 机器学习

自然语言处理-iOS (Natural Language Processing — iOS)

Since the beginning of the coronavirus pandemic, the news has been overwhelmingly negative and somewhat depressing. You open Twitter or your favorite news application, and you’re left with loads and loads of information that can drain your energy.

自从冠状病毒大流行开始以来,这一消息已成为压倒性的消极消息,并令人感到沮丧。 打开Twitter或您喜欢的新闻应用程序,您将获得大量的信息,这些信息可能会消耗您的精力。

In a world saturated with information, more and more people are choosing to offer positive news, even if it’s still often confined to a specific section.For example, The British daily newspaper The Guardian offers “The Upside”, while Fox News, MSN, the HuffPost site, and Yahoo! all have “good news” pages.

在这个充满信息的世界中,即使新闻仍然经常局限于特定的部分,也有越来越多的人选择提供正面新闻。例如,英国日报《卫报》提供了“ The Upside ”,而MSN的Fox News, HuffPost网站和Yahoo! 全部都有“好消息”页面。

Image for post
red) and “positive news” ( 美国 “好消息”( blue) in the 红色 )和“正面新闻”( USA 蓝色 )

The most surprising lesson of this crisis is probably the need for people to access ‘good’ news. Google trends data shows a spike of interesting queries (Figure 1) such as good news or positive news during the months of March and April.

这场危机中最令人惊讶的教训可能是人们需要获得“好消息”。 Google趋势数据显示了三月和四月期间有趣的查询(图1)激增,例如good newspositive news

The data shows that this is also the case in multiple regions (Europe, India…).

数据表明,在多个地区(欧洲,印度...)也是如此。

Image for post
red) and “positive news” ( 红色 )和“正面新闻”( blue) 蓝色 ) Worldwide 全球

After seeing this, I decided that I might be able to choose what kinds of information to consume in order to break the chain of negativity. I’m a developer so I thought, why not create an application that’ll select only positive news and remove negative and neutral ones for me?

看到这一点之后,我决定我可以选择使用哪种类型的信息,以打破负面影响的链条。 我是一名开发人员,所以我想,为什么不创建一个只选择正面新闻并为我删除负面和中立新闻的应用程序?

With recent advances in natural language processing (NLP) and mobile processing, we can select, with a certain level of accuracy, the most positive news and create our own custom feeds.

随着自然语言处理(NLP)和移动处理技术的最新发展,我们可以选择具有一定准确性的最正面新闻,并创建自己的自定义供稿。

In this article, I’ll create an iOS application that will consume an API and select the most positive articles.

在本文中,我将创建一个iOS应用程序,该应用程序将使用API​​并选择最积极的文章。

总览 (Overview)

  1. Find the right news API

    找到正确的新闻API
  2. Create our iOS application

    创建我们的iOS应用程序
  3. Create a decodable to parse the API calls

    创建可解码以解析API调用
  4. Customize the feed view

    自定义提要视图
  5. Final results and possible improvements

    最终结果和可能的改进

I have included code in this article where it’s most instructive. Full code and data can be found on my GitHub page. Let’s get started.

我在本文中包含了最具启发性的代码。 完整的代码和数据可以在我的GitHub页面找到 。 让我们开始吧。

看一下最终结果是什么样的: (This is a look at what the final result will look like:)

Image for post
Figure 3: final result
图3:最终结果

找到正确的新闻API (Find the right news API)

In order to get a stream of articles, we need to find a good API that will get us articles from various sources. These articles will be used to create our custom news feed. The simplest one is News API — you can customize the API calls and get articles related to a specific country or/and a specific topic.

为了获得文章流,我们需要找到一个好的API,可以从各种来源获得文章。 这些文章将用于创建我们的自定义新闻提要。 最简单的一种是News API ,您可以自定义API调用并获取与特定国家/地区和/或特定主题相关的文章。

I chose to get top and breaking news headlines from the United States curated in an API called “Top headlines from the United States”, but you can choose whatever topic interests you.

我选择从“美国的头条新闻” API中挑选美国的头条新闻和突发新闻头条,但您可以选择自己感兴趣的主题。

You do need to create an account to get an apiKey, and the rest is pretty straightforward. You choose the “News sources” and the subcategory, and the website will then generate a GET URL with the appropriate key and news sources.

您确实需要创建一个帐户来获取apiKey ,其余的都非常简单。 您选择“新闻来源”和子类别,然后网站将生成带有适当的键和新闻来源的GET URL。

You can easily test your link in your browser and understand the structure of the API call:

您可以在浏览器中轻松测试链接,并了解API调用的结构:

Image for post
Figure 4: API request status
图4:API请求状态

The API call is structured as such:

API调用的结构如下:

  • error: Indicates whether the request was successful or not—“ok” for a successful request, and an “error” for a problem.

    error :指示请求是否成功-成功请求为“ ok”,问题为“ error”。

  • totalResults: Number of articles

    totalResults :文章数

  • articles: An array of articles

    articles :一系列文章

Image for post
Figure 5: news article API structure
图5:新闻文章API结构

创建我们的iOS应用程序 (Create our iOS application)

Create a new “Single View Application” and make sure you choose Storyboard as User Interface.

创建一个新的“单视图应用程序”,并确保您选择情节提要作为用户界面。

Image for post
Figure 6: create a new iOS project
图6:创建一个新的iOS项目

Now we have our project ready to go. I don’t like using storyboards myself, so the app in this tutorial is built programmatically, which means no buttons or switches to toggle — just pure code.

现在,我们的项目已准备就绪。 我不喜欢自己使用情节提要板,因此本教程中的应用程序是通过编程方式构建的,这意味着没有按钮或开关可切换-只是纯代码。

To follow this method, you’ll have to delete the main.storyboard file and set your SceneDelegate.swift file (Xcode 11 only).

要遵循此方法,您必须删除main.storyboard文件并设置SceneDelegate.swift文件(仅Xcode 11)。

With Xcode 11, you’ll have to change the Info.plist file like so:

使用Xcode 11,您必须像这样更改Info.plist文件:

Image for post
Figure 7: delete the Storyboard Name from the .plist file
图7:从.plist文件中删除情节提要名称

You need to delete the “Storyboard Name” in the file, and that’s about it.

您需要删除文件中的“故事板名称”,仅此而已。

Change the SceneDelegate with the following code:

使用以下代码更改SceneDelegate

创建视图控制器 (Create View Controllers)

We need two ViewControllers:

我们需要两个ViewController:

  • ViewController():

    ViewController()

This is where we’ll set our UICollectionView with all the articles retrieved from the news API.

在这里,我们将使用从新闻API检索到的所有文章来设置UICollectionView

  • DetailsViewController():

    DetailsViewController()

This is where we will show the article’s body.

这是我们将显示文章正文的地方。

创建导航 (Create a navigation)

  • MainTabBarController():

    MainTabBarController()

This is our main navigation, where we’ll create the full navigation structure for our application.

这是我们的主要导航,在这里我们将为应用程序创建完整的导航结构。

Navigation in iOS is pretty straightforward and easy to implement. Here, I’ve changed some things like the color and icon for the navigation bar (and others) so it looks nice.

iOS中的导航非常简单且易于实现。 在这里,我更改了一些内容,例如导航栏(和其他)的颜色和图标,因此看起来不错。

AI-powered mobile apps sound exciting…but how do they work, and how can they help scale your business? Subscribe to the Fritz AI Newsletter for answers to these questions and more.

基于AI的移动应用程序听起来令人兴奋……但是它们如何工作以及如何帮助您扩展业务? 订阅Fritz AI新闻通讯,以获取这些问题的答案以及更多信息。

创建可解码以解析API调用 (Create a decodable to parse the API calls)

Starting with Swift 4, we can create a representation of an API call using a struct and conforming it to the Decodable protocol. The protocol only works when you read JSON data.

从Swift 4开始,我们可以使用结构创建API调用的表示并将其遵循Decodable协议。 该协议仅在您读取JSON数据时有效。

The API returns a series of elements that could be parsed using two important structures. The first one will mimic the API call upper node with a status, totalResult, and finally articles, which is an array of articles. The other one will abstract a representation of an article, and thus will be used to create the array of articles.

该API返回一系列可以使用两个重要结构进行解析的元素。 第一个将模拟一个API调用高层节点,其statusstatustotalResult ,最后是articles ,后者是一系列文章。 另一个将抽象化文章的表示形式,从而将其用于创建文章数组。

Here the structure of the Article struct:

这里Article结构的结构:

Now that we have defined the properties of an Article , we create the ultimate API call object Articles:

现在,我们已经定义了Article的属性,我们将创建最终的API调用对象Articles

Both structures conform to the Decodable protocol. And the former is using the first one to create an array of Article. Make sure that the properties' names are the exact same as the API call.

两种结构均符合可Decodable协议。 前者正在使用第一个来创建一个Article数组。 确保属性名称与API调用完全相同。

自定义提要视图 (Customize the feed view)

Next we will need to customize our feed by adding a UICollectionView that will host our articles.

接下来,我们需要通过添加将托管我们的文章的UICollectionView来定制我们的提要。

Create a UICollectionView :

创建一个 UICollectionView

The news feed will have a stream of articles, we will use UICollectionView() that will be instantiated in ViewController() with the following code:

新闻提要中将包含一系列文章,我们将使用UICollectionView() ,该UICollectionView()将在ViewController()通过以下代码实例化:

  • Create an object of type UICollectionView()

    创建一个UICollectionView()类型的对象

  • Set the scroll direction

    设置滚动方向
  • Change the background color

    更改背景颜色
  • Toggle the Collection View to be constrained using auto layout

    切换要使用自动布局约束的“收藏夹视图”

Then, we need to register the cells and set the data source, as well as set up the ViewController() to conform to the UICollectionView() protocol:

然后,我们需要注册单元格并设置数据源,并设置ViewController()以符合UICollectionView()协议:

Finally, we need to add the UICollectionView to the subview and set up the layout:

最后,我们需要将UICollectionView添加到子视图并设置布局:

  • Add the collection to the subview of the UIViewController()

    将集合添加到UIViewController()的子视图中

  • Change the background color to be compatible with Dark Mode

    更改背景颜色以与黑暗模式兼容

The final step, which is the conformance to UICollectionViewDataSource and UICollectionViewDelegate, is available in the GitHub repository. In this part we will feed the collection view with the data.

GitHub存储库中提供了最后一步,即符合UICollectionViewDataSourceUICollectionViewDelegate 。 在这一部分中,我们将为数据提供收集视图。

Create a custom UICollectionViewCell :

创建一个自定义 UICollectionViewCell

The collection is made up of cells that are members of the feed, think of it as Medium’s homepage, UICollectionViewCell is an instance of an article, and the homepage is the UICollectionView — each cell will have a title, author name and will also lead to the full article. Thus, the homepage is a ‘Collection’ of articles.

该集合由作为提要成员的单元格组成,将其视为Medium的主页, UICollectionViewCell是文章的实例,而主页是UICollectionView -每个单元格将具有标题,作者名称,并且还会导致全文。 因此,主页是文章的“集合”。

I’m using a package made by Paolo Cuscela called Cards that mimics the iOS app store.

我正在使用Paolo Cuscela制作的名为Cards的软件包,该软件包模仿了iOS应用商店。

For the sake of simplicity, I manually included the files in the project and created a new Class that conforms to the CardDelegate protocol. The Class is also included in the GitHub repository.

为了简单起见,我手动将文件包括在项目中,并创建了一个符合CardDelegate协议的新类。 该类也包含在GitHub存储库中

Image for post
Figure 9: custom Card design
图9:定制卡设计

Here’s a breakdown of the CustomCell() our UICollectionViewCell() :

这是CustomCell()CustomCell()UICollectionViewCell()

  • First, we need to instantiate an object of type CardArticle which will be the design structure of the cell

    首先,我们需要实例化CardArticle类型的对象,该对象将是单元的设计结构

  • Then an object of type Article that contains the data

    然后是包含数据的Article类型的对象

  • Create an initializer where we initialize the Card and the Article object

    创建一个初始化程序,在此初始化Card和Article对象
  • Create a function that will set up the Card’s bounds and attributes (title, author, background color, text color and many more)

    创建一个函数来设置卡的边界和属性(标题,作者,背景颜色,文本颜色等等)
  • Finally, we need to override an important function that gets invoked every time a cell is reused by the UICollectionView() . This function exists to improve the efficiency and the performance of the feed. Thus, when a cell is not visible on the screen, the collection view dequeues it and remove it from the stack.

    最后,我们需要重写一个重要函数,每次UICollectionView()重用单元时,该函数都会被调用。 存在此功能以提高进纸的效率和性能。 因此,当一个单元格在屏幕上不可见时,收集视图将其出队,并将其从堆栈中移除。

预测并填充提要 (Predict and populate the feed)

Since iOS 13, Apple has included in its NaturalLanguage framework the ability to leverage a built-in solution without any external resource.

从iOS 13开始,Apple在其NaturalLanguage框架中包括无需任何外部资源即可利用内置解决方案的功能。

This feature, more broadly, is known as sentiment analysis, and it gives you the power to access the general sentiment in a given word, sentence, paragraph, or document. The sentiment score is structured as a float number that can range from -1.0 to 1.0. A score of 1.0 is the most positive, a score of -1.0 is the most negative, and a score of 0.0 is neutral.

广义上来说,此功能称为情感分析 ,它使您能够访问给定单词,句子,段落或文档中的一般情感。 情绪得分的结构为浮动数字,范围为-1.01.0 。 分数1.0是最正的,分数-1.0是最负的,分数0.0是中性的。

Since we only want positive text, we’ll only surface articles that have a score strictly above 0.

由于我们只需要肯定的文本,因此我们只会列出分数严格高于0的文章

Here’s a break down of the code:

以下是代码分解:

  • Instantiate a NLTagger and choose sentimentScore as an option.

    实例化一个NLTagger并选择sentimentScore作为选项。

  • Set the object’s string by passing the input text.

    通过传递输入文本来设置对象的字符串。
  • Run inference by calling the method tag(), specifying that the text is a paragraph for better prediction.

    通过调用方法tag()来运行推理,指定文本是一段以便更好地进行预测。

  • Parse the output as a Double.

    将输出解析为Double

  • Test the output and set the final score if the text is positive (1), negative (0) or neutral (-1).

    如果文本为正数( 1 ),负数( 0 )或中性( -1 ),请测试输出并设置最终分数。

Before loading the CollectionView, we’ll run inference on each and every article’s text.

在加载CollectionView之前,我们将对每篇文章的文本进行推断。

最终结果和可能的改进 (Final results and possible improvements)

The application calls an API and only shows the most positive articles. Unfortunately, the News API is not free and only returns a portion of articles. Thus, there are a number of possibilities for improving the overall experience by adding or modifying the following elements:

该应用程序调用API,仅显示最积极的文章。 不幸的是,News API不是免费的,只能返回部分文章。 因此,通过添加或修改以下元素,存在许多改善整体体验的可能性:

  • Create your own API by scraping and parsing your own favorite news outlet, which will help you customize your feed even more.

    通过抓取和解析自己喜欢的新闻媒体来创建自己的API,这将帮助您进一步自定义Feed。
  • Create your own custom NLP model using state-of-the-art architectures such as Transformer GPT-2 or BERT. In these cases, the model will perform the inference on the server-side rather than on-device. I wrote an article that can help you get started with sentiment analysis using Transformers.

    使用最新的架构(例如Transformer GPT-2或BERT)创建自己的自定义NLP模型。 在这些情况下,模型将在服务器端而不是在设备上执行推理。 我写了一篇文章,可以帮助您开始使用Transformers进行情感分析

  • Improve the overall experience by running inference in backend while scraping and parsing articles.

    通过在后端抓取和解析文章时进行推断来改善总体体验。
  • Add a section for the most important and breaking news articles in order to stay up to date.

    添加有关最重要和最新新闻文章的部分,以保持最新状态。
  • Setup a notification system in order to receive intermittent news alerts.

    设置通知系统以接收间歇性的新闻警报。
  • Add a share functionality to spread positivity around you 😃

    添加共享功能以在您周围传播积极性😃

The Internet is full of positive news, you just need to search harder on the various news sites and you will find good news. By using your coding skills you can leverage the power of ML and programming and totally automate the process. The news feed can also cover subjects that you deem important, as long as the news fits your own expectations.

互联网上充满了积极的新闻,您只需要在各个新闻站点上加倍搜索,就会发现好消息。 通过使用您的编码技能,您可以利用ML和编程的力量,并使流程完全自动化。 只要新闻符合您自己的期望,新闻提要也可以涵盖您认为重要的主题。

Thanks for reading this article. If you have any questions, don’t hesitate to send me an email at omarmhaimdat@gmail.com.

感谢您阅读本文。 如有任何疑问,请随时发送电子邮件至omarmhaimdat@gmail.com

This project is available to download from my GitHub account:

该项目可以从我的GitHub帐户下载:

Editor’s Note: Heartbeat is a contributor-driven online publication and community dedicated to exploring the emerging intersection of mobile app development and machine learning. We’re committed to supporting and inspiring developers and engineers from all walks of life.

编者注: 心跳 是由贡献者驱动的在线出版物和社区,致力于探索移动应用程序开发和机器学习的新兴交集。 我们致力于为各行各业的开发人员和工程师提供支持和启发。

Editorially independent, Heartbeat is sponsored and published by Fritz AI, the machine learning platform that helps developers teach devices to see, hear, sense, and think. We pay our contributors, and we don’t sell ads.

Heartbeat在编辑上是独立的,由以下机构赞助和发布 Fritz AI ,一种机器学习平台,可帮助开发人员教设备看,听,感知和思考。 我们向贡献者付款,并且不出售广告。

If you’d like to contribute, head on over to our call for contributors. You can also sign up to receive our weekly newsletters (Deep Learning Weekly and the Fritz AI Newsletter), join us on Slack, and follow Fritz AI on Twitter for all the latest in mobile machine learning.

如果您想做出贡献,请继续我们的 呼吁捐助者 您还可以注册以接收我们的每周新闻通讯(《 深度学习每周》 和《 Fritz AI新闻通讯》 ),并加入我们 Slack ,然后关注Fritz AI Twitter 提供了有关移动机器学习的所有最新信息。

翻译自: https://heartbeat.fritz.ai/build-a-positive-news-ios-application-using-the-power-of-machine-learning-dfabc2d598be

ios 机器学习

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值